class TextFieldPanel(JPanel, FocusListener):
    __metaclass__ = Singleton

    def __init__(self):
        super(TextFieldPanel, self).__init__()
        self._text_field = None

    def focusGained(self, event):
        pass

    def focusLost(self, event):
        Application.get_instance().execute(
            SetDomainDictValueCommand(
                self._get_domain_dict_type(), self._get_domain_dict_key(),
                InfrastructureHelpers.split(self._text_field.getText())))

    def display(self, values):
        self._prepare_components(values)

    def _prepare_components(self, values):
        self._text_field = JTextField()
        self._text_field.setColumns(30)
        self._text_field.setEditable(True)
        self._text_field.setText(
            InfrastructureHelpers.join(values[self._get_domain_dict_key()]))
        self._text_field.addFocusListener(self)
        self.add(self._text_field)
예제 #2
0
class DatabasePanel(JPanel, ActionListener):
    __metaclass__ = Singleton

    def __init__(self):
        super(DatabasePanel, self).__init__()
        self._button = None
        self._text_field = None

    def actionPerformed(self, event):
        database_path = UIHelpers.choose_file()
        if database_path:
            if Application.get_instance().execute(
                    SetDomainDictValueCommand(
                        SetDomainDictValueCommand.TYPE_PERSISTENCE,
                        'database_path', database_path)):
                self._text_field.setText(database_path)

    def display(self, values):
        self._prepare_components(values)

    def _prepare_components(self, values):
        self._text_field = JTextField()
        self._text_field.setColumns(30)
        self._text_field.setEditable(False)
        self._text_field.setText(values['database_path'])
        self.add(self._text_field)
        button = JButton('Save as...')
        button.addActionListener(self)
        self.add(button)
예제 #3
0
class PTTextField(JPanel):

    def getName(self):
        return self._name

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

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

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

        length = 1000
        self._name = name
        self._label = JLabel(label)
        self._textfield = JTextField(length) \
            if function is None \
            else JTextField(length, actionPerformed=function)
        self.add(self._label)
        self.add(self._textfield)
        if button1 is not None:
            self._button1 = button1
            self.add(self._button1)
        if button2 is not None:
            self._button2 = button2
            self.add(self._button2)
        self.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self._textfield.setText("0" * length)
        self._textfield.setMaximumSize(self._textfield.getPreferredSize())
        self.setMaximumSize(self.getPreferredSize())
        self.setText(text)
        self.setLayout(BoxLayout(self, BoxLayout.X_AXIS))
예제 #4
0
class TagPanel(JPanel, DocumentListener):
    __metaclass__ = Singleton

    def __init__(self):
        super(TagPanel, self).__init__()
        self._text_field = None

    def changeUpdate(self, event):
        self._update()

    def insertUpdate(self, event):
        self._update()

    def removeUpdate(self, event):
        self._update()

    def display(self, values):
        self.add(JLabel('<html><b>Tags:</b></html>'))
        self._text_field = JTextField()
        self._text_field.setColumns(20)
        self._text_field.setEditable(True)
        self._text_field.setText(InfrastructureHelpers.join(values['tags']))
        self._text_field.getDocument().addDocumentListener(self)
        self.add(self._text_field)

    def _update(self):
        Application.get_instance().execute(SetDomainDictValueCommand(
            SetDomainDictValueCommand.TYPE_VISIBLE_ITEMS,
            'tags',
            InfrastructureHelpers.split(self._text_field.getText())
        ))
예제 #5
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with "+person.name)
        self.display = JTextArea(columns=100,
                                 rows=15,
                                 editable=0,
                                 lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n"+self.person.client.name+": "+text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n"+self.person.name+": "+text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with "+newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
예제 #6
0
class HumanDetailPanel(DetailPanel):
    """ generated source for class HumanDetailPanel """
    moveTable = JZebraTable()
    moveTextField = JTextField()
    selectButton = JButton()
    selection = Move()
    timerBar = JTimerBar()

    def __init__(self):
        """ generated source for method __init__ """
        super(HumanDetailPanel, self).__init__(GridBagLayout())
        model = DefaultTableModel()
        model.addColumn("Legal Moves")
        self.moveTable = JZebraTable(model)
        self.selectButton = JButton(selectButtonMethod())
        self.moveTextField = JTextField()
        self.timerBar = JTimerBar()
        self.selection = None
        self.moveTable.setShowHorizontalLines(True)
        self.moveTable.setShowVerticalLines(True)
        self.moveTextField.setEditable(False)
        self.add(JScrollPane(self.moveTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.add(self.selectButton, GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 0, 0))
        self.add(self.moveTextField, GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.add(self.timerBar, GridBagConstraints(0, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))

    @overloaded
    def observe(self, event):
        """ generated source for method observe """
        if isinstance(event, (HumanNewMovesEvent, )):
            self.observe(event)
        elif isinstance(event, (HumanTimeoutEvent, )):
            self.observe(event)
        elif isinstance(event, (PlayerTimeEvent, )):
            self.observe(event)

    @observe.register(object, HumanNewMovesEvent)
    def observe_0(self, event):
        """ generated source for method observe_0 """
        model = self.moveTable.getModel()
        model.setRowCount(0)
        for move in event.getMoves():
            model.addRow([None]*)
        self.selection = event.getSelection()
        self.moveTextField.setText(self.selection.__str__())

    @observe.register(object, HumanTimeoutEvent)
    def observe_1(self, event):
        """ generated source for method observe_1 """
        event.getHumanPlayer().setMove(self.selection)

    @observe.register(object, PlayerTimeEvent)
    def observe_2(self, event):
        """ generated source for method observe_2 """
        self.timerBar.time(event.getTime(), 500)

    def selectButtonMethod(self):
        """ generated source for method selectButtonMethod """
        return AbstractAction("Select")
예제 #7
0
class PrefsPanel(JPanel):
    """JPanle with gui for tool preferences
    """
    def __init__(self, app):
        strings = app.strings

        self.setLayout(GridLayout(3, 2, 5, 5))
        userLbl = JLabel(strings.getString("osmose_pref_username"))
        self.userTextField = JTextField(20)
        self.userTextField.setToolTipText(
            strings.getString("osmose_pref_username_tooltip"))

        levelLbl = JLabel(strings.getString("osmose_pref_level"))
        self.levels = ["1", "1,2", "1,2,3", "2", "3"]
        self.levelsCombo = JComboBox(self.levels)
        self.levelsCombo.setToolTipText(
            strings.getString("osmose_pref_level_tooltip"))

        limitLbl = JLabel(strings.getString("osmose_pref_limit"))
        self.limitTextField = JTextField(20)
        self.limitTextField.setToolTipText(
            strings.getString("osmose_pref_limit_tooltip"))

        self.add(userLbl)
        self.add(self.userTextField)
        self.add(levelLbl)
        self.add(self.levelsCombo)
        self.add(limitLbl)
        self.add(self.limitTextField)

    def update_gui(self, preferences):
        """Update preferences gui
        """
        self.userTextField.setText(preferences["username"])
        self.levelsCombo.setSelectedIndex(
            self.levels.index(preferences["level"]))
        self.limitTextField.setText(str(preferences["limit"]))

    def read_gui(self):
        """Read preferences from gui
        """
        username = self.userTextField.getText()
        level = self.levelsCombo.getSelectedItem()
        limit = self.limitTextField.getText()
        try:
            limit = Integer.parseInt(limit)
            if limit > 500:
                limit = 500
            limit = str(limit)
        except NumberFormatException:
            limit = ""

        preferences = {
            "username": username.strip(),
            "level": level,
            "limit": limit
        }
        return preferences
예제 #8
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with " + person.name)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n" + self.person.client.name + ": " + text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n" + self.person.name + ": " + text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with " + newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
예제 #9
0
def makeUI(model):
    # Components:
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    if base_path is not None:
        base_path_field.setText(base_path)
    # Panel for all components
    all = JPanel()
    all.setBorder(EmptyBorder(20, 20, 20, 20))
    layout, c = GridBagLayout(), GC()
    all.setLayout(layout)
    # First row: label and regex text field
    add(all, regex_label, gridx=0, gridy=0)  # with default constraints
    add(all, regex_field, gridx=1, gridy=0, fill=GC.HORIZONTAL, weightx=1.0)
    # Second row: the table
    add(all,
        jsp,
        gridx=0,
        gridy=1,
        fill=GC.BOTH,
        gridwidth=2,
        weightx=1.0,
        weighty=1.0)  # full weights so it stretches when resizing
    # Third row: the base path
    add(all, base_path_label, gridx=0, gridy=2)
    add(all,
        base_path_field,
        gridx=1,
        gridy=2,
        fill=GC.HORIZONTAL,
        weightx=1.0)
    # Window frame
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    #frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table))
    table.addMouseListener(RowClickListener(base_path_field))
    al = ArrowListener(table, regex_field)
    table.addKeyListener(al)
    regex_field.addKeyListener(al)
    # Instead of a KeyListener, use the input vs action map
    table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                            "enter")
    table.getActionMap().put("enter", OpenImageFromTableCell())
    #
    return model, table, regex_field, frame
예제 #10
0
class consoleTimeout1( java.lang.Runnable ) :

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Build and display our graphical application
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run( self ) :
        frame = JFrame(
           'Console timeout',
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        #-----------------------------------------------------------------------
        # The frame (i.e., it's ContentPane) should use a vertically aligned
        # BoxLayout layout manager (i.e., along the Y_AXIS)
        #-----------------------------------------------------------------------
        cp = frame.getContentPane()
        cp.setLayout( BoxLayout( cp, BoxLayout.Y_AXIS ) )

        #-----------------------------------------------------------------------
        # The JTextField will be preceeded, and followed by JLabel components
        # identifying the value being displayed, and the associated time units.
        # However, we want them displayed horizontally, so we put them into a
        # single JPanel instance using a FlowLayout layout manager
        #-----------------------------------------------------------------------
        input = JPanel( layout = FlowLayout() )
        input.add( JLabel( 'Timeout:' ) )
        self.text = JTextField( 3, actionPerformed = self.update )
        input.add( self.text )
        self.text.setText( getTimeout() )
        input.add( JLabel( 'minutes' ) )
        cp.add( input )

        #-----------------------------------------------------------------------
        # Then, we add a message area beneath
        #-----------------------------------------------------------------------
        self.msg  = cp.add( JLabel() )

        frame.setSize( 290, 100 )
        frame.setVisible( 1 )

    #---------------------------------------------------------------------------
    # Name: update()
    # Role: TextField event handler - invoked when user presses <Enter>
    #---------------------------------------------------------------------------
    def update( self, event ) :
        value = self.text.getText().strip()
        if re.search( '^\d+$', value ) :
            self.msg.setText( setTimeout( value ) )
        else :
            msg = 'Invalid value "%s" ignored.' % value
            self.msg.setText( msg )
            self.text.setText( getTimeout() )
예제 #11
0
class javadocInfo_02(java.lang.Runnable):

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Instantiate the user class
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run(self):
        frame = JFrame('javadocInfo_02',
                       locationRelativeTo=None,
                       size=(350, 225),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        model = DefaultListModel()
        model.addElement('One moment please...')
        self.List = JList(model,
                          valueChanged=self.pick,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        frame.add(JScrollPane(self.List), BorderLayout.CENTER)
        self.msg = JTextField()
        frame.add(self.msg, BorderLayout.SOUTH)
        self.Links = {}
        soupTask(
            self.List,  # The visible JList instance
            self.msg,  # The message area (JTextField)
            JAVADOC_URL,  # Remote web page URL to be processed
            self.Links  # Dictionary of links found
        ).execute()
        frame.setVisible(1)

    #---------------------------------------------------------------------------
    # Name: pick()
    # Role: ListSelectionListener event handler
    #---------------------------------------------------------------------------
    def pick(self, e):
        #-----------------------------------------------------------------------
        # Note: Ignore valueIsAdjusting events
        #-----------------------------------------------------------------------
        if not e.getValueIsAdjusting():
            List = self.List
            model = List.getModel()
            #-------------------------------------------------------------------
            # Ignore events for initial "One moment please..." list
            #-------------------------------------------------------------------
            if model.getSize() > 1:
                #---------------------------------------------------------------
                # Is an item selected, or not?
                #---------------------------------------------------------------
                index = List.getSelectedIndex()
                if index > -1:
                    choice = model.elementAt(index)
                    self.msg.setText(self.Links[choice])
                else:
                    self.msg.setText('Make a selection')
예제 #12
0
class PrefsPanel(JPanel):
    """JPanle with gui for tool preferences
    """
    def __init__(self, app):
        strings = app.strings

        self.setLayout(GridLayout(3, 2, 5, 5))
        userLbl = JLabel(strings.getString("osmose_pref_username"))
        self.userTextField = JTextField(20)
        self.userTextField.setToolTipText(strings.getString("osmose_pref_username_tooltip"))

        levelLbl = JLabel(strings.getString("osmose_pref_level"))
        self.levels = ["1", "1,2", "1,2,3", "2", "3"]
        self.levelsCombo = JComboBox(self.levels)
        self.levelsCombo.setToolTipText(strings.getString("osmose_pref_level_tooltip"))

        limitLbl = JLabel(strings.getString("osmose_pref_limit"))
        self.limitTextField = JTextField(20)
        self.limitTextField.setToolTipText(strings.getString("osmose_pref_limit_tooltip"))

        self.add(userLbl)
        self.add(self.userTextField)
        self.add(levelLbl)
        self.add(self.levelsCombo)
        self.add(limitLbl)
        self.add(self.limitTextField)

    def update_gui(self, preferences):
        """Update preferences gui
        """
        self.userTextField.setText(preferences["username"])
        self.levelsCombo.setSelectedIndex(self.levels.index(preferences["level"]))
        self.limitTextField.setText(str(preferences["limit"]))

    def read_gui(self):
        """Read preferences from gui
        """
        username = self.userTextField.getText()
        level = self.levelsCombo.getSelectedItem()
        limit = self.limitTextField.getText()
        try:
            limit = Integer.parseInt(limit)
            if limit > 500:
                limit = 500
            limit = str(limit)
        except NumberFormatException:
            limit = ""

        preferences = {"username": username.strip(),
                       "level": level,
                       "limit": limit}
        return preferences
예제 #13
0
    def output(self, value):
        #url = "https://dict.leo.org/englisch-deutsch/dog"
        #import urllib.request
        #with urllib.request.urlopen(url) as response:
        #html = response.read()
        #with open("leoausgabe.txt","w") as f:
        #f.write(str(html))
        t = ''

        frame = JFrame(
            'Lektion erstellen',
            defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
            size=(500, 500),
        )

        def change_text(event):
            text = feld.getText()
            name = feld2.getText() + ".csv"
            with open(name, "w") as f:
                f.write(text)
                #print(name + " gespeichert")
            #print(text)
            t = text
            self.send(t)
            #return(t)

        button = JButton('Lektion speichern!',
                         actionPerformed=change_text,
                         size=(10, 20))
        button.setBounds(20, 40, 20, 40)
        pnl = JPanel()
        pnl.setLayout(BoxLayout(pnl, BoxLayout.Y_AXIS))
        feld = JTextArea()
        feld.editable = True

        feld.setText("Deutsch,Englisch\n")
        feld2 = JTextField()
        feld2.setText("Ersetzen durch Namen der Lektion")
        pnl.add(feld2)
        pnl.add(feld)
        pnl.add(button)
        frame.add(pnl)
        frame.setVisible(True)

        #change_text(value)
        print(t)

        print "Lektion erstellt"
예제 #14
0
    def gui(self):

        # Hilfsfunktion für event
        # erstellt ein Rezeptobjekt anhand einer URL
        # schließt die GUI
        def create(event):
            url = field.getText()
            self.recipe = Recipe(url)
            frame.dispose()
            print("created recipe for " + self.recipe.get_title())
            # der Dialog wartet, bis "continue" gesendet wird
            self.send("continue")

        # Frame erstellen
        frame = JFrame(
            'URL eingeben',
            defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
            size=(480, 200),
        )
        frame.setLayout(None)

        # Text im Frame
        fieldlabel = JLabel()
        fieldlabel.setText(
            "<html><font size=+1>Geben Sie die Internetadresse des Rezepts ein</font></html>"
        )
        fieldlabel.setBounds(20, 20, 500, 40)
        frame.add(fieldlabel)

        # Textfeld im Frame
        field = JTextField()
        field.setText("https://www.chefkoch.de/rezepte/...")
        field.setBounds(20, 60, 411, 40)
        frame.add(field)

        # Button im Frame
        # ruft Hilfsfunktion create auf
        button = JButton("Los!", actionPerformed=create)
        button.setBounds(155, 100, 150, 30)
        frame.add(button)

        #Frame anzeigen
        frame.setVisible(True)
def getGUI(sym_dict):
	global frame, outCheckbox, fillCheckbox, slider, colorTF, widthTF
	frame = JFrame("Border Symbology", defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE, 
		       bounds=(100, 100, 450, 200), layout=FlowLayout(), resizable=0)

	colorL = JLabel('Color: ')
	colorTF = JTextField(20)
	color = sym_dict["color"]
	color = Color(color.getRed(), color.getGreen(), color.getBlue(), sym_dict["alpha"])
	colorTF.setBackground(color)
	colorTF.setText(color.toString())

	colorB = JButton('...', actionPerformed=colorChooser)
	frame.add(colorL)
	frame.add(colorTF)
	frame.add(colorB)

	widthL = JLabel('Width: ')
	widthTF = JTextField(3)
	widthTF.setText(str(sym_dict["width"]))
	frame.add(widthL)
	frame.add(widthTF)

	alphaL = JLabel('Transparency: ')
	frame.add(alphaL)

	# Create a horizontal slider with min=0, max=100, value=50
	slider = JSlider()
	slider.setPreferredSize(Dimension(200, 50))
	slider.setValue(sym_dict["alpha"]*100/255)
	slider.setMajorTickSpacing(25)
	slider.setMinorTickSpacing(5)
	slider.setPaintTicks(1)
	slider.setPaintLabels(1)

	applyButton = JButton("Apply", actionPerformed=action)
	acceptButton = JButton("Accept", actionPerformed=accept)

	frame.add(slider)
	frame.add(applyButton)
	frame.add(acceptButton)

	frame.show()
예제 #16
0
파일: gui.py 프로젝트: LSTANCZYK/Ignition
def inputBox(message, defaultText=None):
    """Opens up a popup input dialog box.

    This dialog box will show a prompt message, and allow the user to
    type in a string. When the user is done, they can press "OK" or
    "Cancel". If OK is pressed, this function will return with the value
    that they typed in. If Cancel is pressed, this function will return
    the value None.

    Args:
        message (str): The message to display for the input box. Will
            accept html formatting.
        defaultText (str): The default text to initialize the input box
            with. Optional.

    Returns:
        str: The string value that was entered in the input box.
    """
    options = ["OK", "Cancel"]

    panel = JPanel()
    label = JLabel("{}: ".format(message))
    panel.add(label)
    text_field = JTextField(25)
    text_field.setText(defaultText)
    panel.add(text_field)

    choice = JOptionPane.showOptionDialog(
        None,
        panel,
        "Input",
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        None,
        options,
        options[0],
    )

    return text_field.getText() if choice == JOptionPane.OK_OPTION else None
예제 #17
0
class EditSettingsView(JDialog):
    def __init__(self, controller, working_dir, servers, console_style,
                 edit_area_style, keystrokes, languages, projects):
        self.logger = logging.getLogger("NammuController")
        self.setAlwaysOnTop(True)
        self.controller = controller
        self.working_dir = working_dir
        self.servers = servers
        self.keystrokes = keystrokes
        self.languages = languages
        self.projects = projects
        self.console_fontsize = console_style['fontsize']['user']
        self.console_font_color = console_style['font_color']['user']
        self.console_bg_color = console_style['background_color']['user']
        self.edit_area_fontsize = edit_area_style['fontsize']['user']
        self.pane = self.getContentPane()

        # Grab the console color options from the console view
        self.consoleView = self.controller.controller.consoleController.view
        self.color_options = self.consoleView.colors.keys()

    def build(self):
        '''
        Create all tab panels and put together to form the settings window.
        '''
        self.setLayout(BorderLayout())
        self.add(self.build_tabbed_panel(), BorderLayout.CENTER)
        self.add(self.build_buttons_panel(), BorderLayout.SOUTH)

    def build_tabbed_panel(self):
        '''
        Build panel with tabs for each of the settings editable sections.
        '''
        tabbed_pane = JTabbedPane()
        tab_titles = [
            "General", "Appearance", "Keystrokes", "Languages", "Projects"
        ]
        for title in tab_titles:
            panel = self.build_settings_panel(title.lower())
            tabbed_pane.addTab(title, panel)
        return tabbed_pane

    def build_settings_panel(self, text):
        '''
        Call correspondent method to create panel for given tab text.
        '''
        panel = getattr(self, "build_{}_panel".format(text))()
        return panel

    def build_general_panel(self):
        '''
        Create the panel that'll go in the General tab. This should contain
        options for choosing which server to use for validation as well as
        default working dir.
        '''
        panel = JPanel(GridBagLayout())
        constraints = self.add_constraints(GridBagConstraints(),
                                           insets=Insets(10, 10, 10, 10))
        self.build_working_dir_panel(constraints, panel)
        self.build_servers_panel(constraints, panel)
        return panel

    def add_constraints(self,
                        constraints,
                        weightx=None,
                        gridx=None,
                        gridy=None,
                        fill=None,
                        insets=None,
                        gridwidth=None,
                        anchor=None):
        '''
        Wrapper around the various constraints we need to set.
        '''
        # Cant use pythonic truth value test as we need 0 to evaluate as true
        if weightx is not None:
            constraints.weightx = weightx
        if gridx is not None:
            constraints.gridx = gridx
        if gridy is not None:
            constraints.gridy = gridy
        if fill is not None:
            constraints.fill = fill
        if insets is not None:
            constraints.insets = insets
        if gridwidth is not None:
            constraints.gridwidth = gridwidth
        if anchor is not None:
            constraints.anchor = anchor

        return constraints

    def build_working_dir_panel(self, constraints, panel):
        '''
        Working directory row: label + field + button
        This is for users to browse for their preferred default directory
        when opening/creating a new file.
        '''
        working_dir_label = JLabel("Working directory:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.30,
                                           gridx=0,
                                           gridy=0,
                                           anchor=GridBagConstraints.EAST)

        panel.add(working_dir_label, constraints)

        self.wd_field = JTextField()
        self.wd_field.setEditable(False)
        # Can't find an elegant way to default to something that would be
        # crossplatform, and I can't leave the default field empty.
        if self.working_dir['default'] != "None":
            self.wd_field.setText(self.working_dir['default'])
        else:
            self.wd_field.setText(os.getcwd())

        constraints = self.add_constraints(constraints,
                                           weightx=0.60,
                                           gridx=1,
                                           gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL,
                                           insets=Insets(10, 10, 10, 5))
        panel.add(self.wd_field, constraints)

        constraints.fill = 0
        button = JButton("Browse", actionPerformed=self.browse)
        constraints = self.add_constraints(constraints,
                                           weightx=0.10,
                                           gridx=2,
                                           gridy=0,
                                           insets=Insets(10, 0, 10, 10))
        panel.add(button, constraints)

    def build_console_background_color_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        console_bg_label = JLabel("Console background color:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.30,
                                           gridx=0,
                                           gridy=2)
        panel.add(console_bg_label, constraints)

        self.bg_color_combo = self.build_combobox(self.color_options,
                                                  self.console_bg_color)
        constraints = self.add_constraints(constraints,
                                           weightx=0.70,
                                           gridx=1,
                                           gridy=2,
                                           gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.bg_color_combo, constraints)

    def build_console_font_color_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        console_font_label = JLabel("Console font color:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.30,
                                           gridx=0,
                                           gridy=3)
        panel.add(console_font_label, constraints)

        self.font_color_combo = self.build_combobox(self.color_options,
                                                    self.console_font_color)
        constraints = self.add_constraints(constraints,
                                           weightx=0.70,
                                           gridx=1,
                                           gridy=3,
                                           gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.font_color_combo, constraints)

    def build_servers_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        server_label = JLabel("ORACC server location:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.30,
                                           gridx=0,
                                           gridy=1,
                                           insets=Insets(10, 10, 80, 10))
        panel.add(server_label, constraints)

        self.combo = self.build_servers_combobox()
        constraints = self.add_constraints(constraints,
                                           weightx=0.70,
                                           gridx=1,
                                           gridy=1,
                                           gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.combo, constraints)

    def build_console_font_panel(self, constraints, panel):
        '''
        Font size on a textfield.
        '''
        fontzise_label = JLabel("Console font size:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.20,
                                           gridx=0,
                                           gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(fontzise_label, constraints)

        self.fs_field = JTextField()
        self.fs_field.setEditable(True)
        if self.console_fontsize:
            self.fs_field.setText("{}".format(self.console_fontsize))
        else:
            self.fs_field.setText(
                self.controller.config['console_style']['fontsize']['default'])

        constraints = self.add_constraints(constraints,
                                           weightx=0.80,
                                           gridx=1,
                                           gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.fs_field, constraints)

    def build_edit_area_font_panel(self, constraints, panel):
        '''
        Font size on a textfield.
        '''
        fontzise_label = JLabel("Edit area font size:")
        constraints = self.add_constraints(constraints,
                                           weightx=0.20,
                                           gridx=0,
                                           gridy=4)
        panel.add(fontzise_label, constraints)

        self.edit_area_fs_field = JTextField()
        self.edit_area_fs_field.setEditable(True)
        if self.edit_area_fontsize:
            self.edit_area_fs_field.setText("{}".format(
                self.edit_area_fontsize))
        else:
            self.edit_area_fs_field.setText(
                self.controller.config['edit_area_style']['fontsize']
                ['default'])

        constraints = self.add_constraints(constraints,
                                           weightx=0.80,
                                           gridx=1,
                                           gridy=4,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.edit_area_fs_field, constraints)

    def build_combobox(self, choices, default):
        '''
        Generic method to construct a combobox. choices should be an iterable
        of strings of the choices to be made and default should be a string
        which is equal to one of the values within the iterable.
        '''
        combo = JComboBox()
        for choice in choices:
            combo.addItem(choice)
        combo.setSelectedItem(default)
        return combo

    def build_servers_combobox(self):
        combo = JComboBox()
        # Go through list of servers and add to combo box.
        for server in self.servers.keys():
            if server != "default":
                combo_item = "{}: {}:{}".format(server,
                                                self.servers[server]['url'],
                                                self.servers[server]['port'])
                combo.addItem(combo_item)
                # If this item is the default one, set it as selected
                if server == self.servers['default']:
                    combo.setSelectedItem(combo_item)
        return combo

    def build_buttons_panel(self):
        '''
        Builds the buttons panel to save or cancel changes.
        TODO: Reset button to reset to defaults?
        '''
        panel = JPanel(FlowLayout())
        panel.add(JButton('Cancel', actionPerformed=self.cancel))
        panel.add(JButton('Save', actionPerformed=self.save))
        return panel

    def build_keystrokes_panel(self):
        '''
        Create the panel that'll go in the Keystrokes tab. This should contain
        options for choosing which keystrokes are to be assigned to which
        actions.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_languages_panel(self):
        '''
        Create the panel that'll go in the Languages tab. This should contain
        options for choosing which is the list of languages that can be
        included from the new ATF window and their abbrv.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_projects_panel(self):
        '''
        Create the panel that'll go in the Projects tab. This should contain
        the list of preferred projects and a means to select which is the
        preferred default.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_appearance_panel(self):
        '''
        Create the panel that'll go in the General tab. This should contain
        options for choosing which server to use for validation as well as
        default working dir.
        '''
        panel = JPanel(GridBagLayout())
        constraints = self.add_constraints(GridBagConstraints(),
                                           insets=Insets(10, 10, 10, 10))
        self.build_console_font_panel(constraints, panel)
        self.build_console_font_color_panel(constraints, panel)
        self.build_console_background_color_panel(constraints, panel)
        self.build_edit_area_font_panel(constraints, panel)
        return panel

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("Edit settings")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def display_error(self, keyword):
        '''
        Display error message when keyword is not in settings file.
        '''
        pass

    def cancel(self, event=None):
        '''
        Close window and don't save changes.
        '''
        self.dispose()

    def validate_fontsize(self, input_size, target_key):
        '''
        Method to validate an input fontsize. The target key points to either
        the console font sizes 'console_style' or the edit area font sizes
        'edit_area_style'. If the value is invalid, return the previous user
        fontsize that was stored.
        The second return value is a bool indicating if the value has changed.
        '''
        # Extract plain english from key name for use in error message
        target = target_key[:-6].replace('_', ' ')

        # Use isnumeric() to test if a unicode string only has digits
        if (input_size.isnumeric() and (8 <= int(input_size) <= 30)):
            return input_size, True
        else:
            input_size = self.controller.config[target_key]['fontsize']['user']
            self.logger.error("Invalid {} font size. Please enter a "
                              "number between 8 and 36.\n\n"
                              "Font size left at "
                              "previous value: {}".format(target, input_size))

            return input_size, False

    def validate_colors(self, bg_color, font_color):
        '''
        Validate console colors to ensure they do not match.
        The second return value is a bool indicating if the value has changed.
        '''
        valid = True
        if bg_color == font_color:
            config = self.controller.config
            self.logger.error("Console font colour cannot match background"
                              " colour. Resetting to default values.")
            bg_color = config['console_style']['background_color']['default']
            font_color = config['console_style']['font_color']['default']
            valid = False

        return bg_color, font_color, valid

    def validate_working_dir(self, working_dir):
        '''
        Method to validate input working directories. If directory does not
        exist or if a path to a file is provided instead of a path to a
        directory the method returns None.
        The second return value is a bool indicating if the value has changed.
        '''
        if os.path.isdir(working_dir):
            return working_dir, True
        else:
            self.logger.error("{} is not a valid working directory."
                              " No working directory has been "
                              "saved".format(working_dir))
            return None, False

    def validate_all_inputs(self, working_dir, console_fontsize,
                            edit_area_fontsize, bg_color, font_color):
        '''
        Wrapper around the input validation methods. Returns a tuple containing
        the validated inputs with the last value in the tuple a boolean set to
        False if any of the values have been altered during the validation
        and True if there have been no changes.
        '''
        # Collect the results of each validation. In future we might use this
        # to provide more detailed error logging on bad user input
        validation_results = []

        # Validate the working directory input string
        working_dir, v = self.validate_working_dir(working_dir)
        validation_results.append(v)

        # Validate the input fontsizes
        con_size, v = self.validate_fontsize(console_fontsize, 'console_style')
        validation_results.append(v)

        edit_size, v = self.validate_fontsize(edit_area_fontsize,
                                              'edit_area_style')
        validation_results.append(v)

        # Validate input console colors
        bg_color, font_color, v = self.validate_colors(bg_color, font_color)
        validation_results.append(v)

        return (working_dir, int(con_size), font_color, bg_color,
                int(edit_size), all(validation_results))

    def save(self, event=None):
        '''
        Save changes made by user on local settings file.
        '''
        # Update only the working_dir and the server for now
        # TODO: update keystrokes, projects list, etc.
        working_dir = self.wd_field.getText()

        # Read the fontsize from the textfield
        console_fontsize = self.fs_field.getText()
        edit_area_fontsize = self.edit_area_fs_field.getText()

        # Get the user selected font and background colours
        bg_color = self.bg_color_combo.getSelectedItem()
        font_color = self.font_color_combo.getSelectedItem()

        validated = self.validate_all_inputs(working_dir, console_fontsize,
                                             edit_area_fontsize, bg_color,
                                             font_color)

        # The server format is "name: url:port". We only need "name"
        server = self.combo.getSelectedItem().split(':')[0]
        self.controller.update_config(validated[0], server, validated[1],
                                      validated[2], validated[3],
                                      int(validated[4]))

        # If no values have been changed, print that settings have been
        # updated without errors
        if validated[5]:
            self.logger.info("Settings have been successfully updated.")

        # On saving settings, update the console and edit area properties
        self.controller.refreshConsole()
        self.controller.refreshEditArea()
        # Close window
        self.dispose()

        # Refresh the syntax highlighting in a separate thread so it updates
        # after everything else has been done.
        runSwingLater(self.controller.controller.initHighlighting)

    def browse(self, event=None):
        '''
        Open new dialog for the user to select a path as default working dir.
        '''
        default_path = self.wd_field.getText()
        if not os.path.isdir(default_path):
            default_path = os.getcwd()
        fileChooser = JFileChooser(default_path)
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        # Fixed showDialog bug using showOpenDialog instead. The former was
        # duplicating the last folder name in the path due to a Java bug in
        # OSX in the implementation of JFileChooser!
        status = fileChooser.showOpenDialog(self)
        if status == JFileChooser.APPROVE_OPTION:
            self.wd_field.setText(fileChooser.getSelectedFile().toString())
예제 #18
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)
예제 #19
0
   f2_txt2.setText("")
   del gvars['path_original_image']
   del gvars['path_label_image']

def f3_clic_finish(event): # Finish
   print "Click Finish"
   gvars["workingImage"].close() # When going back, close the current picture
   frame3.dispose()


# Number of pixels to erode
lbl1 = JLabel("Number of pixels to erode")
lbl1.setBounds(110,30,160,20)
f3_txt1 = JTextField(10)
f3_txt1.setBounds(270, 30, 60,20)
f3_txt1.setText(str(0))

# Button Update
f3_btn_update = JButton("Update ROIs", actionPerformed = f3_clic_update)
f3_btn_update.setBounds(60,70,150,20)

# Button Save Rois
f3_btn_saveRois = JButton("Save ROIs", actionPerformed = f3_clic_SaveROIs)
f3_btn_saveRois.setBounds(250,70,150,20)

# Button Previous - Choose Parameters
f3_btn_params = JButton("Set measurements", actionPerformed = f3_clic_measurements)
f3_btn_params.setBounds(60,110,150,20)

# Button Previous - Save Table
f3_btn_saveTable = JButton("Save CSV Table", actionPerformed = f3_clic_saveTable)
예제 #20
0
class NewZoneDialog(JDialog, ActionListener, WindowListener):
    """Dialog for favourite zone editing
    """
    def __init__(self, parent, title, modal, app):
        from java.awt import CardLayout
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.addWindowListener(self)
        self.pack()

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

        #Reset polygon mode
        self.polygonAsString = ""

        #Reset boundary mode
        self.boundaryAsString = ""

        self.modesComboBox.setSelectedIndex(0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def close_dialog(self, e=None):
        #delete favourite zone editing layer if present
        self.remove_new_zone_editing_layer()
        self.dispose()
        self.app.preferencesFrame.setEnabled(True)
        self.app.preferencesFrame.toFront()
예제 #21
0
class BurpExtender(IBurpExtender, IScannerCheck, ITab):
    def __init__(self):
        self.ext_name = 'AWS Extender'
        self.callbacks = None
        self.gui_elements = None
        self.aws_access_key_inpt = None
        self.aws_secret_key_inpt = None
        self.aws_session_token_inpt = None
        self.gs_access_key_inpt = None
        self.gs_secret_key_inpt = None
        self.wordlist_path_inpt = None
        self.checkbox_inpt = None
        self.aws_access_key = ''
        self.aws_secret_key = ''
        self.aws_session_token = ''
        self.gs_access_key = ''
        self.gs_secret_key = ''
        self.wordlist_path = ''

    def registerExtenderCallbacks(self, callbacks):
        """Register extender callbacks."""
        self.callbacks = callbacks

        # Set the name of the extension
        self.callbacks.setExtensionName(self.ext_name)

        # Register the extension as a scanner check
        self.callbacks.registerScannerCheck(self)

        # Build GUI elements
        self.gui_elements = self.build_gui()

        callbacks.customizeUiComponent(self.gui_elements)
        callbacks.addSuiteTab(self)
        self.check_loading_issues()
        self.reload_config()

    def show_errors(self, label):
        """Display error messages."""
        top_label = JLabel(label, JLabel.CENTER)

        frame = JFrame(self.ext_name)
        frame.setSize(550, 300)
        frame.setLayout(GridLayout(1, 1))

        frame.add(top_label)
        frame.setLocationRelativeTo(None)
        frame.setVisible(True)

    def check_loading_issues(self):
        """Check for any loading issues."""
        missing_libs = []
        tips = []
        label = """<html>
              <body style='margin: 10px'>
                <b>The following dependencies could not be loaded successfully:</b><br>
                <ul><li>%s</li></ul><br>
                <b>Tips:</b><br>
                <ul><li>%s</li><br></ul>
                <b>For detailed information on how to load the plugin, see:</b><br>
                <ul>
                  <li>
                    <a href='#'>https://github.com/VirtueSecurity/aws-extender#getting-started</a>
                  </li>
                </ul>
              </body>
            </html>"""

        if not RUN_TESTS:
            missing_libs.append('boto/boto3')
            tips.append(
                'Make sure that the boto/boto3 library is installed properly, and\
                the right path is specified in the "Folder for loading modules" setting.'
            )
        try:
            CET.fromstring('<test></test>')
        except SAXException:
            # Try to workaround "http://bugs.jython.org/issue1127"
            try:

                def xml_parser(**_):
                    class Parser(object):
                        def feed(*_):
                            raise XMLParseError

                        def close(*_):
                            return None

                    return Parser()

                CET.XMLParser = xml_parser
            except TypeError:
                missing_libs.append('SAXParser')
                tips.append("""Run Burp Suite using the following command:
                   <br><code style='background: #f7f7f9; color: red'>$ java -classpath 
                   xercesImpl.jar;burpsuite_pro.jar burp.StartBurp</code>""")

        if not missing_libs:
            return
        label %= ('</li><li>'.join(missing_libs), '</li><li>'.join(tips))

        self.show_errors(label)

    def build_gui(self):
        """Construct GUI elements."""
        panel = JPanel(BorderLayout(3, 3))
        panel.setBorder(EmptyBorder(160, 160, 160, 160))

        self.aws_access_key_inpt = JTextField(10)
        self.aws_secret_key_inpt = JTextField(10)
        self.aws_session_token_inpt = JTextField(10)
        self.gs_access_key_inpt = JTextField(10)
        self.gs_secret_key_inpt = JTextField(10)
        self.wordlist_path_inpt = JTextField(10)
        self.checkbox_inpt = JCheckBox('Enabled')

        save_btn = JButton('Save', actionPerformed=self.save_config)

        labels = JPanel(GridLayout(0, 1))
        inputs = JPanel(GridLayout(0, 1))
        panel.add(labels, BorderLayout.WEST)
        panel.add(inputs, BorderLayout.CENTER)

        top_label = JLabel('<html><b>Settings</b><br><br></html>')
        top_label.setHorizontalAlignment(JLabel.CENTER)
        panel.add(top_label, BorderLayout.NORTH)
        labels.add(JLabel('AWS Access Key:'))
        inputs.add(self.aws_access_key_inpt)
        labels.add(JLabel('AWS Secret Key:'))
        inputs.add(self.aws_secret_key_inpt)
        labels.add(JLabel('AWS Session Key (optional):'))
        inputs.add(self.aws_session_token_inpt)
        labels.add(JLabel('GS Access Key:'))
        inputs.add(self.gs_access_key_inpt)
        labels.add(JLabel('GS Secret Key:'))
        inputs.add(self.gs_secret_key_inpt)
        labels.add(JLabel('Wordlist Filepath (optional):'))
        inputs.add(self.wordlist_path_inpt)
        labels.add(JLabel('Passive Mode:'))
        inputs.add(self.checkbox_inpt)
        panel.add(save_btn, BorderLayout.SOUTH)
        return panel

    def save_config(self, _):
        """Save settings."""
        error_message = ''
        wordlist_path = self.wordlist_path_inpt.getText()
        save_setting = self.callbacks.saveExtensionSetting
        save_setting('aws_access_key', self.aws_access_key_inpt.getText())
        save_setting('aws_secret_key', self.aws_secret_key_inpt.getText())
        save_setting('aws_session_token',
                     self.aws_session_token_inpt.getText())
        save_setting('gs_access_key', self.gs_access_key_inpt.getText())
        save_setting('gs_secret_key', self.gs_secret_key_inpt.getText())
        save_setting('wordlist_path', wordlist_path)

        if self.checkbox_inpt.isSelected():
            save_setting('passive_mode', 'True')
        else:
            save_setting('passive_mode', '')

        if wordlist_path and not os.path.isfile(wordlist_path):
            error_message = 'Error: Invalid filepath for the "Wordlist Filepath" setting.'
            self.show_errors(error_message)

        self.reload_config()

    def reload_config(self):
        """Reload saved settings."""
        global RUN_TESTS
        load_setting = self.callbacks.loadExtensionSetting
        aws_access_key_val = load_setting('aws_access_key') or ''
        aws_secret_key_val = load_setting('aws_secret_key') or ''
        aws_session_token_val = load_setting('aws_session_token') or ''
        gs_access_key_val = load_setting('gs_access_key') or ''
        gs_secret_key_val = load_setting('gs_secret_key') or ''
        wordlist_path_val = load_setting('wordlist_path') or ''
        checkbox_inpt_val = load_setting('passive_mode')
        checkbox_inpt_val = bool(
            str(checkbox_inpt_val)) if checkbox_inpt_val else False
        if checkbox_inpt_val:
            RUN_TESTS = False
        else:
            RUN_TESTS = True

        self.aws_access_key = aws_access_key_val
        self.aws_secret_key = aws_secret_key_val
        self.aws_session_token = aws_session_token_val
        self.gs_access_key = gs_access_key_val
        self.gs_secret_key = gs_secret_key_val
        self.wordlist_path = wordlist_path_val
        self.aws_access_key_inpt.setText(aws_access_key_val)
        self.aws_secret_key_inpt.setText(aws_secret_key_val)
        self.aws_session_token_inpt.setText(aws_session_token_val)
        self.gs_access_key_inpt.setText(gs_access_key_val)
        self.gs_secret_key_inpt.setText(gs_secret_key_val)
        self.wordlist_path_inpt.setText(wordlist_path_val)
        self.checkbox_inpt.setSelected(checkbox_inpt_val)

    def getTabCaption(self):
        """Return tab caption."""
        return self.ext_name

    def getUiComponent(self):
        """Return GUI elements."""
        return self.gui_elements

    def doPassiveScan(self, request_response):
        """Perform a passive scan."""
        scan_issues = []
        opts = {
            'aws_access_key': self.aws_access_key,
            'aws_secret_key': self.aws_secret_key,
            'aws_session_token': self.aws_session_token,
            'gs_access_key': self.gs_access_key,
            'gs_secret_key': self.gs_secret_key,
            'wordlist_path': self.wordlist_path
        }
        bucket_scan = BucketScan(request_response, self.callbacks, opts)
        bucket_issues = bucket_scan.check_buckets()
        cognito_scan = CognitoScan(request_response, self.callbacks)
        cognito_issues = cognito_scan.identify_identity_pools()

        scan_issues = bucket_issues + cognito_issues
        if len(scan_issues) > 0:
            return scan_issues
        return None

    @staticmethod
    def doActiveScan(*_):
        pass

    @staticmethod
    def consolidateDuplicateIssues(existing_issue, new_issue):
        """Eliminate duplicate issues."""
        if existing_issue.getIssueDetail() == new_issue.getIssueDetail():
            return -1
        else:
            return 0
예제 #22
0
class javadocInfo(java.lang.Runnable):

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Instantiate the user class
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run(self):
        #-----------------------------------------------------------------------
        # Size the frame to use 1/2 of the screen
        #-----------------------------------------------------------------------
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        frameSize = Dimension(screenSize.width >> 1, screenSize.height >> 1)
        frame = JFrame('javadocInfo',
                       size=frameSize,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        #-----------------------------------------------------------------------
        # Reposition the frame to be in the center of the screen
        #-----------------------------------------------------------------------
        frame.setLocation((screenSize.width - frameSize.width) >> 1,
                          (screenSize.height - frameSize.height) >> 1)
        #-----------------------------------------------------------------------
        # Initialize the list to have exactly 1 element
        #-----------------------------------------------------------------------
        self.List = JList(['One moment please...'],
                          valueChanged=self.pick,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        #-----------------------------------------------------------------------
        # Put the List in a ScrollPane and place it in the middle of a pane
        #-----------------------------------------------------------------------
        pane = JPanel(layout=BorderLayout())
        pane.add(JScrollPane(self.List), BorderLayout.CENTER)
        #-----------------------------------------------------------------------
        # Add a TextField [for the URL of the selected entry] at the bottom
        #-----------------------------------------------------------------------
        self.msg = JTextField()
        pane.add(self.msg, BorderLayout.SOUTH)
        #-----------------------------------------------------------------------
        # Add the pane and a scrollable TextArea to a SplitPane in the frame
        #-----------------------------------------------------------------------
        self.area = JTextArea()
        sPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                           pane,
                           JScrollPane(self.area),
                           propertyChange=self.propChange)
        sPane.setDividerLocation(234)
        frame.add(sPane)
        #-----------------------------------------------------------------------
        # Create a separate thread to locate & proces the remote URL
        #-----------------------------------------------------------------------
        self.Links = {}  # Initialize the Links dictionary
        soupTask(
            self.List,  # The visible JList instance
            self.msg,  # The message area (JTextField)
            JAVADOC_URL,  # Remote web page URL to be processed
            self.Links  # Dictionary of links found
        ).execute()
        frame.setVisible(1)

    #---------------------------------------------------------------------------
    # Name: pick()
    # Role: ListSelectionListener event handler
    #---------------------------------------------------------------------------
    def pick(self, e):
        #-----------------------------------------------------------------------
        # Note: Ignore valueIsAdjusting events
        #-----------------------------------------------------------------------
        if not e.getValueIsAdjusting():
            List = self.List
            model = List.getModel()
            #-------------------------------------------------------------------
            # Ignore events for initial "One moment please..." list
            #-------------------------------------------------------------------
            if model.getSize() > 1:
                #---------------------------------------------------------------
                # Is an item selected, or not?
                #---------------------------------------------------------------
                index = List.getSelectedIndex()
                if index > -1:
                    choice = model.elementAt(index)
                    url = self.Links[choice]
                    self.msg.setText(url)
                    textTask(
                        self.area,  # The text area to be updated
                        url  # Remote web page URL to be processed
                    ).execute()
                else:
                    self.msg.setText('Make a selection')
                    self.area.setText('No item selected')

    #---------------------------------------------------------------------------
    # Name: propChange()
    # Role: PropertyChangeListener event handler for JSplitPane
    #---------------------------------------------------------------------------
    def propChange(self, pce):
        src = pce.getSource()  # Should be our JSplitPane
        prop = pce.getPropertyName()
        if prop == JSplitPane.LAST_DIVIDER_LOCATION_PROPERTY:
            curr = src.getDividerLocation()
            last = pce.getNewValue()
            prev = pce.getOldValue()
            print '\nlast: %4d  prev: %4d  curr: %4d' % (last, prev, curr),
예제 #23
0
class Config(ITab):
    """Defines the Configuration tab"""

    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)
        self.path_vars = JTextField(30)


        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass

    def build_ui(self):
        """Builds the configuration screen"""
        labels = JPanel(GridLayout(21, 1))
        checkbox = JCheckBox("Attempt to parse files for URL patterns?",
                             False, actionPerformed=self.set_parse)
        stats_box = JCheckBox("Show stats?", True,
                              actionPerformed=self.set_show_stats)
        # The two year old in me is laughing heartily
        plug_butt = JButton("Specify plugins location",
                            actionPerformed=self.set_plugin_loc)
        load_plug_butt = JButton("Select plugins",
                                 actionPerformed=self.p_build_ui)
        parse_butt = JButton("Parse directory", actionPerformed=self.parse)
        clear_butt = JButton("Clear text", actionPerformed=self.clear)
        spider_butt = JButton("Send to Spider", actionPerformed=self.scan)
        save_butt = JButton("Save config", actionPerformed=self.save)
        rest_butt = JButton("Restore config", actionPerformed=self.restore)
        source_butt = JButton("Input Source File/Directory",
                              actionPerformed=self.get_source_input)

        # Build grid
        labels.add(source_butt)
        labels.add(self.curr_conf)
        labels.add(JLabel("String Delimiter:"))
        labels.add(self.delim)
        labels.add(JLabel("Extension Whitelist:"))
        labels.add(self.ext_white_list)
        labels.add(JLabel("URL:"))
        labels.add(self.url)
        labels.add(JLabel("Path Variables"))
        labels.add(self.path_vars)
        # Leaving these here for now.
        # labels.add(JLabel("Cookies:"))
        # labels.add(self.cookies)
        # labels.add(JLabel("HTTP Headers:"))
        # labels.add(self.headers)
        labels.add(checkbox)
        labels.add(stats_box)
        labels.add(plug_butt)
        labels.add(parse_butt)
        labels.add(JButton("Show all endpoints",
                           actionPerformed=self.print_endpoints))
        labels.add(clear_butt)
        labels.add(spider_butt)
        labels.add(JLabel(""))
        labels.add(save_butt)
        labels.add(rest_butt)
        labels.add(load_plug_butt)
        # Tool tips!
        self.delim.setToolTipText("Use to manipulate the final URL. "
                                  "See About tab for example.")
        self.ext_white_list.setToolTipText("Define a comma delimited list of"
                                           " file extensions to parse. Use *"
                                           " to parse all files.")
        self.url.setToolTipText("Enter the target URL")
        checkbox.setToolTipText("Parse files line by line using plugins"
                                " to enumerate language/framework specific"
                                " endpoints")
        parse_butt.setToolTipText("Attempt to enumerate application endpoints")
        clear_butt.setToolTipText("Clear status window and the parse results")
        spider_butt.setToolTipText("Process discovered endpoints")
        save_butt.setToolTipText("Saves the current config settings")
        rest_butt.setToolTipText("<html>Restores previous config settings:"
                                 "<br/>-Input Directory<br/>-String Delim"
                                 "<br/>-Ext WL<br/>-URL<br/>-Plugins")
        source_butt.setToolTipText("Select the application's "
                                   "source directory or file to parse")
        self.path_vars.setToolTipText("Supply a JSON object with values"
                                      "for dynamically enumerated query"
                                      "string variables")

        return labels

    def set_url(self, menu_url):
        """Changes the configuration URL to the one from the menu event"""
        self.url.setText(menu_url)

    # Event functions
    def set_parse(self, event):
        """
        Handles the click event from the UI checkbox
        to attempt code level parsing
        """
        self.parse_files = not self.parse_files
        if self.parse_files:
            if not self.loaded_plugins:
                self._plugins_missing_warning()

    def restore(self, event):
        """Attempts to restore the previously saved configuration."""
        jdump = None
        try:
            jdump = loads(self._callbacks.loadExtensionSetting("config"))
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll(
                "[!!] Error during restore!\n\tException: %s" % str(exc))
        if jdump is not None:
            self.url.setText(jdump.get('URL'))
            # self.cookies.setText(jdump.get('Cookies'))
            # self.headers.setText(jdump.get("Headers"))
            ewl = ""
            for ext in jdump.get('Extension Whitelist'):
                ewl += ext + ", "
            self.ext_white_list.setText(ewl[:-2])
            self.delim.setText(jdump.get('String Delimiter'))
            self.source_input = jdump.get("Input Directory")
            self.config['Plugin Folder'] = jdump.get("Plugin Folder")
            if (self.config['Plugin Folder'] is not None and
                    (len(self.plugins.values()) < 1)):
                self._load_plugins(self.config['Plugin Folder'])
            self._update()
            self.update_scroll("[^] Restore complete!")
        else:
            self.update_scroll("[!!] Restore failed!")

    def save(self, event=None):
        """
        Saves the configuration details to a Burp Suite's persistent store.
        """
        self._update()
        try:
            if not self._callbacks.isInScope(URL(self.url.getText())):
                self.update_scroll("[!!] URL provided is NOT in Burp Scope!")
        except MalformedURLException:  # If url field is blank we'll
            pass                       # still save the settings.
        try:
            self._callbacks.saveExtensionSetting("config", dumps(self.config))
            self.update_scroll("[^] Settings saved!")
        except Exception:
            self.update_scroll("[!!] Error saving settings to Burp Suite!")

    def parse(self, event):
        """
        Handles the click event from the UI.
        Attempts to parse the given directory
            (and/or source files) for url endpoints
        Saves the items found within the url_reqs list
        """
        self._update()

        file_set = set()
        fcount = 0
        other_dirs = set()
        self.ext_stats = {}
        if self.loaded_plugins:
            self.update_scroll("[^] Attempting to parse files" +
                               " for URL patterns. This might take a minute.")
        if path.isdir(self.source_input):
            for dirname, _, filenames in walk(self.source_input):
                for filename in filenames:
                    fcount += 1
                    ext = path.splitext(filename)[1]
                    count = self.ext_stats.get(ext, 0) + 1
                    filename = "%s/%s" % (dirname, filename)
                    self.ext_stats.update({ext: count})
                    if self.parse_files and self._ext_test(ext):
                        # i can haz threading?
                        file_set.update(self._code_as_endpoints(filename, ext))
                    elif self._ext_test(ext):
                        r_files, oths = self._files_as_endpoints(filename, ext)
                        file_set.update(r_files)
                        other_dirs.update(oths)
        elif path.isfile(self.source_input):
            ext = path.splitext(self.source_input)[1]
            file_set.update(self._code_as_endpoints(self.source_input, ext))
        else:
            self.update_scroll("[!!] Input Directory is not valid!")
        if len(other_dirs) > 0:
            self.update_scroll("[*] Found files matching file extension in:\n")
            for other_dir in other_dirs:
                self.update_scroll(" " * 4 + "%s\n" % other_dir)
        self._handle_path_vars(file_set)
        self._print_parsed_status(fcount)
        return (other_dirs, self.url_reqs)

    def _handle_path_vars(self, file_set):
        proto = 'http://'
        for item in file_set:
            if item.startswith("http://") or item.startswith("https://"):
                proto = item.split("//")[0] + '//'
                item = item.replace(proto, "")
                item = self._path_vars(item)
            self.url_reqs.append(proto + item.replace('//', '/'))

    def _path_vars(self, item):
        p_vars = None
        if self.path_vars.getText():
            try:
                p_vars = loads(str(self.path_vars.getText()))
            except:
                self.update_scroll("[!] Error reading supplied Path Variables!")
        if p_vars is not None:
            rep_str = ""
            try:
                for k in p_vars.keys():
                    rep_str += "[^] Replacing %s with %s!\n" % (k, str(p_vars.get(k)))
                self.update_scroll(rep_str)
                for k in p_vars.keys():
                    if str(k) in item:
                        item = item.replace(k, str(p_vars.get(k)))
            except AttributeError:
                self.update_scroll("[!] Error reading supplied Path Variables! This needs to be a JSON dictionary!")
        return item
            
            
    def scan(self, event):
        """
        handles the click event from the UI.
        Adds the given URL to the burp scope and sends the requests
        to the burp spider
        """
        temp_url = self.url.getText()
        if not self._callbacks.isInScope(URL(temp_url)):
            if not self.double_click:
                self.update_scroll("[!!] URL is not in scope! Press Send to "
                                   "Spider again to add to scope and scan!")
                self.double_click = True
                return
            else:
                self._callbacks.sendToSpider(URL(temp_url))
        self.update_scroll(
            "[^] Sending %d requests to Spider" % len(self.url_reqs))
        for req in self.url_reqs:
            self._callbacks.sendToSpider(URL(req))

    def clear(self, event):
        """Clears the viewport and the current parse exts"""
        self.view_port_text.setText("===SpyDir===")
        self.ext_stats = {}

    def print_endpoints(self, event):
        """Prints the discovered endpoints to the status window."""
        req_str = ""
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Printing all discovered endpoints:")
            for req in sorted(self.url_reqs):
                req_str += "    %s\n" % req
        else:
            req_str = "[!!] No endpoints discovered"
        self.update_scroll(req_str)

    def set_show_stats(self, event):
        """Modifies the show stats setting"""
        self.print_stats = not self.print_stats

    def get_source_input(self, event):
        """Sets the source dir/file for parsing"""
        source_chooser = JFileChooser()
        source_chooser.setFileSelectionMode(
            JFileChooser.FILES_AND_DIRECTORIES)
        source_chooser.showDialog(self.tab, "Choose Source Location")
        chosen_source = source_chooser.getSelectedFile()
        try:
            self.source_input = chosen_source.getAbsolutePath()
        except AttributeError:
            pass
        if self.source_input is not None:
            self.update_scroll("[*] Source location: %s" % self.source_input)
            self.curr_conf.setText(self.source_input)

    # Plugin functions
    def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys() and self._ext_test(ext):
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set

    def set_plugin_loc(self, event):
        """Attempts to load plugins from a specified location"""
        if self.config['Plugin Folder'] is not None:
            choose_plugin_location = JFileChooser(self.config['Plugin Folder'])
        else:
            choose_plugin_location = JFileChooser()
        choose_plugin_location.setFileSelectionMode(
            JFileChooser.DIRECTORIES_ONLY)
        choose_plugin_location.showDialog(self.tab, "Choose Folder")
        chosen_folder = choose_plugin_location.getSelectedFile()
        self.config['Plugin Folder'] = chosen_folder.getAbsolutePath()
        self._load_plugins(self.config['Plugin Folder'])

    def _load_plugins(self, folder):
        """
        Parses a local directory to get the plugins
            related to code level scanning
        """
        report = ""
        if len(self.plugins.keys()) > 0:
            report = "[^] Plugins reloaded!"
        for _, _, filenames in walk(folder):
            for p_name in filenames:
                n_e = path.splitext(p_name)  # n_e = name_extension
                if n_e[1] == ".py":
                    f_loc = "%s/%s" % (folder, p_name)
                    loaded_plug = self._validate_plugin(n_e[0], f_loc)
                    if loaded_plug:
                        for p in self.loaded_p_list:
                            if p.get_name() == loaded_plug.get_name():
                                self.loaded_p_list.discard(p)
                        self.loaded_p_list.add(loaded_plug)
                        if not report.startswith("[^]"):
                            report += "%s loaded\n" % loaded_plug.get_name()

        self._dictify(self.loaded_p_list)
        if len(self.plugins.keys()) > 0:
            self.loaded_plugins = True
        else:
            report = "[!!] Plugins load failure"
            self.loaded_plugins = False
        self.update_scroll(report)
        return report

    def _validate_plugin(self, p_name, f_loc):
        """
        Attempts to verify the manditory plugin functions to prevent broken
        plugins from loading.
        Generates an error message if plugin does not contain an appropriate
        function.
        """
        # Load the plugin
        try:
            plug = load_source(p_name, f_loc)
        except Exception as exc:  # this needs to be generic.
            self.update_scroll(
                "[!!] Error loading: %s\n\tType:%s Error: %s"
                % (f_loc, type(exc), str(exc)))
        # Verify the plugin's functions
        funcs = dir(plug)
        err = []
        if "get_name" not in funcs:
            err.append("get_name()")
        if "get_ext" not in funcs:
            err.append("get_ext()")
        if "run" not in funcs:
            err.append("run()")

        # Report errors & return
        if len(err) < 1:
            return Plugin(plug, True)
        for issue in err:
            self.update_scroll("[!!] %s is missing: %s func" %
                               (p_name, issue))
        return None

    def _dictify(self, plist):
        """Converts the list of loaded plugins (plist) into a dictionary"""
        for p in plist:
            exts = p.get_ext().upper()
            for ext in exts.split(","):
                prev_load = self.plugins.get(ext, [])
                prev_load.append(p)
                self.plugins[ext] = prev_load

    # Status window functions
    def _print_parsed_status(self, fcount):
        """Prints the parsed directory status information"""
        if self.parse_files and not self.loaded_plugins:
            self._plugins_missing_warning()
        if len(self.url_reqs) > 0:
            self.update_scroll("[*] Example URL: %s" % self.url_reqs[0])

        if self.print_stats:
            report = (("[*] Found: %r files to be requested.\n\n" +
                       "[*] Stats: \n    " +
                       "Found: %r files.\n") % (len(self.url_reqs), fcount))
            if len(self.ext_stats) > 0:
                report += ("[*] Extensions found: %s"
                           % str(dumps(self.ext_stats,
                                       sort_keys=True, indent=4)))
        else:
            report = ("[*] Found: %r files to be requested.\n" %
                      len(self.url_reqs))
        self.update_scroll(report)
        return report

    def _plugins_missing_warning(self):
        """Prints a warning message"""
        self.update_scroll("[!!] No plugins loaded!")

    def update_scroll(self, text):
        """Updates the view_port_text with the new information"""
        temp = self.view_port_text.getText().strip()
        if text not in temp or text[0:4] == "[!!]":
            self.view_port_text.setText("%s\n%s" % (temp, text))
        elif not temp.endswith("[^] Status unchanged"):
            self.view_port_text.setText("%s\n[^] Status unchanged" % temp)

    # Internal functions
    def _code_as_endpoints(self, filename, ext):
        file_set = set()
        file_url = self.config.get("URL")
        if self.loaded_plugins or ext == '.txt':
            if self._ext_test(ext):
                file_set.update(
                    self._parse_file(filename, file_url))
            else:
                file_set.update(
                    self._parse_file(filename, file_url))
        return file_set

    def _files_as_endpoints(self, filename, ext):
        """Generates endpoints via files with the appropriate extension(s)"""
        file_url = self.config.get("URL")
        broken_splt = ""
        other_dirs = set()  # directories outside of the String Delim.
        file_set = set()
        str_del = self.config.get("String Delimiter")
        if not str_del:
            self.update_scroll("[!!] No available String Delimiter!")
            return
        spl_str = filename.split(str_del)

        try:
            # Fix for index out of bounds exception while parsing
            # subfolders _not_ included by the split
            if len(spl_str) > 1:
                file_url += ((spl_str[1])
                             .replace('\\', '/'))
            else:
                broken_splt = filename.split(self.source_input)[1]
                other_dirs.add(broken_splt)
        except Exception as exc:  # Generic exception thrown directly to user
            self.update_scroll("[!!] Error parsing: " +
                               "%s\n\tException: %s"
                               % (filename, str(exc)))
        if self._ext_test(ext):
            if file_url != self.config.get("URL"):
                file_set.add(file_url)
        else:
            other_dirs.discard(broken_splt)
        return file_set, other_dirs

    def _ext_test(self, ext):
        """Litmus test for extension whitelist"""
        val = False
        if "*" in self.config.get("Extension Whitelist"):
            val = True
        else:
            val = (len(ext) > 0 and
                   (ext.strip().upper()
                    in self.config.get("Extension Whitelist")))
        return val

    def _update(self):
        """Updates internal data"""
        self.config["Input Directory"] = self.source_input
        self.config["String Delimiter"] = self.delim.getText()

        white_list_text = self.ext_white_list.getText()
        self.config["Extension Whitelist"] = white_list_text.upper().split(',')
        file_url = self.url.getText()
        if not (file_url.startswith('https://') or file_url.startswith('http://')):
            self.update_scroll("[!] Assuming protocol! Default value: 'http://'")
            file_url = 'http://' + file_url
            self.url.setText(file_url)

        if not file_url.endswith('/') and file_url != "":
            file_url += '/'

        self.config["URL"] = file_url
        # self.config["Cookies"] = self.cookies.getText()
        # self.config["Headers"] = self.headers.getText()
        del self.url_reqs[:]
        self.curr_conf.setText(self.source_input)

    # Window sizing functions
    def resize(self, event):
        """Resizes the window to better fit Burp"""
        if self.parent_window is not None:
            par_size = self.parent_window.getSize()
            par_size.setSize(par_size.getWidth() * .99,
                             par_size.getHeight() * .9)
            self.tab.setPreferredSize(par_size)
            self.parent_window.validate()
            self.parent_window.switch_focus()

    def p_close(self, event):
        """
        Handles the window close event.
        """
        self.window.setVisible(False)
        self.window.dispose()

    def p_build_ui(self, event):
        """
        Adds a list of checkboxes, one for each loaded plugin
        to the Selct plugins window
        """
        if not self.loaded_p_list:
            self.update_scroll("[!!] No plugins loaded!")
            return

        scroll_pane = JScrollPane()
        scroll_pane.setPreferredSize(Dimension(200, 250))
        check_frame = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.FIRST_LINE_START

        for plug in self.loaded_p_list:
            check_frame.add(JCheckBox(plug.get_name(), plug.enabled,
                                      actionPerformed=self.update_box),
                            constraints)
            constraints.gridy += 1

        vport = JViewport()
        vport.setView(check_frame)
        scroll_pane.setViewport(vport)
        self.window.contentPane.add(scroll_pane)
        self.window.pack()
        self.window.setVisible(True)

    def update_box(self, event):
        """
        Handles the check/uncheck event for the plugin's box.
        """
        for plug in self.loaded_p_list:
            if plug.get_name() == event.getActionCommand():
                plug.enabled = not plug.enabled
                if plug.enabled:
                    self.update_scroll("[^] Enabled: %s" %
                                       event.getActionCommand())
                else:
                    self.update_scroll("[^] Disabled: %s" %
                                       event.getActionCommand())

    # ITab required functions
    @staticmethod
    def getTabCaption():
        """Returns the name of the Burp Suite Tab"""
        return "SpyDir"

    def getUiComponent(self):
        """Returns the UI component for the Burp Suite tab"""
        return self.tab
예제 #24
0
class ConsolePanel(Panel):

	def __init__(self):
		
		self.console = None
		self.outText = None
		self.inText = None
		self.outTextScroller = None
		self.nestedInputPanel = None
		self.directoryText = None
		Panel.__init__(self, "insets 0 0 0 0")

	def sendCommand(self, command):
		print str(self)
		oldText = self.inText.getText()
		self.inText.setText(command)

		self.inText.getActionListeners()[0].actionPerformed(None)
		self.inText.setText(oldText)

	def setDirectoryText(self, dirText):
		self.directoryText.setText(dirText)
		self.nestedInputPanel.revalidate()

	def write_out(self,text):
		if not self.outText:
			return
		self.outText.setText(self.outText.getText() + text)

	def initUI(self):

		font = Font("Courier New", Font.BOLD, 14)

		#create the output text panel
		self.outText = JTextArea()
		self.outText.setEditable(False)
		self.outText.setFont(font)
		self.outText.setWrapStyleWord(True)
		self.outText.setLineWrap(True)
		#self.outText.setLineWrap(True)
		#self.outText.setWrapStyleWord(True)
		class NoGhostScroller(JScrollPane):
			def paintComponent(self, g):
				
				g.setColor(self.getBackground())
				g.fillRect(0, 0, self.getWidth(), self.getHeight())
				#super(NoGhostScroller, self).paintComponent(g)

		self.outTextScroller = JScrollPane(self.outText)
		self.outTextScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
		self.outTextScroller.getVerticalScrollBar().setForeground(Color(255, 0, 0))
		#self.outText.setOpaque(False)
		self.outText.setBackground(Color(0, 20, 0))
		self.outText.setForeground(Color.WHITE)

		#self.outTextScroller.setOpaque(False)
		self.outTextScroller.setBackground(Color(0, 20, 0))

		#self.outText.repaint()

		#self.layered = JLayeredPane()
		#self.layered.setLayer(self.outTextScroller, 0)

		#create the input text box
		self.inText = JTextField()
		self.inText.setFocusTraversalKeysEnabled(False)
		self.inText.setFont(font)
		self.inText.setBackground(Color(0, 20, 0))
		self.inText.setForeground(Color.WHITE)
		self.inText.getCaret().setVisible(True)
		self.inText.getCaret().setBlinkRate(500)
		self.inText.setCaretColor(Color(200,255,200))
		
		class InFocusAdapter(FocusAdapter):
			def focusLost(adap, e):
				self.inText.setVisible(True)
		self.inText.addFocusListener(InFocusAdapter())

		self.nestedInputPanel = Panel("Insets 0 0 0 0")

		#create the directory text box
		self.directoryText = JTextField()
		self.directoryText.setEditable(False)
		self.directoryText.setFont(font)
		self.directoryText.setBackground(Color(0, 20, 0))
		self.directoryText.setForeground(Color.WHITE)
		#set up the console
		sys.stdout = FakeOut(self.outText)
		self.console = BashED_Console(stdout=sys.stdout)
		self.directoryText.setText(self.console.get_prompt())
		self.revalidate();


		dirTex = self.directoryText;

		#create the listener that fires when the 'return' key is pressed
		class InputTextActionListener(ActionListener):
			def __init__(self,parent,inp,out,console):
				self.parent = parent
				self.inp = inp
				self.out = out
				self.console = console

			def actionPerformed(self, e):
				#print self.getCommandText()
				# print(self.console.get_prompt())
				# self.console.onecmd(self.inp.getText())
				# self.parent.write_out("\n" + self.inp.getText())
				# dirTex.setText(self.console.get_prompt())
				# self.inp.setText("")

				self.parent.write_out(self.console.get_prompt() + self.inp.getText() + '\n')
				if 'clear' in self.inp.getText().split(' ')[0]:
					self.out.setText("") #clear the screen
				else:
					self.console.onecmd(self.inp.getText())
				
				dirTex.setText(self.console.get_prompt())
				self.inp.setText("")

		#create the listener that fires whenever a user hits a key
		class InputKeyActionListener(KeyAdapter):
			def __init__(self,parent,inp,out,console):
				self.parent = parent
				self.inp = inp
				self.out = out
				self.console = console

			def keyReleased(self, k):
				inp = self.inp.getText()
				if k.getKeyCode() == 9: #tab character
					autos = self.console.tabcomplete(self.inp.getText())
					if len(autos) == 1:
						self.inp.setText(autos[0])
					else:
						i = 0
						for option in autos:
							self.parent.write_out(option)
							if i % 3 == 0:
								print('\n')
							else:
								print('\t')
				hist = None
				if k.getKeyCode() == 38:
					hist = self.console.next_hist()
				if k.getKeyCode() == 40:
					hist = self.console.last_hist()

				if hist:
					self.inp.setText(hist.rstrip('\n'))#prevent from firing

		self.inText.addActionListener(InputTextActionListener(self,self.inText,self.outText,self.console))
		self.inText.addKeyListener(InputKeyActionListener(self,self.inText,self.outText,self.console))




	def addUI(self):
		
		self.add(self.outTextScroller, "cell 0 0, push, grow")
		self.add(self.nestedInputPanel, "cell 0 1, pushx, growx")
		self.nestedInputPanel.add(self.directoryText, "cell 0 0")
		self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")
예제 #25
0
inputPanel.add(JLabel("Project Name"))
inputPanel.add(projectNameTf)

imageNameTf = JTextField(job.imageName)
inputPanel.add(JLabel("Image Name"))
inputPanel.add(imageNameTf)


scaleLevelsTf = JTextField()
inputPanel.add(JLabel("Scale levels (empty=automatic)"))
inputPanel.add(scaleLevelsTf)

resolutionTf = JTextField()
inputPanel.add(JLabel("Resolution"))
inputPanel.add(resolutionTf)
resolutionTf.setText("%s, %s, %s" % job.resolution)

defaultMinTf = JTextField()
inputPanel.add(JLabel("Default display range min"))
inputPanel.add(defaultMinTf)
defaultMinTf.setText(str(job.displayMin))

defaultMaxTf = JTextField()
inputPanel.add(JLabel("Default display range max"))
inputPanel.add(defaultMaxTf)
defaultMaxTf.setText(str(job.displayMax))

inputPanel.add(JLabel("Output Directory"))
outputDirPanel = JPanel()
outputDirPanel.setLayout(BorderLayout())
outputDirTf = JTextField(job.outputDir)
예제 #26
0
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener):
    """Dialog with preferences
    """
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder()
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"),
                          None,
                          panel1,
                          None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"),
                                           actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = ["",
                   self.app.strings.getString("Type"),
                   self.app.strings.getString("Name")]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                            ImageProvider.get("dialogs", "delete"),
                            actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"),
                          None,
                          panel2,
                          None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"),
                          None,
                          panel3,
                          None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()

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

    def hyperlinkUpdate(self, e):
        if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED:
            OpenBrowser.displayUrl(e.getURL().toString())

    def itemStateChanged(self, e):
        """A ttol has been activated/deactivated.
           Check if at least one tool is on.
        """
        if all(not button.isSelected() for button in self.toolsCBtns):
            JOptionPane.showMessageDialog(
                Main.parent,
                self.app.strings.getString("tools_disabled_warning"),
                self.app.strings.getString("tools_disabled_warning_title"),
                JOptionPane.WARNING_MESSAGE)
            source = e.getItemSelectable()
            source.setSelected(True)

    def actionPerformed(self, e=None):
        """Enable/disable favourite zones panel
        """
        for container in (self.scrollPane, self.buttonsPanel):
            self.enableComponents(container, self.favZoneStatusCBtn.isSelected())
        if self.favZoneStatusCBtn.isSelected():
            self.check_removeBtn_status()

    def enableComponents(self, container, enable):
        components = container.getComponents()
        for component in components:
            component.setEnabled(enable)
            if isinstance(component, Container):
                self.enableComponents(component, enable)

    def on_downloadBtn_clicked(self, e):
        update_checker.Updater(self.app, "manual")

    def clean_map(self):
        """Remove all rectangles and polygons from the map
        """
        self.zonesMap.removeAllMapRectangles()
        self.zonesMap.removeAllMapPolygons()

    def update_gui_from_preferences(self):
        """Update gui status of preferences frame from config file
        """
        #print "\n- updating Preferences gui"
        onOff = {"on": True, "off": False}
        #1 Tab
        #check for update
        self.updateCBtn.setSelected(onOff[self.app.checkUpdate])

        #tools status, enabled or not
        for toolIndex, tool in enumerate(self.app.realTools):
            if "tool.%s" % tool.name in self.app.properties.keys():
                configstatus = self.app.properties.getProperty("tool.%s" % tool.name)
            else:
                configstatus = "on"     # new tool
            self.toolsCBtns[toolIndex].setSelected(onOff[configstatus])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            button.setSelected(mode == self.app.layersMode)

        #max errors number
        self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber))

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()

        #2 Tab
        #favourite area
        self.update_favourite_area_gui_from_preferences()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                tool.prefsGui.update_gui(tool.prefs)

    def update_favourite_area_gui_from_preferences(self):
        #status
        self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus)
        #table
        #store zones to a temporary list, used to store changes
        #and save them when preferences dialog is closed
        self.app.tempZones = list(self.app.zones)
        self.zonesTable.getModel().setNumRows(0)
        for zone in self.app.tempZones:
            self.zonesTable.getModel().addRow([zone.country,
                                               zone.icon,
                                               zone.name])
        if self.app.favZone is not None:
            selectedRow = self.app.tempZones.index(self.app.favZone)
            self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow)
        self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30)
        self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50)
        #enable or disable favourite zone buttons
        self.actionPerformed()

### fav area editing buttons ###########################################
    def on_removeBtn_clicked(self, e):
        rowsNum = self.zonesTable.getSelectedRows()
        rowsNum.reverse()
        for rowNum in rowsNum:
            del self.app.tempZones[rowNum]
            self.zonesTable.getModel().removeRow(rowNum)
        if len(self.app.tempZones) != 0:
            if rowNum == 0:
                self.zonesTable.setRowSelectionInterval(0, 0)
            else:
                self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1)
        self.check_removeBtn_status()

    def check_removeBtn_status(self):
        if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0:
            self.removeBtn.setEnabled(True)
        else:
            self.removeBtn.setEnabled(False)
            self.clean_map()

    def on_newBtn_clicked(self, e):
        try:
            self.newZoneDialog
        except AttributeError:
            self.newZoneDialog = NewZoneDialog(self.app)
        bbox = self.app.get_frame_bounds()
        self.app.newZone = Zone(self.app,
                                self.app.strings.getString("New_zone"),
                                "rectangle",
                                ",".join(["%0.4f" % x for x in bbox]),
                                "")
        self.newZoneDialog.update_gui_from_preferences()
        self.newZoneDialog.show()

### Exit from preferences ##############################################
    def on_cancelBtn_clicked(self, event=None):
        if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible():
            self.newZoneDialog.close_dialog()
        self.dispose()

    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop,
                                            onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones],
                   "deleted": [z for z in self.app.zones if not z in self.app.tempZones]}
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(File.separator.join([self.app.SCRIPTDIR,
                                          "configuration",
                                          "favourite_zones",
                                          "%s.txt" % zone.name]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([self.app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones",
                                            "%s.txt" % zone.name])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name",
                                            "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()
예제 #27
0
class ChatApp(JFrame):
	
	##  Constructor function, initiate the base classes and call the GUI
	
	def __init__(self):
		'''Calls the base class and main UI
		'''
		#  Call to the super class, initiates associated base classes
		super(ChatApp, self).__init__()
		#  Call the Initial UI
		self.initUI()
	
	##  Build the GUI for login, uses GroupLayout Manager for component positioning
		
	def initUI(self):
		'''Initial UI and Widget creation takes place here!
		'''
		self.setContentPane = JPanel()
		#self.setDefaultLookAndFeelDecorated(True)
		#  Borders
		foreground_colour = Color(30,57,68)
		background_colour = Color(247,246,242)
		window_background = Color(145,190,210)
		self.border = BorderFactory.createLoweredBevelBorder()
		self.border2 = BorderFactory.createLineBorder(foreground_colour, 1, True)
		#  Fonts
		self.entry_font= Font("Ubuntu Light",  Font.BOLD, 20)
		self.label_font= Font("Ubuntu Light",  Font.BOLD, 17)
		self.btn_font=Font("Ubuntu Light", Font.BOLD, 15)
		#  Layout start
		layout=GroupLayout(self.getContentPane())
		self.getContentPane().setLayout(layout)	
		layout.setAutoCreateGaps(True)
		layout.setAutoCreateContainerGaps(True)
		self.setPreferredSize(Dimension(300, 150))
		#  Create the labels
		user_label= JLabel(" Username : "******"  Server  : ", JLabel.LEFT, font=self.label_font)
				
		#  Colours
		user_label.setForeground(foreground_colour)
		server_label.setForeground(foreground_colour)
		
		#  Create the text entries
		self.username=JTextField(actionPerformed=self.continueEvent, border=self.border2,  font = self.entry_font)
		self.server=JTextField(actionPerformed=self.continueEvent, border=self.border2,  font = self.entry_font)
		
		#  Colours
		self.username.setBackground(background_colour)
		self.server.setBackground(background_colour)
		self.username.setForeground(foreground_colour)
		self.server.setForeground(foreground_colour)
		
		#  Allow editable
		self.username.setEditable(True)
		self.server.setEditable(True)
		
		#  Create the buttons
		quit_btn=JButton("  Quit!  ", actionPerformed=self.closeEvent, border=self.border2, font=self.btn_font)
		go_btn=JButton("   Go!   ", actionPerformed=self.continueEvent, border=self.border2, font=self.btn_font)
		#  Colours
		quit_btn.setBackground(background_colour)
		go_btn.setBackground(background_colour)
		quit_btn.setForeground(foreground_colour)
		go_btn.setForeground(foreground_colour)
		
		#  Setting up the horizontal groups parameters
		layout.setHorizontalGroup(layout.createSequentialGroup()
		
			#  Left side
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
				.addComponent(user_label)
				.addComponent(server_label))
				
			#  Right side
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(self.username)
				.addComponent(self.server)
				.addGroup(layout.createSequentialGroup()
					.addComponent(quit_btn)
					.addComponent(go_btn)))
		)
		
		#  Setting up Vertical Groups
		layout.setVerticalGroup(layout.createSequentialGroup()
			#  Top group
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(user_label)
				.addComponent(self.username))
			#  Middle group
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
				.addComponent(server_label)
				.addComponent(self.server))
			#  Bottom group
			.addGroup(layout.createParallelGroup()
				.addComponent(quit_btn)
				.addComponent(go_btn))
		)
		
		#  Finalise the GUI	
		layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn])
		self.getContentPane().setBackground(window_background)
		self.pack()
		self.setTitle('Chat Login')
		self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
		self.setLocationRelativeTo(None)
		self.setVisible(True)
		
	##  Event driven funtion to respond to quit button click
	
	def closeEvent(self,event):	
		'''Function to close the login window
		'''
		print("Goodbye!")
		exit()		
	
	
	##  Event driven function to respond to send button click, grabs text and sends it down the wire	
	
	def continueEvent(self,event):
		'''Function that retreives the login details for sending to the server
		'''	
		#  Grab the text that has been entered
		user = self.username.getText()
		Host = self.server.getText()
		#  Default port
		Port=60001
		connected=False
		while not connected:
		#  Try make a connection except when there isn't one available, then quit program'
			try:
				tn=telnetlib.Telnet(Host, Port)
				connected=True
				continue
			except:
				JOptionPane.showMessageDialog(self,'Connection Error, No Server Available!')
				self.username.setText('')
				self.server.setText('')
				self.username.requestFocusInWindow()
				return
		#  Listen for a response	
		response = tn.read_until('<<<')
		print(response)
		#  Acknowledge with the username
		tn.write(user+'\r\n')
		#  Receive validation of name, present dialog if not valid
		valid_name = tn.read_until('<')
		valid_name.strip()
		v_name, delim = valid_name.split('<')
		if v_name.strip() != 'OK':
			JOptionPane.showMessageDialog(self,'Bad Username, please choose another')
			self.username.setText('')
			self.username.requestFocusInWindow()
			return
		#  Set the login GUI to hidden
		self.setVisible(False)  ##   <<<<<<  I have no idea why this doesn't work but I suspect it's something to do with either inheritance or having 2 class instances
		#  Call the main program, pass the connection as a parameter
		ChatClient(user,response , tn)
class BurpExtender(IBurpExtender, IScannerCheck, IScanIssue, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Missing Scanner Checks")
        self.out = callbacks.getStdout()

        # define all checkboxes
        self.cbPassiveChecks = self.defineCheckBox("Passive Scanner Checks")
        self.cbDOMXSS = self.defineCheckBox("DOM XSS", False)
        self.cbDOMXSSSources = self.defineCheckBox("Sources", False)
        self.cbDOMXSSSinks = self.defineCheckBox("Sinks")
        self.cbDOMXSSjQuerySinks = self.defineCheckBox("jQuery Sinks", False)
        self.grpDOMXSSSettings = JPanel()
        self.grpDOMXSSSettings.add(self.cbDOMXSSSources)
        self.grpDOMXSSSettings.add(self.cbDOMXSSSinks)
        self.grpDOMXSSSettings.add(self.cbDOMXSSjQuerySinks)
        self.cbSTS = self.defineCheckBox("Strict Transport Security")
        self.lblSTSMin = JLabel("Minimum acceptable max-age")
        self.inSTSMin = JTextField(str(STSMinimum), 9, actionPerformed=self.setSTSMinimum) # TODO: actionPerformed only fires on enter key - focus lost would be better
        self.inSTSMin.setToolTipText("Enter the minimum max-age value which is considered as acceptable. Press return to change setting!")
        self.grpSTSSettings = JPanel()
        self.grpSTSSettings.add(self.lblSTSMin)
        self.grpSTSSettings.add(self.inSTSMin)
        self.cbXCTO = self.defineCheckBox("Content Sniffing")
        self.cbXXP = self.defineCheckBox("Client-side XSS Filter Configuration")
        self.cbRedirToHTTPS = self.defineCheckBox("Redirection from HTTP to HTTPS")
        self.btnSave = JButton("Set as default", actionPerformed=self.saveConfig)
        self.btnRestore = JButton("Restore", actionPerformed=self.restoreConfig)
        self.grpConfig = JPanel()
        self.grpConfig.add(self.btnSave)
        self.grpConfig.add(self.btnRestore)
        self.restoreConfig()

        # definition of config tab
        self.tab = JPanel()
        layout = GroupLayout(self.tab)
        self.tab.setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
        layout.setHorizontalGroup(
            layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup()
                      .addComponent(self.cbPassiveChecks)
                      )
            .addGroup(layout.createParallelGroup()
                      .addComponent(self.cbDOMXSS)
                      .addComponent(self.cbSTS)
                      .addComponent(self.cbXCTO)
                      .addComponent(self.cbXXP)
                      .addComponent(self.cbRedirToHTTPS)
                      )
            .addGroup(layout.createParallelGroup()
                      .addComponent(self.grpDOMXSSSettings, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                      .addComponent(self.grpSTSSettings, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                      .addComponent(self.grpConfig, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                      )
            )
        layout.setVerticalGroup(
            layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup()
                      .addComponent(self.cbPassiveChecks)
                      .addComponent(self.cbDOMXSS)
                      .addComponent(self.grpDOMXSSSettings, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                      )
            .addGroup(layout.createParallelGroup()
                      .addComponent(self.cbSTS)
                      .addComponent(self.grpSTSSettings, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
                      )
            .addComponent(self.cbXCTO)
            .addComponent(self.cbXXP)
            .addComponent(self.cbRedirToHTTPS)
            .addComponent(self.grpConfig, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
            )

        self.domXSSSourcesRE = re.compile("(location\s*[\[.])|([.\[]\s*[\"']?\s*(arguments|dialogArguments|innerHTML|write(ln)?|open(Dialog)?|showModalDialog|cookie|URL|documentURI|baseURI|referrer|name|opener|parent|top|content|self|frames)\W)|(localStorage|sessionStorage|Database)")
        # NOTE: done some optimizations here, original RE caused too much noise
        # - added leading dot in the first part - original recognized "<a href=..." etc.
        # - removed "value" in first part
        self.domXSSSinksRE = re.compile("(\.(src|href|data|location|code|action)\s*[\"'\]]*\s*\+?\s*=)|((replace|assign|navigate|getResponseHeader|open(Dialog)?|showModalDialog|eval|evaluate|execCommand|execScript|setTimeout|setInterval)\s*[\"'\]]*\s*\()")
        self.domXSSjQuerySinksRE = re.compile("after\(|\.append\(|\.before\(|\.html\(|\.prepend\(|\.replaceWith\(|\.wrap\(|\.wrapAll\(|\$\(|\.globalEval\(|\.add\(|jQUery\(|\$\(|\.parseHTML\(")
        self.headerSTSRE = re.compile("^Strict-Transport-Security:.*?max-age=\"?(\d+)\"?", re.I) # TODO: multiple max-age directives cause confusion!
        self.headerXCTORE = re.compile("^X-Content-Type-Options:\s*nosniff\s*$", re.I)
        self.headerXXP = re.compile("^X-XSS-Protection:\s*(\d)(?:\s*;\s*mode\s*=\s*\"?(block)\"?)?", re.I)
        self.headerLocationHTTPS = re.compile("^(?:Content-)?Location:\s*(https://.*)$", re.I)

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

    def defineCheckBox(self, caption, selected=True, enabled=True):
        checkBox = JCheckBox(caption)
        checkBox.setSelected(selected)
        checkBox.setEnabled(enabled)
        return checkBox

    def setSTSMinimum(self, e=None):
        val = self.inSTSMin.text
        if re.match("^\d+$", val):
            STSMinimum = int(val)
        else:
            self.inSTSMin.setText(str(STSMinimum))   # TODO: doesn't works as desired

    def saveConfig(self, e=None):
        config = {
            'passiveChecks': self.cbPassiveChecks.isSelected(),
            'DOMXSS': self.cbDOMXSS.isSelected(),
            'DOMXSSSources': self.cbDOMXSSSources.isSelected(),
            'DOMXSSSinks': self.cbDOMXSSSinks.isSelected(),
            'DOMXSSjQuerySinks': self.cbDOMXSSjQuerySinks.isSelected(),
            'STS': self.cbSTS.isSelected(),
            'STSMin': self.inSTSMin.text,
            'XCTO': self.cbXCTO.isSelected(),
            'XXP': self.cbXXP.isSelected(),
            'RedirToHTTPS': self.cbRedirToHTTPS.isSelected(),
            }
        self.callbacks.saveExtensionSetting("config", pickle.dumps(config))

    def restoreConfig(self, e=None):
        storedConfig = self.callbacks.loadExtensionSetting("config")
        if storedConfig != None:
            try:
                config = pickle.loads(storedConfig)
                self.cbPassiveChecks.setSelected(config['passiveChecks'])
                self.cbDOMXSS.setSelected(config['DOMXSS'])
                self.cbDOMXSSSources.setSelected(config['DOMXSSSources'])
                self.cbDOMXSSSinks.setSelected(config['DOMXSSSinks'])
                self.cbDOMXSSjQuerySinks.setSelected(config['DOMXSSjQuerySinks'])
                self.cbSTS.setSelected(config['STS'])
                self.inSTSMin.text = config['STSMin'] 
                self.cbXCTO.setSelected(config['XCTO'])
                self.cbXXP.setSelected(config['XXP'])
                self.cbRedirToHTTPS.setSelected(config['RedirToHTTPS'])
                self.setSTSMinimum()
            except:
                print("Classical case of \"shouldn't happen\": something went wrong with config restore. Submit a bug or patch and keep your eyes open for Zombies. Something is really strange here.\nConfig contained: " + storedConfig)
        
    ### ITab ###
    def getTabCaption(self):
        return("Additional Scanner Checks")

    def getUiComponent(self):
        return self.tab

    ### IScannerCheck ###
    def doPassiveScan(self, baseRequestResponse):
        if not self.cbPassiveChecks.isSelected():
            return None
        scanIssues = list()
        requestProtocol = baseRequestResponse.getHttpService().getProtocol()
        analyzedResponse = self.helpers.analyzeResponse(baseRequestResponse.getResponse())
        responseHeaders = analyzedResponse.getHeaders()
        bodyOffset = analyzedResponse.getBodyOffset()
        responseBody = baseRequestResponse.getResponse()[analyzedResponse.getBodyOffset():].tostring()

        # Identify DOMXSS sources and sinks
        domXSSSources = list()
        domXSSSinks = list()
        domXSSjQuerySinks = list()
        
        if self.cbDOMXSS.isSelected():
            if self.cbDOMXSSSources.isSelected():
                domXSSSources = self.domXSSSourcesRE.finditer(responseBody)
            if self.cbDOMXSSSinks.isSelected():
                domXSSSinks = self.domXSSSinksRE.finditer(responseBody)
            if self.cbDOMXSSjQuerySinks.isSelected():
                domXSSjQuerySinks = self.domXSSjQuerySinksRE.finditer(responseBody)

            domXSSSourcesPos = extractMatchPositions(domXSSSources, bodyOffset)
            domXSSSinksPos = extractMatchPositions(domXSSSinks, bodyOffset)
            domXSSjQuerySinksPos = extractMatchPositions(domXSSjQuerySinks, bodyOffset)

            if len(domXSSSourcesPos) + len(domXSSSinksPos) + len(domXSSjQuerySinksPos) > 0: # One of the DOMXSS REs matched
                scanIssues.append(DOMXSSScanIssue(
                    baseRequestResponse,
                    domXSSSourcesPos,
                    domXSSSinksPos,
                    domXSSjQuerySinksPos,
                    self.helpers,
                    self.callbacks
                    ))

        # Identify missing, wrong or multiple occurring HTTP headers
        headersSTS = list()
        headersXCTO = list()
        headersXXP = list()
        headersLocationHTTPS = list()

        offset = 0
        for header in responseHeaders:
            if self.cbSTS.isSelected():
                match = self.headerSTSRE.match(header)
                if match:
                    headersSTS.append((match, offset))

            if self.cbXCTO.isSelected():
                match = self.headerXCTORE.match(header)
                if match:
                    headersXCTO.append(match)

            if self.cbXXP.isSelected():
                match = self.headerXXP.match(header)
                if match:
                    headersXXP.append((match, offset))

            if self.cbRedirToHTTPS.isSelected() and requestProtocol == 'http':
                match = self.headerLocationHTTPS.match(header)
                if match:
                    headersLocationHTTPS.append((match, offset))

            offset += len(header) + 2     # TODO: assumption that CRLF is always used. The world is ugly, make a real check.

        if requestProtocol != "https":
            pass                          # HSTS only valid in HTTPS responses.
        elif self.cbSTS.isSelected():
            if len(headersSTS) == 0:        # No HSTS header
                scanIssues.append(STSScanIssue(
                    baseRequestResponse,
                    STSScanIssue.caseNoHeader,
                    None,
                    self.helpers,
                    self.callbacks
                    ))
            elif len(headersSTS) == 1 and int(headersSTS[0][0].group(1)) < STSMinimum: # HSTS header present, but time frame too short
                scanIssues.append(STSScanIssue(
                    baseRequestResponse,
                    STSScanIssue.caseTooLow,
                    (int(headersSTS[0][0].group(1)), headersSTS[0][1] + headersSTS[0][0].start(1), headersSTS[0][1] + headersSTS[0][0].end(1)),
                    self.helpers,
                    self.callbacks
                    ))
            elif len(headersSTS) > 1:         # multiple HSTS headers
                scanIssues.append(STSScanIssue(
                    baseRequestResponse,
                    STSScanIssue.caseMultipleHeaders,
                    headersSTS,
                    self.helpers,
                    self.callbacks
                    ))

        # Redirection from HTTP to HTTPS
        if self.cbRedirToHTTPS.isSelected() and len(headersLocationHTTPS) > 0:
            scanIssues.append(RedirectFromHTTP2HTTPSScanIssue(
                baseRequestResponse,
                headersLocationHTTPS,
                self.helpers,
                self.callbacks                
                ))

        if self.cbXXP.isSelected():
            if len(headersXXP) == 0:          # No XSS protection header
                scanIssues.append(XXPScanIssue(
                    baseRequestResponse,
                    XXPScanIssue.caseNoHeader,
                    None,
                    self.helpers,
                    self.callbacks
                    ))
            elif len(headersXXP) == 1 and int(headersXXP[0][0].group(1)) == 1 and headersXXP[0][0].group(2) != "block":          # Activated but not in block mode
                scanIssues.append(XXPScanIssue(
                    baseRequestResponse,
                    XXPScanIssue.caseNoBlockMode,
                    headersXXP,
                    self.helpers,
                    self.callbacks
                    ))
            elif len(headersXXP) > 1:          # Multiple XXP headers
                scanIssues.append(XXPScanIssue(
                    baseRequestResponse,
                    XXPScanIssue.caseMultipleHeaders,
                    headersXXP,
                    self.helpers,
                    self.callbacks
                    ))
                # "X-XSS-Protection: 0" already catched by Burp
            

        # X-Content-Type-Options missing
        # NOTE: it is assumed that multiple "X-Content-Type-Options: nosniff" headers can't cause confusion at browser side because they all have the same meaning.
        if self.cbXCTO.isSelected() and len(headersXCTO) == 0:
            scanIssues.append(XCTOScanIssue(
                baseRequestResponse,
                self.helpers,
                self.callbacks
                ))

        return scanIssues

    def consolidateDuplicateIssues(self, existingIssue, newIssue):
        if existingIssue.getIssueName() == newIssue.getIssueName():
            if newIssue.getIssueName() == issueNameDOMXSS:   # DOMXSS issues are different if response content is different.
                responseExisting = existingIssue.getHttpMessages()[0].getResponse()
                analyzedResponseExisting = self.helpers.analyzeResponse(responseExisting)
                bodyOffsetExisting = analyzedResponseExisting.getBodyOffset()
                responseBodyExisting = responseExisting.getResponse()[analyzedResponseExisting.getBodyOffset():].tostring()

                responseNew = newIssue.getHttpMessages()[0].getResponse()
                analyzedResponseNew = self.helpers.analyzeResponse(responseNew)
                bodyOffsetNew = analyzedResponseNew.getBodyOffset()
                responseBodyNew = responseNew.getResponse()[analyzedResponseNew.getBodyOffset():].tostring()

                if responseBodyExisting == responseBodyNew:
                    return -1
                else:
                    return 0
            elif newIssue.getIssueName() == issueNameRedirectFromHTTP2HTTPS: # Redirection issues are different if target URLs differ
                if existingIssue.getIssueDetail() == newIssue.getIssueDetail():
                    return -1
                else:
                    return 0
            else:                         # In all other cases: keep existing issue
                return -1
        return 0
예제 #29
0
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener):
    """ generated source for class ConfigurableConfigPanel """
    serialVersionUID = 1L
    associatedFile = File()
    associatedFileField = JTextField()
    params = JSONObject()
    savedParams = str()
    loadButton = JButton()
    saveAsButton = JButton()
    saveButton = JButton()
    name = JTextField()
    strategy = JComboBox()
    metagameStrategy = JComboBox()
    stateMachine = JComboBox()
    cacheStateMachine = JCheckBox()
    maxPlys = JSpinner()
    heuristicFocus = JSpinner()
    heuristicMobility = JSpinner()
    heuristicOpponentFocus = JSpinner()
    heuristicOpponentMobility = JSpinner()
    mcDecayRate = JSpinner()
    rightPanel = JPanel()

    def __init__(self):
        """ generated source for method __init__ """
        super(ConfigurableConfigPanel, self).__init__(GridBagLayout())
        leftPanel = JPanel(GridBagLayout())
        leftPanel.setBorder(TitledBorder("Major Parameters"))
        self.rightPanel = JPanel(GridBagLayout())
        self.rightPanel.setBorder(TitledBorder("Minor Parameters"))
        self.strategy = JComboBox([None]*)
        self.metagameStrategy = JComboBox([None]*)
        self.stateMachine = JComboBox([None]*)
        self.cacheStateMachine = JCheckBox()
        self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1))
        self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1))
        self.name = JTextField()
        self.name.setColumns(20)
        self.name.setText("Player #" + Random().nextInt(100000))
        self.loadButton = JButton(loadButtonMethod())
        self.saveButton = JButton(saveButtonMethod())
        self.saveAsButton = JButton(saveAsButtonMethod())
        self.associatedFileField = JTextField()
        self.associatedFileField.setEnabled(False)
        buttons = JPanel()
        buttons.add(self.loadButton)
        buttons.add(self.saveButton)
        buttons.add(self.saveAsButton)
        nRow = 0
        leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_0 = nRow
        nRow += 1
        leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_1 = nRow
        nRow += 1
        leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_2 = nRow
        nRow += 1
        leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_3 = nRow
        nRow += 1
        leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        __nRow_4 = nRow
        nRow += 1
        leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0))
        leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0))
        layoutRightPanel()
        add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.params = JSONObject()
        syncJSONtoUI()
        self.strategy.addActionListener(self)
        self.metagameStrategy.addActionListener(self)
        self.stateMachine.addActionListener(self)
        self.cacheStateMachine.addActionListener(self)
        self.maxPlys.addChangeListener(self)
        self.heuristicFocus.addChangeListener(self)
        self.heuristicMobility.addChangeListener(self)
        self.heuristicOpponentFocus.addChangeListener(self)
        self.heuristicOpponentMobility.addChangeListener(self)
        self.mcDecayRate.addChangeListener(self)
        self.name.getDocument().addDocumentListener(self)

    def layoutRightPanel(self):
        """ generated source for method layoutRightPanel """
        nRow = 0
        self.rightPanel.removeAll()
        self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_5 = nRow
        nRow += 1
        self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Heuristic":
        __nRow_6 = nRow
        nRow += 1
        __nRow_7 = nRow
        nRow += 1
        __nRow_8 = nRow
        nRow += 1
        __nRow_9 = nRow
        nRow += 1
        __nRow_10 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Monte Carlo":
        __nRow_11 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_12 = nRow
        nRow += 1
        self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        self.rightPanel.repaint()

    @SuppressWarnings("unchecked")
    def getParameter(self, name, defaultValue):
        """ generated source for method getParameter """
        try:
            if self.params.has(name):
                return self.params.get(name)
            else:
                return defaultValue
        except JSONException as je:
            return defaultValue

    def actionPerformed(self, arg0):
        """ generated source for method actionPerformed """
        if arg0.getSource() == self.strategy:
            self.layoutRightPanel()
        syncJSONtoUI()

    def changedUpdate(self, e):
        """ generated source for method changedUpdate """
        syncJSONtoUI()

    def insertUpdate(self, e):
        """ generated source for method insertUpdate """
        syncJSONtoUI()

    def removeUpdate(self, e):
        """ generated source for method removeUpdate """
        syncJSONtoUI()

    def stateChanged(self, arg0):
        """ generated source for method stateChanged """
        syncJSONtoUI()

    def syncJSONtoUI(self):
        """ generated source for method syncJSONtoUI """
        if settingUI:
            return
        self.params = getJSONfromUI()
        self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams)

    def getJSONfromUI(self):
        """ generated source for method getJSONfromUI """
        newParams = JSONObject()
        try:
            if not self.name.getText().isEmpty():
                newParams.put("name", self.name.getText())
            newParams.put("strategy", self.strategy.getSelectedItem().__str__())
            newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__())
            newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__())
            newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected())
            newParams.put("maxPlys", self.maxPlys.getModel().getValue())
            newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue())
            newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue())
            newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue())
            newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue())
            newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue())
        except JSONException as je:
            je.printStackTrace()
        return newParams

    settingUI = False

    def setUIfromJSON(self):
        """ generated source for method setUIfromJSON """
        self.settingUI = True
        try:
            if self.params.has("name"):
                self.name.setText(self.params.getString("name"))
            if self.params.has("strategy"):
                self.strategy.setSelectedItem(self.params.getString("strategy"))
            if self.params.has("metagameStrategy"):
                self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy"))
            if self.params.has("stateMachine"):
                self.stateMachine.setSelectedItem(self.params.getString("stateMachine"))
            if self.params.has("cacheStateMachine"):
                self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine"))
            if self.params.has("maxPlys"):
                self.maxPlys.getModel().setValue(self.params.getInt("maxPlys"))
            if self.params.has("heuristicFocus"):
                self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus"))
            if self.params.has("heuristicMobility"):
                self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility"))
            if self.params.has("heuristicOpponentFocus"):
                self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus"))
            if self.params.has("heuristicOpponentMobility"):
                self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility"))
            if self.params.has("mcDecayRate"):
                self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate"))
        except JSONException as je:
            je.printStackTrace()
        finally:
            self.settingUI = False

    def loadParamsJSON(self, fromFile):
        """ generated source for method loadParamsJSON """
        if not fromFile.exists():
            return
        self.associatedFile = fromFile
        self.associatedFileField.setText(self.associatedFile.getPath())
        self.params = JSONObject()
        try:
            try:
                while (line = br.readLine()) != None:
                    pdata.append(line)
            finally:
                br.close()
            self.params = JSONObject(pdata.__str__())
            self.savedParams = self.params.__str__()
            self.setUIfromJSON()
            self.syncJSONtoUI()
        except Exception as e:
            e.printStackTrace()

    def saveParamsJSON(self, saveAs):
        """ generated source for method saveParamsJSON """
        try:
            if saveAs or self.associatedFile == None:
                fc.setFileFilter(PlayerFilter())
                if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None:
                    if toFile.__name__.contains("."):
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player")
                    else:
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player")
                    self.associatedFileField.setText(self.associatedFile.getPath())
                else:
                    return
            bw.write(self.params.__str__())
            bw.close()
            self.savedParams = self.params.__str__()
            self.syncJSONtoUI()
        except IOException as ie:
            ie.printStackTrace()

    def saveButtonMethod(self):
        """ generated source for method saveButtonMethod """
        return AbstractAction("Save")

    def saveAsButtonMethod(self):
        """ generated source for method saveAsButtonMethod """
        return AbstractAction("Save As")

    def loadButtonMethod(self):
        """ generated source for method loadButtonMethod """
        return AbstractAction("Load")

    class PlayerFilter(FileFilter):
        """ generated source for class PlayerFilter """
        def accept(self, f):
            """ generated source for method accept """
            if f.isDirectory():
                return True
            return f.__name__.endsWith(".player")

        def getDescription(self):
            """ generated source for method getDescription """
            return "GGP Players (*.player)"
예제 #30
0
파일: mpconfig.py 프로젝트: DMDhariya/core
class MPConfig(TreeSelectionListener):
    """The MPConfig component initializes the KConfig library with the requested configuration,
    and buildst the GUI, consisting of a "Load" and a "Save as" buttons, a search field, "show all"
    checkbox, tree view and information text view."""
    def __init__(self,
                 kconfig_file="Kconfig",
                 config_file=".config",
                 systemLogger=None):
        """[summary]

        Parameters
        ----------
            kconfig_file : string (default: "Kconfig")
                The Kconfig configuration file
            config_file : string (default: ".config")
                The save file which will be used for loading and saving the settings
            systemLogger (default: None)
                A system logger object. If None then print statements are used for logging.
        """
        global log
        if systemLogger:
            log = systemLogger

        # Load Kconfig configuration files
        self.kconfig = Kconfig(kconfig_file)
        setKConfig(self.kconfig)

        if os.path.isfile(config_file):
            log.info(self.kconfig.load_config(config_file))
        elif os.path.isfile(".config"):
            log.info(self.kconfig.load_config(".config"))

        self.tree = KConfigTree(self.kconfig)
        self.tree.addTreeSelectionListener(self.treeSelectionChanged)
        jTreeSP = JScrollPane(self.tree)

        self.jta = JTextArea()
        self.jta.setEditable(False)
        jTextSP = JScrollPane(self.jta)

        toolPanel = JPanel()
        toolPanel.setLayout(BoxLayout(toolPanel, BoxLayout.X_AXIS))
        toolPanel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0))

        toolPanel.add(JLabel("Search: "))

        jSearchPanel = JPanel()
        jSearchPanel.setLayout(BoxLayout(jSearchPanel, BoxLayout.X_AXIS))
        self.jSearchField = JTextField()
        jSearchPanel.setBackground(self.jSearchField.getBackground())
        jSearchPanel.setBorder(self.jSearchField.getBorder())
        self.jSearchField.setBorder(None)
        self.jSearchField.getDocument().addDocumentListener(
            SearchListener(self.tree))
        jSearchPanel.add(self.jSearchField)

        clearSearchButton = JButton(u'\u00d7',
                                    actionPerformed=self.clearSearch)
        d = clearSearchButton.getPreferredSize()
        clearSearchButton.setPreferredSize(Dimension(d.height, d.height))
        clearSearchButton.setBackground(self.jSearchField.getBackground())
        clearSearchButton.setBorder(None)
        clearSearchButton.setOpaque(False)
        clearSearchButton.setContentAreaFilled(False)
        clearSearchButton.setFocusPainted(False)
        jSearchPanel.add(clearSearchButton)

        toolPanel.add(jSearchPanel)

        self.showAllCheckBox = JCheckBox("Show all",
                                         actionPerformed=self.OnShowAllCheck)
        toolPanel.add(self.showAllCheckBox)

        splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT, jTreeSP, jTextSP)
        splitPane.setOneTouchExpandable(True)
        splitPane.setDividerLocation(300)

        treePanel = JPanel(BorderLayout())
        treePanel.add(toolPanel, BorderLayout.NORTH)
        treePanel.add(splitPane, BorderLayout.CENTER)

        loadSavePanel = JPanel()
        loadSavePanel.setLayout(BoxLayout(loadSavePanel, BoxLayout.X_AXIS))
        loadSavePanel.add(
            JButton("Load", actionPerformed=self.loadConfigDialog))
        loadSavePanel.add(
            JButton("Save as", actionPerformed=self.writeConfigDialog))

        self.rootPanel = JPanel()
        self.rootPanel.setLayout(BorderLayout())
        self.rootPanel.add(loadSavePanel, BorderLayout.PAGE_START)
        self.rootPanel.add(treePanel, BorderLayout.CENTER)

    def clearSearch(self, event):
        self.jSearchField.setText("")

    def OnShowAllCheck(self, event):
        self.tree.setShowAll(self.showAllCheckBox.isSelected())
        self.tree.doSearch(self.jSearchField.getText()
                           )  # Must repeat the search if one is active

    def treeSelectionChanged(self, event):
        """When the user selects a new node in the tree, show info about the selected node
        in the info text area below the tree."""
        path = event.getNewLeadSelectionPath()
        if path:
            comp = path.getLastPathComponent()
            if isinstance(comp, DefaultMutableTreeNode):
                nodeData = comp.getUserObject()
                if isinstance(nodeData, TreeNodeData):
                    self.jta.setText(getNodeInfoString(nodeData.knode))
                    self.jta.setCaretPosition(0)

    def getPane(self):
        """Return the panel containing all the other components that is set up in __init__()."""
        return self.rootPanel

    def writeConfig(self, fileName):
        """Write the current configuration to the file specified."""
        self.kconfig.write_config(fileName)  # Save full configuration
        #self.kconfig.write_min_config(fileName) # Save minimal configuration

    def loadConfig(self, fileName):
        """Load configuration settings from the file specified."""
        if os.path.isfile(fileName):
            log.info(self.kconfig.load_config(fileName))
            self.tree.createKconfShadowModel(self.kconfig)
            self.tree.updateTree()

    def writeConfigDialog(self, e):
        """Open a file dialog to save configuration"""
        fileChooser = JFileChooser(os.getcwd())
        retval = fileChooser.showSaveDialog(None)
        if retval == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            self.writeConfig(f.getPath())

    def loadConfigDialog(self, e):
        """Open a file dialog to select configuration to load"""
        fileChooser = JFileChooser(os.getcwd())
        retval = fileChooser.showOpenDialog(None)
        if retval == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            log.info("Selected file: " + f.getPath())
            self.loadConfig(f.getPath())
class DemultiplexGUI(Runnable):

    global SampleSheet
    
    def __init__(self):

        self.f = JFrame("Demultiplex the data")
        self.f.setSize(1250, 1000)
        self.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        
        #Progress Monitor
        self.pm=JProgressBar(100,100)
        
        #Lane Area
        self.LaneAre=JPanel()
        self.lane1=JCheckBox("Lane 1", True)
        self.lane2=JCheckBox("Lane 2", True)
        self.lane3=JCheckBox("Lane 3", True)
        self.lane4=JCheckBox("Lane 4", True)
        self.lane5=JCheckBox("Lane 5", True)
        self.lane6=JCheckBox("Lane 6", True)
        self.lane7=JCheckBox("Lane 7", True)
        self.lane8=JCheckBox("Lane 8", True)
        self.LaneAre.add(self.lane1)
        self.LaneAre.add(self.lane2)
        self.LaneAre.add(self.lane3)
        self.LaneAre.add(self.lane4)
        self.LaneAre.add(self.lane5)
        self.LaneAre.add(self.lane6)
        self.LaneAre.add(self.lane7)
        self.LaneAre.add(self.lane8)
        
        self.txtArea = JPanel(GridLayout(15,0))
        #self.txtArea.setPreferredSize(Dimension(150, 150))
        self.textAreaForSheet = JTextField(30)
        self.textAreaInputForFolder = JTextField(30)
        self.textAreaOutPutFolder= JTextField(30)
        self.txtArea.add(self.textAreaForSheet)
        self.txtArea.add(self.textAreaInputForFolder)
        self.txtArea.add(self.textAreaOutPutFolder)
        self.txtArea.add(self.LaneAre)
        
        self.buttonArea = JPanel(GridLayout(15,0))
        #self.buttonArea.setPreferredSize(Dimension(150, 150))
        self.sampleSheetBtn = JButton("SampleSheet", actionPerformed=self.onClickSample)
        self.runOutPutFolder = JButton("RUN Folder",actionPerformed=self.onClickRun)
        self.DemultiplexOutPutFolder = JButton("Output Folder",actionPerformed=self.onClickOut)
        self.buttonArea.add(self.sampleSheetBtn)
        self.buttonArea.add(self.runOutPutFolder)
        self.buttonArea.add(self.DemultiplexOutPutFolder)
        
        self.CheckBox = JPanel(GridLayout(15,0))
        #self.buttonArea.setPreferredSize(Dimension(150, 150))
        self.Iter1 = JCheckBox("01_0M_NY", True,)
        self.Iter2 = JCheckBox("02_0M_N", True,)
        self.Iter3 = JCheckBox("03_1M_NY", True,)
        self.Iter4 = JCheckBox("04_1M_N", True,)
        
        self.CheckBox.add(self.Iter1)
        self.CheckBox.add(self.Iter2)
        self.CheckBox.add(self.Iter3)
        self.CheckBox.add(self.Iter4)

        self.ExecutePanel = JPanel()
        self.console=JTextArea(20,100)
        
        self.sp = JScrollPane(self.console);
        self.RunBtn = JButton("Demultiplex",actionPerformed= self.performDemultiplex)
        self.CanBtn = JButton("Cancel",actionPerformed= self.CancelJob)

        self.ExecutePanel.add(self.RunBtn)
        self.ExecutePanel.add(self.CanBtn)
        self.ExecutePanel.add(self.sp, BorderLayout.CENTER)

        self.f.add(self.txtArea, BorderLayout.CENTER)
        self.f.add(self.buttonArea, BorderLayout.WEST)
        self.f.add(self.CheckBox, BorderLayout.EAST)
        self.f.add(self.ExecutePanel, BorderLayout.NORTH)
        self.f.add(self.pm,BorderLayout.SOUTH)
        
    def run(self):
        self.f.setVisible(True)

    def onClickRun(self,event=""):
        self.DirName= FolderChooser(self.f)
        self.textAreaInputForFolder.setText(str(self.DirName))

    def onClickOut(self,event=""):
        self.OutDirName= FolderChooser(self.f)
        self.textAreaOutPutFolder.setText(str(self.OutDirName))
    
    def onClickSample(self,event):
        self.sampleSheet=FileChooser(self.f)
        self.textAreaForSheet.setText(str(self.sampleSheet))
        
    def performDemultiplex(self,event):
        NumberOfIterations=[self.Iter1.selected,self.Iter2.selected,self.Iter3.selected,self.Iter4.selected]
        LaneNumber=[self.lane1.selected,self.lane2.selected,self.lane3.selected,self.lane4.selected,self.lane5.selected,self.lane6.selected,self.lane7.selected,self.lane8.selected]
        selectedLanes = [str(i+1) for i, x in enumerate(LaneNumber) if x==True]
        lanes=','.join(selectedLanes)
        print LaneNumber,selectedLanes,lanes, lanes
        self.task = ET.Task(self,NumberOfIterations,str(self.sampleSheet),str(self.DirName),str(self.OutDirName), lanes)
        self.task.execute()

    def CancelJob(self,event):
        self.task.cancel(True)
    def output(self, value):
        eingabe = value.getString()
        if eingabe == "Lexikon":
            # Falls "Lexikon" an den Clienten übergeben wird, wird die GUI geöffnet,
            # in der man deutsche Wörter eingeben kann, die einem dann auf Englisch
            # vorgelesen werden.
            def change_text(event):
                text = feld.getText()
                x = suche(text)
                self.send(x)
                frame.visible = False

            frame = JFrame(
                'Woerterbuch',
                defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                size=(380, 350),
            )
            frame.setLayout(None)
            frame.visible = True
            hintergrund = ImageIcon("Hintergrund.jpg")
            hintergrundlabel = JLabel(hintergrund)
            frame.setContentPane(hintergrundlabel)

            uebersetzerlabel = JLabel()
            uebersetzerlabel.setForeground(Color(025, 025, 112))
            uebersetzerlabel.setText(
                "<html><font size=+1>Welches Wort soll ich uebersetzen?</font></html>"
            )
            uebersetzerlabel.setBounds(10, 20, 500, 50)
            frame.add(uebersetzerlabel)

            feld = JTextField()
            feld.setText("")
            feld.setBounds(20, 80, 300, 25)
            frame.add(feld)

            button = JButton('Uebersetzen',
                             actionPerformed=change_text,
                             size=(10, 20))
            button.setBounds(20, 110, 300, 30)
            frame.add(button)

        if eingabe == "neue Lektion":
            # Falls dem Clienten "neue Lektion" übergeben wird, öffnet er er die
            # GUI für das Verwalten der Lektionen
            frame = JFrame('Lektion erstellen',
                           defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                           size=(1000, 1000))
            frame.setLayout(None)

            def auflisten_in(ort):
                font = Font("Verdana", Font.BOLD, 15)
                liste_mit_Lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        liste_mit_Lektionen.append(line.strip())
                liste_mit_Lektionen.sort()
                text = ""
                for lektion in liste_mit_Lektionen:
                    text += lektion
                    text += "\n"
                ort.setText(text)
                ort.setFont(font)
                frame.setLayout(None)
                uebersichtLabel = JLabel()

            def uebersetzen(event):
                frage = feld_frage.getText()
                x = suche(frage)
                feld_frage.setText(x)
                liste = []
                with open(pfad, "r") as lektionen:
                    for lektion in lektionen:
                        if "nachgeschlagen" in lektion:
                            liste.append(lektion)
                if liste:
                    name = liste[-1]
                    words = []
                    sql = "SELECT deutsch, englisch, symbol FROM " + name
                    zeile = stmt.executeQuery(sql)
                    while zeile.next():
                        d = zeile.getString("deutsch")
                        e = zeile.getString("englisch")
                        symb = zeile.getString("symbol")
                        words.append((d, e, symb))
                    if len(words) < 50:
                        sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                        pstmt = conn.prepareStatement(sql)
                        pstmt.setString(1, frage)
                        pstmt.setString(2, x)
                        pstmt.setString(3, "X")
                        pstmt.executeUpdate()
                    else:
                        namensteile = name.split("_")
                        nummer = int(namensteile[1].strip()) + 1
                        name = "nachgeschlagen_" + str(nummer)
                        test = ""
                        with open(pfad, "r") as f:
                            for line in f:
                                test += line
                        if not name in test:
                            with open(pfad, "a") as f:
                                f.write(name + "\n")
                        sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                        stmt.execute(sql)
                        sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                        pstmt = conn.prepareStatement(sql)
                        pstmt.setString(1, frage)
                        pstmt.setString(2, x)
                        pstmt.setString(3, "X")
                        pstmt.executeUpdate()
                else:
                    name = "nachgeschlagen_1"
                    test = ""
                    with open(pfad, "r") as f:
                        for line in f:
                            test += line
                    if not name in test:
                        with open(pfad, "a") as f:
                            f.write(name + "\n")
                    sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                    stmt.execute(sql)
                    sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                    pstmt = conn.prepareStatement(sql)
                    pstmt.setString(1, frage)
                    pstmt.setString(2, x)
                    pstmt.setString(3, "X")
                    pstmt.executeUpdate()
                auflisten_in(uebersicht)

            def delete(event):
                name = feld.getText()
                print name
                print self.geladen
                if name == self.geladen:
                    count = 0
                    while tabelle.getValueAt(count, 0) != None:
                        tabelle.setValueAt(None, count, 0)
                        tabelle.setValueAt(None, count, 1)
                        count += 1
                stmt.execute("DROP TABLE " + name + ";")
                lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        lektion = line.strip()
                        if not name == lektion:
                            lektionen.append(lektion)
                with open(pfad, "w") as f:
                    for lektion in lektionen:
                        f.write(lektion + "\n")
                auflisten_in(uebersicht)

            def laden(event):
                name = feld.getText()
                self.geladen = name
                sql = "SELECT deutsch, englisch FROM " + name
                results = stmt.executeQuery(sql)
                count = 0
                while results.next():
                    d = results.getString("deutsch")
                    e = results.getString("englisch")
                    tabelle.setValueAt(d, count, 0)
                    tabelle.setValueAt(e, count, 1)
                    count += 1
                while tabelle.getValueAt(count, 0) != None:
                    tabelle.setValueAt(None, count, 0)
                    tabelle.setValueAt(None, count, 1)
                    count += 1

            def erstelle_Lektionstabelle(event):
                reihen = []
                for i in range(0, 50):
                    deutsch = tabelle.getValueAt(i, 0)
                    englisch = tabelle.getValueAt(i, 1)
                    if deutsch != None:
                        symbol = "X"
                        reihen.append([deutsch, englisch, symbol])
                    else:
                        break
                z = 0
                name = feld.getText()
                sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);"
                try:
                    stmt.execute(sql)
                except SQLError:
                    stmt.execute("DROP TABLE " + name + ";")
                    stmt.execute(sql)
                for reihe in reihen:
                    print(reihe)
                    deutsch = reihe[0]
                    englisch = reihe[1]
                    symbol = reihe[2]
                    sql = "INSERT INTO " + name + " (deutsch, englisch, symbol)  VALUES(?,?,?);"
                    pstmt = conn.prepareStatement(sql)
                    pstmt.setString(1, deutsch)
                    pstmt.setString(2, englisch)
                    pstmt.setString(3, symbol)
                    pstmt.executeUpdate()
                test = ""
                with open(pfad, "r") as f:
                    for line in f:
                        test += line
                if not name in test:
                    with open(pfad, "a") as f:
                        f.write(name + "\n")
                self.send(name)
                frame.setVisible(False)

            frame = JFrame('Vokabel Listen',
                           defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                           size=(1000, 1000))
            frame.setLayout(None)
            label_enter = JLabel()
            label_enter.setText(
                "<html><font size=+0.5 color = 000000>Bitte vor dem Speichern<br>die Entertaste bedienen</font></html>"
            )
            label_enter.setBounds(20, 720, 250, 50)
            uebersichtLabel = JLabel()
            uebersichtLabel.setText(
                "<html><font size=+1 color=#191970>Bereits vorhandene Lektionen:</font></html>"
            )
            uebersichtLabel.setBounds(450, 230, 250, 50)
            uebersicht = JTextArea()
            uebersicht.editable = False
            uebersicht_scroll = JScrollPane(uebersicht)
            uebersicht_scroll.viewport.view = uebersicht
            uebersicht_scroll.setBounds(450, 300, 250, 380)
            auflisten_in(uebersicht)
            button = JButton('Lektion speichern/Lektion reseten',
                             actionPerformed=erstelle_Lektionstabelle,
                             size=(10, 20))
            button.setBounds(20, 700, 300, 30)
            button_laden = JButton('vorhandene Lektion laden',
                                   actionPerformed=laden,
                                   size=(10, 20))
            button_laden.setBounds(20, 110, 210, 30)
            button_delete = JButton("Lektion entfernen",
                                    actionPerformed=delete)
            button_delete.setBounds(20, 140, 210, 30)
            hintergrund = ImageIcon("Hintergrund.jpg")
            pnl = JPanel()
            hintergrundlabel = JLabel(hintergrund)
            frame.setContentPane(hintergrundlabel)
            lektionsnamensLabel = JLabel()
            lektionsnamensLabel.setForeground(Color(025, 025, 112))
            lektionsnamensLabel.setText(
                "<html><font size=+1>Hier bitte Namen der Lektion eingeben<br>(Nur ein Wort lang)</font></html>"
            )
            lektionsnamensLabel.setBounds(10, 20, 500, 50)
            frame.add(lektionsnamensLabel)
            feld = JTextField()
            feld.setText("")
            feld.setBounds(20, 80, 210, 25)
            frame.add(feld)
            column_names = [
                "<html><font size=+1 color=#191970><b>Deutsch</b></font></html>",
                "<html><font size=+1 color=#191970><b>Englisch</b></font></html>"
            ]
            table_model = DefaultTableModel(column_names, 50)
            tabelle = JTable(table_model)
            lektionsnamensLabel.setForeground(Color(025, 025, 112))
            scrollbar = JScrollPane(tabelle)
            scrollbar.viewport.view = tabelle
            scrollbar.setVerticalScrollBarPolicy(
                scrollbar.VERTICAL_SCROLLBAR_ALWAYS)
            scrollbar.setVisible(True)
            tabelle.setVisible(True)
            scrollbar.setBounds(20, 190, 300, 490)
            feld_frage = JTextField()
            feld_frage.setText("")
            feld_frage.setBounds(450, 30, 300, 50)
            uebersetzerlabel = JLabel()
            uebersetzerlabel.setForeground(Color(025, 025, 112))
            uebersetzerlabel.setText(
                "<html><font size=+1>Hier kannst Du ein deutsches Wort eintragen,<br>dass ich fuer Dich nachschlage</font></html>"
            )
            uebersetzerlabel.setBounds(450, 80, 500, 50)
            button_uebersetzen = JButton('Uebersetzen',
                                         actionPerformed=uebersetzen,
                                         size=(10, 20))
            button_uebersetzen.setBounds(450, 130, 300, 30)
            frame.add(button_uebersetzen)
            frame.add(uebersetzerlabel)
            frame.add(feld_frage)
            frame.add(feld)
            frame.add(scrollbar)
            frame.add(button)
            frame.add(button_laden)
            frame.setVisible(True)
            frame.add(uebersicht_scroll)
            frame.add(uebersichtLabel)
            frame.add(button_delete)
            frame.add(label_enter)
        elif eingabe == "alle Lektionen auflisten":
            # Hier erstellt der Client eine dynamische Grammatik
            # mit den vorhandenen Lektionen, die man sich abfragen lassen kann
            # und gibt diese wieder an DialogOS zurück.
            # Außerdem wird der Feedback Frame geöffnet.
            def auflisten_in2(ort):
                font = Font("Verdana", Font.BOLD, 15)
                liste_mit_Lektionen = []
                with open(pfad, "r") as f:
                    for line in f:
                        liste_mit_Lektionen.append(line.strip())
                        liste_mit_Lektionen.sort()
                text = ""
                for lektion in liste_mit_Lektionen:
                    text += lektion
                    text += "\n"
                ort.setText(text)
                ort.setFont(font)

            frame_feedback.setVisible(True)
            auflisten_in2(uebersicht2)
            grammatik = ""
            grammatik = "root $NamevonLektion;\n"
            grammatik += "$NamevonLektion = "
            with open(pfad, "r") as f:
                z = 0
                for line in f:
                    if z == 0:
                        if not "_" in line:
                            grammatik += line
                        else:
                            zeile = line.split("_")
                            grammatik += zeile[0] + " "
                            grammatik += zeile[1].strip()
                    else:
                        if not "_" in line:
                            grammatik += "|" + line
                        else:
                            zeile = line.split("_")
                            grammatik += "|" + zeile[0] + " "
                            grammatik += zeile[1].strip()
                    if line != "\n":
                        z += 1
            grammatik += ";"
            self.send(grammatik)
        elif "sende" in eingabe:
            # DialogOS sagt dem Clienten, welche Lektion der User abgefragt
            # werden möchte. Der Client ließt dann die entsprechende Lektion
            # aus der Datenbank aus und gibt eine Liste mit 2 Listen zurück.
            # In der ersten Liste befinden sich die deutschen Bedeutungen, der
            # noch nicht gewussten Wörter, in der 2. Liste die englsichen Bedeutungen.
            # Falls alle Wörter bereits gekonnt wurden, wird stattdessen eine entsprechende
            # Anmerkung an DialogOS geschickt und DialogOS informiert den User darüber.
            z = 0
            if "nachgeschlagen" in eingabe:
                bestandteile = eingabe.split()
                name = bestandteile[1] + "_" + bestandteile[2]
            else:
                name = eingabe.split()[1]
            sql = "SELECT deutsch, englisch, symbol FROM " + name
            vokabelliste = stmt.executeQuery(sql)
            deutsch = []
            englisch = []
            symbol = []
            while (vokabelliste.next()):
                deutsch.append(vokabelliste.getString("deutsch"))
                englisch.append(vokabelliste.getString("englisch"))
                symbol.append(vokabelliste.getString("symbol"))

            indices = range(0, len(deutsch))
            random.shuffle(indices)
            vokabeln = [[], []]
            for index in indices:
                d = deutsch[index]
                e = englisch[index]
                s = symbol[index]
                if s == "X":
                    vokabeln[0].append(d)
                    vokabeln[1].append(e)
            if vokabeln[0]:
                self.send(vokabeln)
            else:
                self.send([
                    "Du kannst diese Lektion schon komplett. Wenn Du sie wieder abgefragt werden willst, resete sie bitte unter Wokabeln verwalten."
                ])
        else:
            # Dieser Teil des Codes wird während der Abfrage ausgeführt.
            # Nach jeder neuen Vokabel wird dann in ein Feld im Feedback
            # Frame die deutsche, die englische Vokabel und ein Symbol angezeigt,
            # welches einen darüber informiert, ob man die Vokabel wusste, oder nicht.
            # (O für gewusst und X für nicht gewusst)
            nametext = eingabe.split(":")
            name = nametext[0]
            text = nametext[1]
            feld_feedback.setText(text)
            zeilen = text.split("\n")
            symb = zeilen[-2].split("\t")[-1]
            d = zeilen[-2].split("\t")[-3]
            print d
            sql = "UPDATE " + name + " SET symbol = ? WHERE deutsch = ?"
            pstmt = conn.prepareStatement(sql)
            pstmt.setString(1, symb)
            pstmt.setString(2, d)
            pstmt.executeUpdate()
예제 #33
0
class EditSettingsView(JDialog):
    def __init__(self, controller, working_dir, servers, console_style,
                 edit_area_style, keystrokes, languages, projects):
        self.logger = logging.getLogger("NammuController")
        self.setAlwaysOnTop(True)
        self.controller = controller
        self.working_dir = working_dir
        self.servers = servers
        self.keystrokes = keystrokes
        self.languages = languages
        self.projects = projects
        self.console_fontsize = console_style['fontsize']['user']
        self.console_font_color = console_style['font_color']['user']
        self.console_bg_color = console_style['background_color']['user']
        self.edit_area_fontsize = edit_area_style['fontsize']['user']
        self.pane = self.getContentPane()

        # Grab the console color options from the console view
        self.consoleView = self.controller.controller.consoleController.view
        self.color_options = self.consoleView.colors.keys()

    def build(self):
        '''
        Create all tab panels and put together to form the settings window.
        '''
        self.setLayout(BorderLayout())
        self.add(self.build_tabbed_panel(), BorderLayout.CENTER)
        self.add(self.build_buttons_panel(), BorderLayout.SOUTH)

    def build_tabbed_panel(self):
        '''
        Build panel with tabs for each of the settings editable sections.
        '''
        tabbed_pane = JTabbedPane()
        tab_titles = ["General", "Appearance", "Keystrokes", "Languages",
                      "Projects"]
        for title in tab_titles:
            panel = self.build_settings_panel(title.lower())
            tabbed_pane.addTab(title, panel)
        return tabbed_pane

    def build_settings_panel(self, text):
        '''
        Call correspondent method to create panel for given tab text.
        '''
        panel = getattr(self, "build_{}_panel".format(text))()
        return panel

    def build_general_panel(self):
        '''
        Create the panel that'll go in the General tab. This should contain
        options for choosing which server to use for validation as well as
        default working dir.
        '''
        panel = JPanel(GridBagLayout())
        constraints = self.add_constraints(GridBagConstraints(),
                                           insets=Insets(10, 10, 10, 10))
        self.build_working_dir_panel(constraints, panel)
        self.build_servers_panel(constraints, panel)
        return panel

    def add_constraints(self, constraints, weightx=None, gridx=None,
                        gridy=None, fill=None, insets=None, gridwidth=None,
                        anchor=None):
        '''
        Wrapper around the various constraints we need to set.
        '''
        # Cant use pythonic truth value test as we need 0 to evaluate as true
        if weightx is not None:
            constraints.weightx = weightx
        if gridx is not None:
            constraints.gridx = gridx
        if gridy is not None:
            constraints.gridy = gridy
        if fill is not None:
            constraints.fill = fill
        if insets is not None:
            constraints.insets = insets
        if gridwidth is not None:
            constraints.gridwidth = gridwidth
        if anchor is not None:
            constraints.anchor = anchor

        return constraints

    def build_working_dir_panel(self, constraints, panel):
        '''
        Working directory row: label + field + button
        This is for users to browse for their preferred default directory
        when opening/creating a new file.
        '''
        working_dir_label = JLabel("Working directory:")
        constraints = self.add_constraints(constraints, weightx=0.30,
                                           gridx=0, gridy=0,
                                           anchor=GridBagConstraints.EAST)

        panel.add(working_dir_label, constraints)

        self.wd_field = JTextField()
        self.wd_field.setEditable(False)
        # Can't find an elegant way to default to something that would be
        # crossplatform, and I can't leave the default field empty.
        if self.working_dir['default'] != "None":
            self.wd_field.setText(self.working_dir['default'])
        else:
            self.wd_field.setText(os.getcwd())

        constraints = self.add_constraints(constraints, weightx=0.60,
                                           gridx=1, gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL,
                                           insets=Insets(10, 10, 10, 5))
        panel.add(self.wd_field, constraints)

        constraints.fill = 0
        button = JButton("Browse", actionPerformed=self.browse)
        constraints = self.add_constraints(constraints, weightx=0.10,
                                           gridx=2, gridy=0,
                                           insets=Insets(10, 0, 10, 10))
        panel.add(button, constraints)

    def build_console_background_color_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        console_bg_label = JLabel("Console background color:")
        constraints = self.add_constraints(constraints, weightx=0.30,
                                           gridx=0, gridy=2)
        panel.add(console_bg_label, constraints)

        self.bg_color_combo = self.build_combobox(self.color_options,
                                                  self.console_bg_color)
        constraints = self.add_constraints(constraints, weightx=0.70,
                                           gridx=1, gridy=2, gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.bg_color_combo, constraints)

    def build_console_font_color_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        console_font_label = JLabel("Console font color:")
        constraints = self.add_constraints(constraints, weightx=0.30,
                                           gridx=0, gridy=3)
        panel.add(console_font_label, constraints)

        self.font_color_combo = self.build_combobox(self.color_options,
                                                    self.console_font_color)
        constraints = self.add_constraints(constraints, weightx=0.70,
                                           gridx=1, gridy=3, gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.font_color_combo, constraints)

    def build_servers_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        server_label = JLabel("ORACC server location:")
        constraints = self.add_constraints(constraints, weightx=0.30,
                                           gridx=0, gridy=1,
                                           insets=Insets(10, 10, 80, 10))
        panel.add(server_label, constraints)

        self.combo = self.build_servers_combobox()
        constraints = self.add_constraints(constraints, weightx=0.70,
                                           gridx=1, gridy=1, gridwidth=2,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.combo, constraints)

    def build_console_font_panel(self, constraints, panel):
        '''
        Font size on a textfield.
        '''
        fontzise_label = JLabel("Console font size:")
        constraints = self.add_constraints(constraints, weightx=0.20,
                                           gridx=0, gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(fontzise_label, constraints)

        self.fs_field = JTextField()
        self.fs_field.setEditable(True)
        if self.console_fontsize:
            self.fs_field.setText("{}".format(self.console_fontsize))
        else:
            self.fs_field.setText(self.controller.config[
                                    'console_style']['fontsize']['default'])

        constraints = self.add_constraints(constraints, weightx=0.80,
                                           gridx=1, gridy=0,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.fs_field, constraints)

    def build_edit_area_font_panel(self, constraints, panel):
        '''
        Font size on a textfield.
        '''
        fontzise_label = JLabel("Edit area font size:")
        constraints = self.add_constraints(constraints, weightx=0.20,
                                           gridx=0, gridy=4)
        panel.add(fontzise_label, constraints)

        self.edit_area_fs_field = JTextField()
        self.edit_area_fs_field.setEditable(True)
        if self.edit_area_fontsize:
            self.edit_area_fs_field.setText(
                                    "{}".format(self.edit_area_fontsize))
        else:
            self.edit_area_fs_field.setText(self.controller.config[
                                    'edit_area_style']['fontsize']['default'])

        constraints = self.add_constraints(constraints, weightx=0.80,
                                           gridx=1, gridy=4,
                                           fill=GridBagConstraints.HORIZONTAL)
        panel.add(self.edit_area_fs_field, constraints)

    def build_combobox(self, choices, default):
        '''
        Generic method to construct a combobox. choices should be an iterable
        of strings of the choices to be made and default should be a string
        which is equal to one of the values within the iterable.
        '''
        combo = JComboBox()
        for choice in choices:
            combo.addItem(choice)
        combo.setSelectedItem(default)
        return combo

    def build_servers_combobox(self):
        combo = JComboBox()
        # Go through list of servers and add to combo box.
        for server in self.servers.keys():
            if server != "default":
                combo_item = "{}: {}:{}".format(server,
                                                self.servers[server]['url'],
                                                self.servers[server]['port'])
                combo.addItem(combo_item)
                # If this item is the default one, set it as selected
                if server == self.servers['default']:
                    combo.setSelectedItem(combo_item)
        return combo

    def build_buttons_panel(self):
        '''
        Builds the buttons panel to save or cancel changes.
        TODO: Reset button to reset to defaults?
        '''
        panel = JPanel(FlowLayout())
        panel.add(JButton('Cancel', actionPerformed=self.cancel))
        panel.add(JButton('Save', actionPerformed=self.save))
        return panel

    def build_keystrokes_panel(self):
        '''
        Create the panel that'll go in the Keystrokes tab. This should contain
        options for choosing which keystrokes are to be assigned to which
        actions.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_languages_panel(self):
        '''
        Create the panel that'll go in the Languages tab. This should contain
        options for choosing which is the list of languages that can be
        included from the new ATF window and their abbrv.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_projects_panel(self):
        '''
        Create the panel that'll go in the Projects tab. This should contain
        the list of preferred projects and a means to select which is the
        preferred default.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_appearance_panel(self):
        '''
        Create the panel that'll go in the General tab. This should contain
        options for choosing which server to use for validation as well as
        default working dir.
        '''
        panel = JPanel(GridBagLayout())
        constraints = self.add_constraints(GridBagConstraints(),
                                           insets=Insets(10, 10, 10, 10))
        self.build_console_font_panel(constraints, panel)
        self.build_console_font_color_panel(constraints, panel)
        self.build_console_background_color_panel(constraints, panel)
        self.build_edit_area_font_panel(constraints, panel)
        return panel

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("Edit settings")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def display_error(self, keyword):
        '''
        Display error message when keyword is not in settings file.
        '''
        pass

    def cancel(self, event=None):
        '''
        Close window and don't save changes.
        '''
        self.dispose()

    def validate_fontsize(self, input_size, target_key):
        '''
        Method to validate an input fontsize. The target key points to either
        the console font sizes 'console_style' or the edit area font sizes
        'edit_area_style'. If the value is invalid, return the previous user
        fontsize that was stored.
        The second return value is a bool indicating if the value has changed.
        '''
        # Extract plain english from key name for use in error message
        target = target_key[:-6].replace('_', ' ')

        # Use isnumeric() to test if a unicode string only has digits
        if (input_size.isnumeric() and (8 <= int(input_size) <= 30)):
            return input_size, True
        else:
            input_size = self.controller.config[target_key]['fontsize']['user']
            self.logger.error("Invalid {} font size. Please enter a "
                              "number between 8 and 36.\n\n"
                              "Font size left at "
                              "previous value: {}".format(target, input_size))

            return input_size, False

    def validate_colors(self, bg_color, font_color):
        '''
        Validate console colors to ensure they do not match.
        The second return value is a bool indicating if the value has changed.
        '''
        valid = True
        if bg_color == font_color:
            config = self.controller.config
            self.logger.error("Console font colour cannot match background"
                              " colour. Resetting to default values.")
            bg_color = config['console_style']['background_color']['default']
            font_color = config['console_style']['font_color']['default']
            valid = False

        return bg_color, font_color, valid

    def validate_working_dir(self, working_dir):
        '''
        Method to validate input working directories. If directory does not
        exist or if a path to a file is provided instead of a path to a
        directory the method returns None.
        The second return value is a bool indicating if the value has changed.
        '''
        if os.path.isdir(working_dir):
            return working_dir, True
        else:
            self.logger.error("{} is not a valid working directory."
                              " No working directory has been "
                              "saved".format(working_dir))
            return None, False

    def validate_all_inputs(self, working_dir, console_fontsize,
                            edit_area_fontsize, bg_color, font_color):
        '''
        Wrapper around the input validation methods. Returns a tuple containing
        the validated inputs with the last value in the tuple a boolean set to
        False if any of the values have been altered during the validation
        and True if there have been no changes.
        '''
        # Collect the results of each validation. In future we might use this
        # to provide more detailed error logging on bad user input
        validation_results = []

        # Validate the working directory input string
        working_dir, v = self.validate_working_dir(working_dir)
        validation_results.append(v)

        # Validate the input fontsizes
        con_size, v = self.validate_fontsize(console_fontsize, 'console_style')
        validation_results.append(v)

        edit_size, v = self.validate_fontsize(edit_area_fontsize,
                                              'edit_area_style')
        validation_results.append(v)

        # Validate input console colors
        bg_color, font_color, v = self.validate_colors(bg_color, font_color)
        validation_results.append(v)

        return (working_dir, int(con_size), font_color, bg_color,
                int(edit_size), all(validation_results))

    def save(self, event=None):
        '''
        Save changes made by user on local settings file.
        '''
        # Update only the working_dir and the server for now
        # TODO: update keystrokes, projects list, etc.
        working_dir = self.wd_field.getText()

        # Read the fontsize from the textfield
        console_fontsize = self.fs_field.getText()
        edit_area_fontsize = self.edit_area_fs_field.getText()

        # Get the user selected font and background colours
        bg_color = self.bg_color_combo.getSelectedItem()
        font_color = self.font_color_combo.getSelectedItem()

        validated = self.validate_all_inputs(working_dir, console_fontsize,
                                             edit_area_fontsize, bg_color,
                                             font_color)

        # The server format is "name: url:port". We only need "name"
        server = self.combo.getSelectedItem().split(':')[0]
        self.controller.update_config(validated[0], server,
                                      validated[1], validated[2],
                                      validated[3], int(validated[4]))

        # If no values have been changed, print that settings have been
        # updated without errors
        if validated[5]:
            self.logger.info("Settings have been successfully updated.")

        # On saving settings, update the console and edit area properties
        self.controller.refreshConsole()
        self.controller.refreshEditArea()
        # Close window
        self.dispose()

        # Refresh the syntax highlighting in a separate thread so it updates
        # after everything else has been done.
        runSwingLater(self.controller.controller.initHighlighting)

    def browse(self, event=None):
        '''
        Open new dialog for the user to select a path as default working dir.
        '''
        default_path = self.wd_field.getText()
        if not os.path.isdir(default_path):
            default_path = os.getcwd()
        fileChooser = JFileChooser(default_path)
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        # Fixed showDialog bug using showOpenDialog instead. The former was
        # duplicating the last folder name in the path due to a Java bug in
        # OSX in the implementation of JFileChooser!
        status = fileChooser.showOpenDialog(self)
        if status == JFileChooser.APPROVE_OPTION:
            self.wd_field.setText(fileChooser.getSelectedFile().toString())
예제 #34
0
class BurpExtender(IBurpExtender, IScannerCheck, IScanIssue, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Missing Scanner Checks")
        self.out = callbacks.getStdout()

        # define all checkboxes
        self.cbPassiveChecks = self.defineCheckBox("Passive Scanner Checks")
        self.cbDOMXSS = self.defineCheckBox("DOM XSS", False)
        self.cbDOMXSSSources = self.defineCheckBox("Sources", False)
        self.cbDOMXSSSinks = self.defineCheckBox("Sinks")
        self.cbDOMXSSjQuerySinks = self.defineCheckBox("jQuery Sinks", False)
        self.grpDOMXSSSettings = JPanel()
        self.grpDOMXSSSettings.add(self.cbDOMXSSSources)
        self.grpDOMXSSSettings.add(self.cbDOMXSSSinks)
        self.grpDOMXSSSettings.add(self.cbDOMXSSjQuerySinks)
        self.cbSTS = self.defineCheckBox("Strict Transport Security")
        self.lblSTSMin = JLabel("Minimum acceptable max-age")
        self.inSTSMin = JTextField(
            str(STSMinimum), 9, actionPerformed=self.setSTSMinimum
        )  # TODO: actionPerformed only fires on enter key - focus lost would be better
        self.inSTSMin.setToolTipText(
            "Enter the minimum max-age value which is considered as acceptable. Press return to change setting!"
        )
        self.grpSTSSettings = JPanel()
        self.grpSTSSettings.add(self.lblSTSMin)
        self.grpSTSSettings.add(self.inSTSMin)
        self.cbXCTO = self.defineCheckBox("Content Sniffing")
        self.cbXXP = self.defineCheckBox(
            "Client-side XSS Filter Configuration")
        self.cbRedirToHTTPS = self.defineCheckBox(
            "Redirection from HTTP to HTTPS")
        self.btnSave = JButton("Set as default",
                               actionPerformed=self.saveConfig)
        self.btnRestore = JButton("Restore",
                                  actionPerformed=self.restoreConfig)
        self.grpConfig = JPanel()
        self.grpConfig.add(self.btnSave)
        self.grpConfig.add(self.btnRestore)
        self.restoreConfig()

        # definition of config tab
        self.tab = JPanel()
        layout = GroupLayout(self.tab)
        self.tab.setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
        layout.setHorizontalGroup(layout.createSequentialGroup().addGroup(
            layout.createParallelGroup().addComponent(self.cbPassiveChecks)
        ).addGroup(layout.createParallelGroup().addComponent(
            self.cbDOMXSS).addComponent(self.cbSTS).addComponent(
                self.cbXCTO).addComponent(self.cbXXP).addComponent(
                    self.cbRedirToHTTPS)).addGroup(
                        layout.createParallelGroup().addComponent(
                            self.grpDOMXSSSettings, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.PREFERRED_SIZE,
                            GroupLayout.PREFERRED_SIZE).addComponent(
                                self.grpSTSSettings,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.grpConfig, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE)))
        layout.setVerticalGroup(layout.createSequentialGroup().addGroup(
            layout.createParallelGroup().addComponent(
                self.cbPassiveChecks).addComponent(self.cbDOMXSS).addComponent(
                    self.grpDOMXSSSettings, GroupLayout.PREFERRED_SIZE,
                    GroupLayout.PREFERRED_SIZE,
                    GroupLayout.PREFERRED_SIZE)).addGroup(
                        layout.createParallelGroup().addComponent(
                            self.cbSTS).addComponent(
                                self.grpSTSSettings,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE)).addComponent(
                                    self.cbXCTO).addComponent(
                                        self.cbXXP).addComponent(
                                            self.cbRedirToHTTPS).addComponent(
                                                self.grpConfig,
                                                GroupLayout.PREFERRED_SIZE,
                                                GroupLayout.PREFERRED_SIZE,
                                                GroupLayout.PREFERRED_SIZE))

        self.domXSSSourcesRE = re.compile(
            "(location\s*[\[.])|([.\[]\s*[\"']?\s*(arguments|dialogArguments|innerHTML|write(ln)?|open(Dialog)?|showModalDialog|cookie|URL|documentURI|baseURI|referrer|name|opener|parent|top|content|self|frames)\W)|(localStorage|sessionStorage|Database)"
        )
        # NOTE: done some optimizations here, original RE caused too much noise
        # - added leading dot in the first part - original recognized "<a href=..." etc.
        # - removed "value" in first part
        self.domXSSSinksRE = re.compile(
            "(\.(src|href|data|location|code|action)\s*[\"'\]]*\s*\+?\s*=)|((replace|assign|navigate|getResponseHeader|open(Dialog)?|showModalDialog|eval|evaluate|execCommand|execScript|setTimeout|setInterval)\s*[\"'\]]*\s*\()"
        )
        self.domXSSjQuerySinksRE = re.compile(
            "after\(|\.append\(|\.before\(|\.html\(|\.prepend\(|\.replaceWith\(|\.wrap\(|\.wrapAll\(|\$\(|\.globalEval\(|\.add\(|jQUery\(|\$\(|\.parseHTML\("
        )
        self.headerSTSRE = re.compile(
            "^Strict-Transport-Security:.*?max-age=\"?(\d+)\"?",
            re.I)  # TODO: multiple max-age directives cause confusion!
        self.headerXCTORE = re.compile(
            "^X-Content-Type-Options:\s*nosniff\s*$", re.I)
        self.headerXXP = re.compile(
            "^X-XSS-Protection:\s*(\d)(?:\s*;\s*mode\s*=\s*\"?(block)\"?)?",
            re.I)
        self.headerLocationHTTPS = re.compile(
            "^(?:Content-)?Location:\s*(https://.*)$", re.I)

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

    def defineCheckBox(self, caption, selected=True, enabled=True):
        checkBox = JCheckBox(caption)
        checkBox.setSelected(selected)
        checkBox.setEnabled(enabled)
        return checkBox

    def setSTSMinimum(self, e=None):
        val = self.inSTSMin.text
        if re.match("^\d+$", val):
            STSMinimum = int(val)
        else:
            self.inSTSMin.setText(
                str(STSMinimum))  # TODO: doesn't works as desired

    def saveConfig(self, e=None):
        config = {
            'passiveChecks': self.cbPassiveChecks.isSelected(),
            'DOMXSS': self.cbDOMXSS.isSelected(),
            'DOMXSSSources': self.cbDOMXSSSources.isSelected(),
            'DOMXSSSinks': self.cbDOMXSSSinks.isSelected(),
            'DOMXSSjQuerySinks': self.cbDOMXSSjQuerySinks.isSelected(),
            'STS': self.cbSTS.isSelected(),
            'STSMin': self.inSTSMin.text,
            'XCTO': self.cbXCTO.isSelected(),
            'XXP': self.cbXXP.isSelected(),
            'RedirToHTTPS': self.cbRedirToHTTPS.isSelected(),
        }
        self.callbacks.saveExtensionSetting("config", pickle.dumps(config))

    def restoreConfig(self, e=None):
        storedConfig = self.callbacks.loadExtensionSetting("config")
        if storedConfig != None:
            try:
                config = pickle.loads(storedConfig)
                self.cbPassiveChecks.setSelected(config['passiveChecks'])
                self.cbDOMXSS.setSelected(config['DOMXSS'])
                self.cbDOMXSSSources.setSelected(config['DOMXSSSources'])
                self.cbDOMXSSSinks.setSelected(config['DOMXSSSinks'])
                self.cbDOMXSSjQuerySinks.setSelected(
                    config['DOMXSSjQuerySinks'])
                self.cbSTS.setSelected(config['STS'])
                self.inSTSMin.text = config['STSMin']
                self.cbXCTO.setSelected(config['XCTO'])
                self.cbXXP.setSelected(config['XXP'])
                self.cbRedirToHTTPS.setSelected(config['RedirToHTTPS'])
                self.setSTSMinimum()
            except:
                print(
                    "Classical case of \"shouldn't happen\": something went wrong with config restore. Submit a bug or patch and keep your eyes open for Zombies. Something is really strange here.\nConfig contained: "
                    + storedConfig)

    ### ITab ###
    def getTabCaption(self):
        return ("Additional Scanner Checks")

    def getUiComponent(self):
        return self.tab

    def doActiveScan(self, baseRequestResponse, insertionPoint):
        pass

    ### IScannerCheck ###
    def doPassiveScan(self, baseRequestResponse):
        if not self.cbPassiveChecks.isSelected():
            return None
        scanIssues = list()
        requestProtocol = baseRequestResponse.getHttpService().getProtocol()
        analyzedResponse = self.helpers.analyzeResponse(
            baseRequestResponse.getResponse())
        responseHeaders = analyzedResponse.getHeaders()
        bodyOffset = analyzedResponse.getBodyOffset()
        responseBody = baseRequestResponse.getResponse(
        )[analyzedResponse.getBodyOffset():].tostring()

        # Identify DOMXSS sources and sinks
        domXSSSources = list()
        domXSSSinks = list()
        domXSSjQuerySinks = list()

        if self.cbDOMXSS.isSelected():
            if self.cbDOMXSSSources.isSelected():
                domXSSSources = self.domXSSSourcesRE.finditer(responseBody)
            if self.cbDOMXSSSinks.isSelected():
                domXSSSinks = self.domXSSSinksRE.finditer(responseBody)
            if self.cbDOMXSSjQuerySinks.isSelected():
                domXSSjQuerySinks = self.domXSSjQuerySinksRE.finditer(
                    responseBody)

            domXSSSourcesPos = extractMatchPositions(domXSSSources, bodyOffset)
            domXSSSinksPos = extractMatchPositions(domXSSSinks, bodyOffset)
            domXSSjQuerySinksPos = extractMatchPositions(
                domXSSjQuerySinks, bodyOffset)

            if len(domXSSSourcesPos) + len(domXSSSinksPos) + len(
                    domXSSjQuerySinksPos) > 0:  # One of the DOMXSS REs matched
                scanIssues.append(
                    DOMXSSScanIssue(baseRequestResponse, domXSSSourcesPos,
                                    domXSSSinksPos, domXSSjQuerySinksPos,
                                    self.helpers, self.callbacks))

        # Identify missing, wrong or multiple occurring HTTP headers
        headersSTS = list()
        headersXCTO = list()
        headersXXP = list()
        headersLocationHTTPS = list()

        offset = 0
        for header in responseHeaders:
            if self.cbSTS.isSelected():
                match = self.headerSTSRE.match(header)
                if match:
                    headersSTS.append((match, offset))

            if self.cbXCTO.isSelected():
                match = self.headerXCTORE.match(header)
                if match:
                    headersXCTO.append(match)

            if self.cbXXP.isSelected():
                match = self.headerXXP.match(header)
                if match:
                    headersXXP.append((match, offset))

            if self.cbRedirToHTTPS.isSelected() and requestProtocol == 'http':
                match = self.headerLocationHTTPS.match(header)
                if match:
                    headersLocationHTTPS.append((match, offset))

            offset += len(
                header
            ) + 2  # TODO: assumption that CRLF is always used. The world is ugly, make a real check.

        if requestProtocol != "https":
            pass  # HSTS only valid in HTTPS responses.
        elif self.cbSTS.isSelected():
            if len(headersSTS) == 0:  # No HSTS header
                scanIssues.append(
                    STSScanIssue(baseRequestResponse,
                                 STSScanIssue.caseNoHeader, None, self.helpers,
                                 self.callbacks))
            elif len(headersSTS) == 1 and int(
                    headersSTS[0][0].group(1)
            ) < STSMinimum:  # HSTS header present, but time frame too short
                scanIssues.append(
                    STSScanIssue(baseRequestResponse, STSScanIssue.caseTooLow,
                                 (int(headersSTS[0][0].group(1)),
                                  headersSTS[0][1] + headersSTS[0][0].start(1),
                                  headersSTS[0][1] + headersSTS[0][0].end(1)),
                                 self.helpers, self.callbacks))
            elif len(headersSTS) > 1:  # multiple HSTS headers
                scanIssues.append(
                    STSScanIssue(baseRequestResponse,
                                 STSScanIssue.caseMultipleHeaders, headersSTS,
                                 self.helpers, self.callbacks))

        # Redirection from HTTP to HTTPS
        if self.cbRedirToHTTPS.isSelected() and len(headersLocationHTTPS) > 0:
            scanIssues.append(
                RedirectFromHTTP2HTTPSScanIssue(baseRequestResponse,
                                                headersLocationHTTPS,
                                                self.helpers, self.callbacks))

        if self.cbXXP.isSelected():
            if len(headersXXP) == 0:  # No XSS protection header
                scanIssues.append(
                    XXPScanIssue(baseRequestResponse,
                                 XXPScanIssue.caseNoHeader, None, self.helpers,
                                 self.callbacks))
            elif len(headersXXP) == 1 and int(
                    headersXXP[0][0].group(1)) == 1 and headersXXP[0][0].group(
                        2) != "block":  # Activated but not in block mode
                scanIssues.append(
                    XXPScanIssue(baseRequestResponse,
                                 XXPScanIssue.caseNoBlockMode, headersXXP,
                                 self.helpers, self.callbacks))
            elif len(headersXXP) > 1:  # Multiple XXP headers
                scanIssues.append(
                    XXPScanIssue(baseRequestResponse,
                                 XXPScanIssue.caseMultipleHeaders, headersXXP,
                                 self.helpers, self.callbacks))
                # "X-XSS-Protection: 0" already catched by Burp

        # X-Content-Type-Options missing
        # NOTE: it is assumed that multiple "X-Content-Type-Options: nosniff" headers can't cause confusion at browser side because they all have the same meaning.
        if self.cbXCTO.isSelected() and len(headersXCTO) == 0:
            scanIssues.append(
                XCTOScanIssue(baseRequestResponse, self.helpers,
                              self.callbacks))

        return scanIssues

    def consolidateDuplicateIssues(self, existingIssue, newIssue):
        if existingIssue.getIssueName() == newIssue.getIssueName():
            if newIssue.getIssueName(
            ) == issueNameDOMXSS:  # DOMXSS issues are different if response content is different.
                responseExisting = existingIssue.getHttpMessages(
                )[0].getResponse()
                analyzedResponseExisting = self.helpers.analyzeResponse(
                    responseExisting)
                bodyOffsetExisting = analyzedResponseExisting.getBodyOffset()
                responseBodyExisting = responseExisting.getResponse(
                )[analyzedResponseExisting.getBodyOffset():].tostring()

                responseNew = newIssue.getHttpMessages()[0].getResponse()
                analyzedResponseNew = self.helpers.analyzeResponse(responseNew)
                bodyOffsetNew = analyzedResponseNew.getBodyOffset()
                responseBodyNew = responseNew.getResponse(
                )[analyzedResponseNew.getBodyOffset():].tostring()

                if responseBodyExisting == responseBodyNew:
                    return -1
                else:
                    return 0
            elif newIssue.getIssueName(
            ) == issueNameRedirectFromHTTP2HTTPS:  # Redirection issues are different if target URLs differ
                if existingIssue.getIssueDetail() == newIssue.getIssueDetail():
                    return -1
                else:
                    return 0
            else:  # In all other cases: keep existing issue
                return -1
        return 0
예제 #35
0
   for i in range(n):
      zx = random.random()
      zy = random.random()
      if zx * zx + zy * zy < 1:
         hits = hits + 1
         setColor("red")
      else:
         setColor("green")
      point(zx, zy)
   return hits

lbl1 = JLabel("Number of drops: ")
lbl2 = JLabel("          PI = ")
tf1 = JTextField(6)
tf2 = JTextField(10)
btn1 = JButton("OK", actionListener = actionCallback)

makeGPanel("Monte Carlo Simulation", -0.1, 1.1, -0.1, 1.1)
createGUI()
tf1.setText("10000")
init()

while True:
   putSleep()
   init()
   n = int(tf1.getText())
   k = doIt(n)
   pi =  4 * k / n
   tf2.setText(str(pi))

예제 #36
0
class TimesketchSettingsWithUISettingsPanel(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
    def __init__(self, settings):
        self.local_settings = settings
        self.tag_list = []
        self.initComponents()
        self.customizeComponents()
        self.path_to_Timesketch_exe = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Timesketch_api.exe")
            
    # Check to see if the Timesketch server is available and you can talk to it
    def Check_Server(self, e):

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

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

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

    def setUserName(self, event):
        self.local_settings.setSetting('userName', self.userName_TF.getText()) 

    def setPassword(self, event):
        self.local_settings.setSetting('password', self.password_TF.getText()) 

    def setsketchName(self, event):
        self.local_settings.setSetting('sketchName', self.sketchName_TF.getText()) 

    def setsketchDescription(self, event):
        self.local_settings.setSetting('sketchDescription', self.sketchDescription_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_2 = JLabel("Timesketch 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.Label_4 = JLabel("User Name")
        self.Label_4.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.Label_4, self.gbcPanel0 ) 
        self.panel0.add( self.Label_4 ) 

        self.userName_TF = JTextField(20, focusLost=self.setUserName) 
        self.userName_TF.setEnabled(True)
        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 = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.userName_TF, self.gbcPanel0 ) 
        self.panel0.add( self.userName_TF ) 

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

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

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

        self.Blank_5 = JLabel( " ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 
        
        self.Label_6 = JLabel("Sketch Name")
        self.Label_6.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.Label_6, self.gbcPanel0 ) 
        self.panel0.add( self.Label_6 ) 

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

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

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

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

        self.Blank_7 = JLabel( " ") 
        self.Blank_7.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_7, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_7 ) 
        
        # self.Check_Server_Status_BTN = JButton( "Check Server Status", actionPerformed=self.Check_Server) 
        # self.Check_Server_Status_BTN.setEnabled(True)
        # self.rbgPanel0.add( self.Save_Settings_BTN ) 
        # 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.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 = 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.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_Timesketch_CB.setSelected(self.local_settings.getRun_Timesketch())
        #self.Import_Timesketch_CB.setSelected(self.local_settings.getImport_Timesketch())
        #self.check_Database_entries()
        self.IP_Address_TF.setText(self.local_settings.getSetting('ipAddress'))
        self.Port_Number_TF.setText(self.local_settings.getSetting('portNumber'))
        self.userName_TF.setText(self.local_settings.getSetting('userName'))
        self.password_TF.setText(self.local_settings.getSetting('password'))
        self.sketchName_TF.setText(Case.getCurrentCase().getNumber())
        self.sketchDescription_TF.setText(Case.getCurrentCase().getName())
        self.local_settings.setSetting('sketchName', self.sketchName_TF.getText()) 
        self.local_settings.setSetting('sketchDescription', self.sketchDescription_TF.getText()) 


    # Return the settings used
    def getSettings(self):
        return self.local_settings
예제 #37
0
class ProtoBufEditorTab(burp.IMessageEditorTab):
    """Tab in interceptor/repeater for editing protobuf message.
    Decodes them to JSON and back.
    The message type is attached to this object.
    """

    def __init__(self, extension, controller, editable, callbacks):

        self._callbacks = callbacks
        self._extension = extension
        self._callbacks = extension.callbacks
        self._helpers = extension.helpers

        self._controller = controller

        self._text_editor = self._callbacks.createTextEditor()
        self._text_editor.setEditable(editable)
        self._editable = editable

        self._last_valid_type_index = None

        self._filtered_message_model = FilteredMessageModel(
            extension.known_message_model, self._callbacks
        )

        self._type_list_component = JList(self._filtered_message_model)
        self._type_list_component.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
        self._type_list_component.addListSelectionListener(TypeListListener(self))

        self._new_type_field = JTextField()

        self._component = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._component.setLeftComponent(self._text_editor.getComponent())
        self._component.setRightComponent(self.createButtonPane())
        self._component.setResizeWeight(0.95)

        self.message_type = None
        self._is_request = None
        self._encoder = None
        self._original_json = None
        self._original_typedef = None
        self._last_set_json = ""
        self._content_info = None
        self._request_content_info = None
        self._request = None
        self._original_content = None

    def getTabCaption(self):
        """Return message tab caption"""
        return "Protobuf"

    def getMessage(self):
        """Transform the JSON format back to the binary protobuf message"""
        try:
            if self.message_type is None or not self.isModified():
                return self._original_content

            json_data = self._text_editor.getText().tostring()

            protobuf_data = blackboxprotobuf.protobuf_from_json(
                json_data, self.message_type
            )

            protobuf_data = self.encodePayload(protobuf_data)
            if "set_protobuf_data" in dir(user_funcs):
                result = user_funcs.set_protobuf_data(
                    protobuf_data,
                    self._original_content,
                    self._is_request,
                    self._content_info,
                    self._helpers,
                    self._request,
                    self._request_content_info,
                )
                if result is not None:
                    return result

            headers = self._content_info.getHeaders()
            return self._helpers.buildHttpMessage(headers, str(protobuf_data))

        except Exception as exc:
            self._callbacks.printError(traceback.format_exc())
            JOptionPane.showMessageDialog(
                self._component, "Error encoding protobuf: " + str(exc)
            )
            # Resets state
            return self._original_content

    def setMessage(self, content, is_request, retry=True):
        """Get the data from the request/response and parse into JSON.
        sets self.message_type
        """
        # Save original content
        self._original_content = content
        if is_request:
            self._content_info = self._helpers.analyzeRequest(
                self._controller.getHttpService(), content
            )
        else:
            self._content_info = self._helpers.analyzeResponse(content)
        self._is_request = is_request
        self._request = None
        self._request_content_info = None

        if not is_request:
            self._request = self._controller.getRequest()
            self._request_content_info = self._helpers.analyzeRequest(
                self._controller.getHttpService(), self._request
            )

        # how we remember which message type correlates to which endpoint
        self._message_hash = self.getMessageHash()

        # Try to find saved messsage type
        self.message_type = None
        self.message_type_name = None
        if self._message_hash in self._extension.saved_types:
            typename = self._extension.saved_types[self._message_hash]
            if typename in default_config.known_types:
                self.message_type_name = typename
                self.message_type = default_config.known_types[typename]
            else:
                del self._extension.saved_types[self._message_hash]

        try:
            protobuf_data = None
            if "get_protobuf_data" in dir(user_funcs):
                protobuf_data = user_funcs.get_protobuf_data(
                    content,
                    is_request,
                    self._content_info,
                    self._helpers,
                    self._request,
                    self._request_content_info,
                )
            if protobuf_data is None:
                protobuf_data = content[self._content_info.getBodyOffset() :].tostring()

            protobuf_data = self.decodePayload(protobuf_data)

            # source_typedef will be the original, updatable version of the dict
            # TODO fix this hack
            self._original_data = protobuf_data
            self._filtered_message_model.set_new_data(protobuf_data)
            self._source_typedef = self.message_type
            json_data, self.message_type = blackboxprotobuf.protobuf_to_json(
                protobuf_data, self.message_type
            )

            self._original_json = json_data
            self._original_typedef = self.message_type
            self._last_set_json = str(json_data)
            self._text_editor.setText(json_data)
            success = True
        except Exception as exc:
            success = False
            self._callbacks.printError(
                "Got error decoding protobuf binary: " + traceback.format_exc()
            )

        # Bring out of exception handler to avoid nexting handlers
        if not success:
            if self._message_hash in self._extension.saved_types:
                del self._extension.saved_types[self._message_hash]
                self.setMessage(content, is_request, False)
                self._text_editor.setText("Error decoding protobuf")

        if self.message_type_name:
            self.forceSelectType(self.message_type_name)

    def decodePayload(self, payload):
        """Add support for decoding a few default methods. Including Base64 and GZIP"""
        if payload.startswith(bytearray([0x1F, 0x8B, 0x08])):
            gzip_decompress = zlib.decompressobj(-zlib.MAX_WBITS)
            self._encoder = "gzip"
            return gzip_decompress.decompress(payload)

        # Try to base64 decode
        try:
            protobuf = base64.b64decode(payload, validate=True)
            self._encoder = "base64"
            return protobuf
        except Exception as exc:
            pass

        # try decoding as a gRPC payload: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
        # we're naiively handling only uncompressed payloads
        if len(payload) > 1 + 4 and payload.startswith(
            bytearray([0x00])
        ):  # gRPC has 1 byte flag + 4 byte length
            (message_length,) = struct.unpack_from(">I", payload[1:])
            if len(payload) == 1 + 4 + message_length:
                self._encoder = "gRPC"
                return payload[1 + 4 :]
        # try:
        #    protobuf = base64.urlsafe_b64decode(payload)
        #    self._encoder = 'base64_url'
        #    return protobuf
        # except Exception as exc:
        #    pass

        self._encoder = None
        return payload

    def encodePayload(self, payload):
        """If we detected an encoding like gzip or base64 when decoding, redo
        that encoding step here
        """
        if self._encoder == "base64":
            return base64.b64encode(payload)
        elif self._encoder == "base64_url":
            return base64.urlsafe_b64encode(payload)
        elif self._encoder == "gzip":
            gzip_compress = zlib.compressobj(-1, zlib.DEFLATED, -zlib.MAX_WBITS)
            self._encoder = "gzip"
            return gzip_compress.compress(payload)
        elif self._encoder == "gRPC":
            message_length = struct.pack(">I", len(payload))
            return bytearray([0x00]) + bytearray(message_length) + payload
        else:
            return payload

    def getSelectedData(self):
        """Get text currently selected in message"""
        return self._text_editor.getSelectedText()

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

    def isEnabled(self, content, is_request):
        """Try to detect a protobuf in the message to enable the tab. Defaults
        to content-type header of 'x-protobuf'. User overridable
        """
        # TODO implement some more default checks
        if is_request:
            info = self._helpers.analyzeRequest(content)
        else:
            info = self._helpers.analyzeResponse(content)

        if "detect_protobuf" in dir(user_funcs):
            result = user_funcs.detect_protobuf(
                content, is_request, info, self._helpers
            )
            if result is not None:
                return result

        # Bail early if there is no body
        if info.getBodyOffset() == len(content):
            return False

        protobuf_content_types = [
            "protobuf",
            "grpc",
        ]
        # Check all headers for x-protobuf
        for header in info.getHeaders():
            if "content-type" in header.lower():
                for protobuf_content_type in protobuf_content_types:
                    if protobuf_content_type in header.lower():
                        return True

        return False

    def isModified(self):
        """Return if the message was modified"""
        return self._text_editor.isTextModified()

    def createButtonPane(self):
        """Create a new button pane for the message editor tab"""
        self._button_listener = EditorButtonListener(self)

        panel = JPanel()
        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
        panel.setBorder(EmptyBorder(5, 5, 5, 5))

        panel.add(Box.createRigidArea(Dimension(0, 5)))
        type_scroll_pane = JScrollPane(self._type_list_component)
        type_scroll_pane.setMaximumSize(Dimension(200, 100))
        type_scroll_pane.setMinimumSize(Dimension(150, 100))
        panel.add(type_scroll_pane)
        panel.add(Box.createRigidArea(Dimension(0, 3)))

        new_type_panel = JPanel()
        new_type_panel.setLayout(BoxLayout(new_type_panel, BoxLayout.X_AXIS))
        new_type_panel.add(self._new_type_field)
        new_type_panel.add(Box.createRigidArea(Dimension(3, 0)))
        new_type_panel.add(
            self.createButton(
                "New", "new-type", "Save this message's type under a new name"
            )
        )
        new_type_panel.setMaximumSize(Dimension(200, 20))
        new_type_panel.setMinimumSize(Dimension(150, 20))

        panel.add(new_type_panel)

        button_panel = JPanel()
        button_panel.setLayout(FlowLayout())
        if self._editable:
            button_panel.add(
                self.createButton(
                    "Validate", "validate", "Validate the message can be encoded."
                )
            )
        button_panel.add(
            self.createButton("Edit Type", "edit-type", "Edit the message type")
        )
        button_panel.add(
            self.createButton(
                "Reset Message", "reset", "Reset the message and undo changes"
            )
        )
        button_panel.add(
            self.createButton(
                "Clear Type", "clear-type", "Reparse the message with an empty type"
            )
        )
        button_panel.setMinimumSize(Dimension(100, 200))
        button_panel.setPreferredSize(Dimension(200, 1000))

        panel.add(button_panel)

        return panel

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

    def validateMessage(self):
        """Callback for validate button. Attempts to encode the message with
        the current type definition
        """
        try:
            json_data = self._text_editor.getText().tostring()
            blackboxprotobuf.protobuf_from_json(json_data, self.message_type)
            # If it works, save the message
            self._original_json = json_data
            self._original_typedef = self.message_type
        except Exception as exc:
            JOptionPane.showMessageDialog(self._component, str(exc))
            self._callbacks.printError(traceback.format_exc())

    def resetMessage(self):
        """Drop any changes and reset the message. Callback for "reset"
        button
        """

        self._last_set_json = str(self._original_json)
        self._text_editor.setText(self._original_json)
        self.message_type = self._original_typedef

    def getMessageHash(self):
        """Compute an "identifier" for the message which is used for sticky
        type definitions. User modifiable
        """
        message_hash = None
        if "hash_message" in dir(user_funcs):
            message_hash = user_funcs.hash_message(
                self._original_content,
                self._is_request,
                self._content_info,
                self._helpers,
                self._request,
                self._request_content_info,
            )
        if message_hash is None:
            # Base it off just the URL and request/response

            content_info = (
                self._content_info if self._is_request else self._request_content_info
            )
            url = content_info.getUrl().getPath()
            message_hash = ":".join([url, str(self._is_request)])
        return message_hash

    def forceSelectType(self, typename):
        index = self._filtered_message_model.get_type_index(typename)
        if index is not None:
            self._last_valid_type_index = index
            self._type_list_component.setSelectedIndex(index)

    def updateTypeSelection(self):
        """Apply a new typedef based on the selected type in the type list"""
        # Check if something is selected
        if self._type_list_component.isSelectionEmpty():
            self._last_valid_type_index = None
            del self._extension.saved_types[self._message_hash]
            return

        # TODO won't actually work right if we delete the type we're using a
        # new type is now in the index
        if self._last_valid_type_index == self._type_list_component.getSelectedIndex():
            # hasn't actually changed since last time we tried
            # otherwise can trigger a second time when we call setSelectedIndex below on failure
            return

        type_name = self._type_list_component.getSelectedValue()
        # try to catch none here...
        if not type_name or type_name not in default_config.known_types:
            return

        try:
            self.applyType(default_config.known_types[type_name])
        except BlackboxProtobufException as exc:
            self._callbacks.printError(traceback.format_exc())

            if isinstance(exc, EncoderException):
                JOptionPane.showMessageDialog(
                    self._component,
                    "Error encoding protobuf with previous type: %s" % (exc),
                )
            elif isinstance(exc, DecoderException):
                JOptionPane.showMessageDialog(
                    self._component,
                    "Error encoding protobuf with type %s: %s" % (type_name, exc),
                )
                # decoder exception means it doesn't match the message that was sucessfully encoded by the prev type
                self._filtered_message_model.remove_type(type_name)

            if self._last_valid_type_index is not None:
                type_name = self._type_list_component.setSelectedIndex(
                    self._last_valid_type_index
                )
            else:
                self._type_list_component.clearSelection()
            return

        self._extension.saved_types[self._message_hash] = type_name
        self._last_valid_type_index = self._type_list_component.getSelectedIndex()

    def editType(self, typedef):
        """Apply the new typedef. Use dict.update to change the original
        dictionary, so we also update the anonymous cached definition and ones
        stored in known_messages"""
        # TODO this is kind of an ugly hack. Should redo how these are referenced
        # probably means rewriting a bunch of the editor
        old_source = self._source_typedef
        old_source.clear()
        old_source.update(typedef)
        self.applyType(old_source)

    def applyType(self, typedef):
        """Apply a new typedef to the message. Throws an exception if type is invalid."""
        # store a reference for later mutation?
        self._source_typedef = typedef
        # Convert to protobuf as old type and re-interpret as new type
        old_message_type = self.message_type
        json_data = self._text_editor.getText().tostring()
        protobuf_data = blackboxprotobuf.protobuf_from_json(json_data, old_message_type)

        new_json, message_type = blackboxprotobuf.protobuf_to_json(
            str(protobuf_data), typedef
        )

        # Should exception out before now if there is an issue
        self.message_type = message_type

        # if the json data was modified, then re-check our types
        if json_data != self._last_set_json:
            self._filtered_message_model.set_new_data(protobuf_data)
        self._last_set_json = str(new_json)
        self._text_editor.setText(str(new_json))

    def saveAsNewType(self):
        """Copy the current type into known_messages"""
        name = self._new_type_field.getText().strip()
        if not NAME_REGEX.match(name):
            JOptionPane.showMessageDialog(
                self._component,
                "%s is not a valid "
                "message name. Message names should be alphanumeric." % name,
            )
            return
        if name in default_config.known_types:
            JOptionPane.showMessageDialog(
                self._component, "Message name %s is " "already taken." % name
            )
            return

        # Do a deep copy on the dictionary so we don't accidentally modify others
        default_config.known_types[name] = copy.deepcopy(self.message_type)
        # update the list of messages. This should trickle down to known message model
        self._extension.known_message_model.addElement(name)
        self._new_type_field.setText("")
        self._extension.saved_types[self._message_hash] = name

        # force select our new type
        self.forceSelectType(name)

    def clearType(self):
        self.applyType({})
        self._type_list_component.clearSelection()
        self._new_type_field.setText("")

    def open_typedef_window(self):
        self._extension.open_typedef_editor(self.message_type, self.editType)
예제 #38
0
class BurpExtender(IBurpExtender,ITab,IHttpListener):
    def registerExtenderCallbacks(self,callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        self.callbacks.setExtensionName("KkMultiProxy")
        self.PROXY_LIST = []

        self.jPanel = JPanel()
        boxVertical = Box.createVerticalBox()
        boxHorizontal = Box.createHorizontalBox()

        boxHorizontal.add(JButton("File",actionPerformed=self.getFile))
        self.FileText = JTextField("")
        boxHorizontal.add(self.FileText)
        boxVertical.add(boxHorizontal)

        TableHeader = ('IP','PORT')
        TableModel = DefaultTableModel(self.PROXY_LIST,TableHeader)
        self.Table = JTable(TableModel)
        boxVertical.add(self.Table)

        boxHorizontal = Box.createHorizontalBox()
        boxHorizontal.add(JButton("Add",actionPerformed=self.addIP))
        boxHorizontal.add(JButton("Delete",actionPerformed=self.deleteIP))
        boxHorizontal.add(JButton("Save",actionPerformed=self.saveIP))
        boxVertical.add(boxHorizontal)

        self.jPanel.add(boxVertical)

        self.callbacks.addSuiteTab(self)
        self.callbacks.registerHttpListener(self)
        return

    def getFile(self,button):
        dlg = JFileChooser()
        result = dlg.showOpenDialog(None)
        if result == JFileChooser.APPROVE_OPTION:
            f = dlg.getSelectedFile()
            path = f.getPath()
            self.FileText.setText(path)
            try:
                self.getIPList(path)
            except:
                exit(0)

    def addIP(self,button):
        #chooser = JFileChooser()
        #chooser.showOpenDialog(None)
        demo = DialogDemo(self.Table)

    def deleteIP(self,button):
        selectRows = len(self.Table.getSelectedRows()) 
        TableModel = self.Table.getModel()
        if selectRows:
            selectedRowIndex = self.Table.getSelectedRow()
            TableModel.removeRow(selectedRowIndex)

    def saveIP(self,button):
        TableModel = self.Table.getModel()
        rowCount = TableModel.getRowCount()
        result_str = ""
        for i in range(rowCount):
            if i == 0:
                result_str+=TableModel.getValueAt(i,0)+':'+TableModel.getValueAt(i,1)
            else:
                result_str+='|'+TableModel.getValueAt(i,0)+':'+TableModel.getValueAt(i,1)
        print result_str
        f = open(self.FileText.getText(),'w+')
        f.write(result_str)
        f.close()
    def getTabCaption(self):
        return "MultiProxy"

    def getUiComponent(self):
        return self.jPanel

    def processHttpMessage(self,toolFlag,messageIsRequest,messageInfo):
        if messageIsRequest:
            httpService = messageInfo.getHttpService()
            print httpService.getHost()

            # if the host is HOST_FROM, change it to HOST_TO
            i = randint(0,len(self.TableDatas)-1)
            messageInfo.setHttpService(self.helpers.buildHttpService(self.PROXY_LIST[i]['ip'], self.PROXY_LIST[i]['port'], httpService.getProtocol()))
            print messageInfo.getHttpService().getHost()

    def getIPList(self,path):
        f = open(path,'r+')
        content = f.read()
        f.close()
        if content:
            ip_array = content.split('|')
            for _ip in ip_array:
                ip = _ip.split(':')[0]
                port = _ip.split(':')[1]
                self.PROXY_LIST.append([ip,port])
        print self.PROXY_LIST
예제 #39
0
class ConfigurationPanel(JPanel, PropertyChangeListener):
    
    def __init__(self):
        ''' Configuration Panel '''
#         pconfig = JPanel(GridBagLayout())
#         pconfig.setSize(Dimension(500,300))
        self.setLayout(GridBagLayout())
#         super(self,GridBagLayout())
        self.setSize(Dimension(500,300))
        ''' fila 1 '''
        label = JLabel('Configuration panel')
        c1 = GridBagConstraints()
        c1.fill = GridBagConstraints.HORIZONTAL
        c1.weightx = 0.5
        c1.gridwidth = 4
        c1.gridx = 0
        c1.gridy = 0
        self.add(label, c1)
        ''' fila 2 '''
        self.radioBtnOMC = JRadioButton('OpenModelica')
        c2 = GridBagConstraints()
        c2.fill = GridBagConstraints.HORIZONTAL
        c2.weightx = 0.5
        c2.gridx = 0
        c2.gridy = 1
        self.add(self.radioBtnOMC, c2)
        self.radioBtnJM = JRadioButton('JModelica')
        c3 = GridBagConstraints()
        c3.fill = GridBagConstraints.HORIZONTAL
        c3.weightx = 0.5
        c3.gridx = 1
        c3.gridy = 1
        self.add(self.radioBtnJM, c3)
        self.radioBtnDY = JRadioButton('Dymola')
        c4 = GridBagConstraints()
        c4.fill = GridBagConstraints.HORIZONTAL
        c4.weightx = 0.5
        c4.gridx = 2
        c4.gridy = 1
        self.add(self.radioBtnDY, c4)
        rbBtnGroup = ButtonGroup()
        rbBtnGroup.add(self.radioBtnOMC)
        rbBtnGroup.add(self.radioBtnJM)
        rbBtnGroup.add(self.radioBtnDY)
        ''' fila 2 '''
        label = JLabel('Start time')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 2
        self.add(label, c)
        self.txtstart= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 2
        self.add(self.txtstart, c)
        label = JLabel('Stop time')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 2
        self.add(label, c)
        self.txtstop= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 2
        self.add(self.txtstop, c)
        ''' fila 3 '''
        label = JLabel('Solver')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 3
        self.add(label, c)
        self.cbsolver= JComboBox(['dassl','rkfix2'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 3
        self.add(self.cbsolver, c)
        label = JLabel('Algorithm (JM)')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 3
        self.add(label, c)
        self.cbalgorithm= JComboBox(['AssimuloAlg'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 3
        self.add(self.cbalgorithm, c)
        ''' fila 4 '''
        label = JLabel('Interval')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 4
        self.add(label, c)
        self.txtinterval= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 4
        self.add(self.txtinterval, c)
        ''' fila 5 '''
        label = JLabel('Tolerance')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 5
        self.add(label, c)
        self.txttolerance= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 5
        self.add(self.txttolerance, c)
        ''' fila 6 '''
        label = JLabel('Output format')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 6
        self.add(label, c)
        self.cboutformat= JComboBox(['.mat','.h5','.csv'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 6
        self.add(self.cboutformat, c)
        label = JLabel('Initialize (JM)')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 6
        self.add(label, c)
        self.cbinitialize= JComboBox(['True','False'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 6
        self.add(self.cbinitialize, c)
        ''' fila 7 '''
        bSaveCfg= JButton('Save Configuration', actionPerformed= self.saveConfiguration)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 0
        c.gridy = 7
        self.add(bSaveCfg, c)
        self.bSimulation= JButton('Load Configuration', actionPerformed= self.loadConfiguration)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 2
        c.gridy = 7
        self.add(self.bSimulation, c)
        ''' fila 8 '''
        self.bSimulation= JButton('Simulate', actionPerformed= self.startSimlation)
        self.bSimulation.enabled= 0
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 8
        self.add(self.bSimulation, c)
        ''' file 9 '''
        simProgress= JProgressBar(0, self.getWidth(), value=0, stringPainted=True)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 9
        self.add(simProgress, c)
        ''' fila 10 '''
        self.lblResult= JLabel('Simulation information')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 10
        self.add(self.lblResult, c) 
     
    def startSimlation(self, event):
        "Invoked when the user presses the start button"
        self.bSimulation.enabled = False
        #Instances of javax.swing.SwingWorker are not reusable, so
        #we create new instances as needed.
        self.simtask = SimulationTask(self)
#         self.simtask.addPropertyChangeListener(self)
        self.simtask.execute() 
        
    def saveConfiguration(self,event):
        if self.radioBtnOMC.isSelected() or self.radioBtnDY.isSelected():
            self.config= SimulationConfigOMCDY()
            self.config.set_starttime(self.txtstart.getText())
            self.config.set_stoptime(self.txtstop.getText())
            self.config.set_tolerance(self.txttolerance.getText())
            self.config.set_intervals(self.txtinterval.getText())
            self.config.set_method(self.cbsolver.selectedItem)
            self.config.set_outputformat(self.cboutformat.selectedItem)
            if self.radioBtnOMC.isSelected():
                nomfile= './config/simConfigurationOMC.properties'
            if self.radioBtnDY.isSelected():
                nomfile= './config/simConfigurationDY.properties'
            self.config.save_Properties(nomfile, 'Simulation Configuration')
        if self.radioBtnJM.isSelected():
            self.config= SimulationConfigJM()
            self.config.set_starttime(self.txtstart.getText())
            self.config.set_stoptime(self.txtstop.getText())
            self.config.set_intervals(self.txtinterval.text)
            self.config.set_method(self.cbsolver.selectedItem)
            self.config.set_algorithm(self.cbalgorithm.selectedItem)
            self.config.set_initialization(self.cbinitialize.selectedItem)
            self.config.set_outputformat(self.cboutformat.selectedItem)
            nomfile= './config/simConfigurationJM.properties'
            self.config.save_Properties(nomfile, 'Simulation Configuration')
        self.bSimulation.enabled= 1
        
    def loadConfiguration(self, event):
        if self.radioBtnOMC.isSelected() or self.radioBtnDY.isSelected():
            self.config= SimulationConfigOMCDY()
            self.config.load_Properties('./config/simConfigurationOMC.properties')
            self.txtstart.setText(self.config.get_starttime())
            self.txtstop.setText(self.config.get_stoptime())
            self.txttolerance.setText(self.config.get_tolerance())
            self.txtinterval.setText(self.config.get_intervals())
            self.cbsolver.selectedItem= self.config.get_method()
            self.cboutformat.selectedItem= self.config.get_outputformat()
        if self.radioBtnJM.isSelected():
            self.config= SimulationConfigJM()
            self.config.load_Properties('./config/simConfigurationJM.properties')
            self.txtstart.setText(self.config.get_starttime())
            self.txtstop.setText(self.config.get_stoptime())
            self.txtinterval.setText(self.config.get_intervals())
            self.cbsolver.selectedItem= self.config.get_method()
            self.cbalgorithm.selectedItem= self.config.get_algorithm()
            self.cbinitialize.selectedItem= self.config.get_initialization()
#             self.cboutformat.selectedItem= self.config.get_outputformat()
        self.bSimulation.enabled= 1
예제 #40
0
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

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

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

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

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

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

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

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
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
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
           
    # 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.setProcessIDs(self.Process_Ids_To_Dump_TF.getText()) 
        #self.Error_Message.setText(self.Process_Ids_To_Dump_TF.getText())
        
    def checkBoxEvent(self, event):
        if self.Check_Box.isSelected():
            self.local_settings.setSetting('Flag', 'true')
        else:
            self.local_settings.setSetting('Flag', 'False')
        
    # 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 = 15
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

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

        self.Check_Box = JCheckBox("Extract and Create Memory Image from Hiberfile", actionPerformed=self.checkBoxEvent) 
        self.Blank_1.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.Check_Box, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Box ) 

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

        self.Label_3 = JLabel( "Message:") 
        self.Label_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.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.Check_Box.setSelected(self.local_settings.getSetting('Flag') == 'true')
        self.Program_Executable_TF.setText(self.local_settings.getSetting('Volatility_Directory'))
        #pass
        
    # Return the settings used
    def getSettings(self):
        return self.local_settings
예제 #42
0
class ChannelPanel(JPanel):

    gbc = GridBagConstraints()

    def __init__(self):
        JPanel.__init__(self)

        self.setLayout(GridBagLayout())
        self.setBorder(TitledBorder("Channel"))

        # some helper constants
        REL = GridBagConstraints.RELATIVE
        REM = GridBagConstraints.REMAINDER
        HORIZ = GridBagConstraints.HORIZONTAL
        NW = GridBagConstraints.NORTHWEST
        CENTER = GridBagConstraints.CENTER

        # --- title
        label = JLabel("Title:")
        self.constrain(label, REL, REL, REL, 1,
                       HORIZ, CENTER, 1.0, 1.0,
                       2, 2, 2, 2)
        self.field_title = JTextField()
        self.field_title.setEditable(0)
        self.constrain(self.field_title, REL, REL, REM, 1,
                       HORIZ, CENTER, 1.0, 1.0,
                       2, 2, 2, 2)

        # --- description
        label = JLabel("Description:")
        self.constrain(label, REL, REL, REL, 1,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)
        self.field_descr = JTextArea(3, 40)
        self.field_descr.setEditable(0)
        # wrap long lines
        self.field_descr.setLineWrap(1)
        # allow only full words to be wrapped
        self.field_descr.setWrapStyleWord(1)
        # ensure that the border look is the same
        self.field_descr.setBorder(self.field_title.getBorder())
        self.constrain(self.field_descr, REL, REL, REM, 1,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)

        # --- location
        label = JLabel("Location:")
        self.constrain(label, REL, REL, REL, 1,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)
        self.field_location = JTextField()
        self.constrain(self.field_location, REL, REL, REM, REL,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)

        # --- last update
        label = JLabel("Last Update:")
        self.constrain(label, REL, REL, REL, REM,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)
        self.field_lastupdate = JTextField()
        self.field_lastupdate.setEditable(0)
        self.constrain(self.field_lastupdate, REL, REL, REM, REM,
                       HORIZ, NW, 1.0, 1.0,
                       2, 2, 2, 2)

    def setChannel(self, channel):
        self.channel = channel
        self.field_title.setText(channel.getTitle())
        self.field_descr.setText(channel.getDescription())
        self.field_location.setText(channel.getLocation().toString())
        self.field_lastupdate.setText(channel.getSubscription().getLastUpdated().toString())

    def refresh(self):
        self.setChannel(self.channel)

    def constrain(self, component,
                  grid_x, grid_y, grid_width, grid_height,
                  fill, anchor, weight_x, weight_y,
                  top, left, bottom, right):
        container = self
        c = self.gbc
        c.gridx = grid_x
        c.gridy = grid_y
        c.gridwidth = grid_width
        c.gridheight = grid_height
        c.fill = fill
        c.anchor = anchor
        c.weightx = weight_x
        c.weighty = weight_y
        if (top + bottom + left + right > 0):
            c.insets = Insets(top, left, bottom, right)

        container.getLayout().setConstraints(component, c)
        container.add(component)
예제 #43
0
class SeniorDesign(JFrame):
        startTime =0
        endTime =0
        global timeTextField
        global end
        
        def __init__(self):
            self.timeTextField = JTextField("00:00")
            self.end = True
            pass
        
        def drawChart(self):
            data = [(10, 20, 30), (20, 65, 33),
                    (30, 55, 30), (40, 45, 51),
                    (50, 25, 27), (60, 75, 30)]

            ar = area.T(size = (150,120),
            y_grid_interval=10,
            x_axis=axis.X(label="X label", label_offset=(0,-7)),
            y_axis=axis.Y(label="Y label"),
            legend = legend.T(), y_range = (0, None))

            ar.add_plot(bar_plot.T(label="foo", data=data),
            line_plot.T(label="bar", data=data, ycol=2))
            ar.draw()
        def createChart(self):
            ds = XYDataset()
            data = { {0.1, 0.2, 0.3}, {1, 2, 3} }
            ds.addSeries("series1", data)
            chart = ChartFactory.createXYLineChart("DemoChart", "x", "y", PlotOrientation.VERTICAL, ds, True, True, False)
            chartPanel= ChartPanel()
            return chartPanel

        def createMenuBar(self):
            #JMenuBar menuBar;
            #JMenu soccerHub, subscriptions,skin,suggestions,help;
        
            menuBar = JMenuBar();
        
            #SoccerHub menu
            seniorDesign = JMenu("SeniorDesign");
            #seniorDesign.setMnemonic(KeyEvent.VK_0);
            menuBar.add(seniorDesign);
        
            #subscription menu
            statistics = JMenu("Statistics");
            #subscriptions.setMnemonic(KeyEvent.VK_1);
            menuBar.add(statistics);
        
            return menuBar;
        
        def mytimer(self,timeTextField):
            timer = Timer()
            while(True):
                timeTextField.setText(timer.getTime())
                
        def getTimeElapsed(self,elapsed):
            global startTime
            millis = int(round(time.time()*1000))
            #elapsedTime = millis - startTime;
            elapsedTime = elapsed
            #elapsedTime = elapsedTime / 1000;

            seconds = str((int)((elapsedTime/1000) % 60));
            minutes = str((int)((elapsedTime/(1000*60)) % 60));
            hours = str((int)((elapsedTime/(1000*60*60)) % 24));

            if (len(seconds) < 2):
                seconds = "0" + seconds;

            if (len(minutes) < 2):
                minutes = "0" + minutes;

            if (len(hours) < 2):
                hours = "0" + hours;

            return hours+":"+minutes+":"+seconds;
            
        def startTimer(self,event):
            global startTime
            #startTime = time.time()
            startTime = int(Calendar.getInstance().getTimeInMillis())
            self.updateTextField("Running")
            timer = Timer()
            

            

        def stopTimer(self,event):
            global endTime
            endTime = int(Calendar.getInstance().getTimeInMillis())
            self.updateTextField(self.getTimeElapsed(endTime-startTime))
            
        def timerListener(self,textfield):
            time = self.getTimeElapsed()
            textfield.setText(time)
            
        def printTime(self):
            print "Current time"+ self.getTimeElapsed(time.time()*1000)
        
        def updateTextField(self,text):
            self.timeTextField.setText(str(text))
            self.repaint()
            
        def updateText(self,textField,startTime):
            count=1
            while(count < 10000):
                #print "start Time" + str(self.getTimeElapsed(startTime))
                print "start Time: " + str(int(startTime))
                #print "end Time" + str(time.time()-startTime)
                elapsed = Calendar.getInstance().getTimeInMillis() - startTime
                #print "elapsed Time" + self.getTimeElapsed(elapsed)
                timer =Timer(1000,self.printTime,())
                timer.start()
                textField.setText( 'Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) );
                count =count+1
            #textField.setText(self.getTimeElapsed(elapsed))
        

            
        def addComponentsToPane(self):
            
            global stopWatch
           # global textF
            pane = JPanel()  
            layout = GridLayout(0,2)
            pane.setLayout(layout)
            
            
            distanceLabel = JLabel("Distance")
            pane.add(distanceLabel)
            
            distanceTextField = JTextField("Distance")
            pane.add(distanceTextField)
            
            timeLabel = JLabel("Time")
            pane.add(timeLabel)
            
            elapsed = Calendar.getInstance().getTimeInMillis()
            
            #timeTextField = JTextField("00:00")
            
            pane.add(self.timeTextField)
            
            colorLabel = JLabel("color")
            pane.add(colorLabel)
            
            colors = ["Black", "Blue", "Red"]
            colorCombo = JComboBox(colors)
            pane.add(colorCombo)
            startButton = JButton("Start", actionPerformed =self.startTimer)
            stopButton = JButton("Stop", actionPerformed = self.stopTimer)
            leftpanel = self.createChart()
        

            pane.add(startButton)
            pane.add(stopButton)
            self.add(pane)
            self.add(leftpanel,BorderLayout.EAST)

            

    
        def createAndShowGUI(self):
            frame= SeniorDesign()
            frame.setJMenuBar(self.createMenuBar())
            frame.addComponentsToPane()
            frame.pack()
            frame.setSize(500,500)
            frame.setVisible(True);
            
        def main(self):
            self.createAndShowGUI()
예제 #44
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
예제 #45
0
class BobGui(JFrame):
    def __init__(self):
        super(BobGui, self).__init__('BobPy')
        # IJ.log('okay?')
        # print('okay??')
        self.setLayout(BorderLayout())
        self.main_panel = JPanel()
        # self.main_panel.setLayout(MigLayout('insets 1 10 1 1'))
        self.main_panel.setLayout(MigLayout())

        dir_panel = JPanel()
        dir_panel.setLayout(BoxLayout(dir_panel, BoxLayout.X_AXIS))

        dir_label = JLabel('Experiment Folder:')
        dir_panel.add(dir_label)

        self.dir_text_field = JTextField(10)
        self.dir_text_field.addActionListener(
            ActionListenerFactory(self, self.text_field_al))
        dir_panel.add(self.dir_text_field)

        dir_button = JButton('open')
        dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))
        dir_panel.add(dir_button)

        self.main_panel.add(dir_panel, 'wrap, growx, spanx, pushx')

        add_key_args(self.main_panel, 'close_w',
                     ActionListenerFactory(self, self.close_al), KeyEvent.VK_W,
                     Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())

        self.add(self.main_panel, BorderLayout.CENTER)

        self.setPreferredSize(Dimension(650, 600))

        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)

    def show_exper_info(self):

        chf_panel = self.make_chf_panel()
        hseg_tree_panel = self.make_hseg_tree_panel()

        self.split_pane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)

        self.split_pane.setOneTouchExpandable(True)
        self.split_pane.setContinuousLayout(True)
        self.split_pane.setResizeWeight(0.5)

        self.split_pane.add(chf_panel)
        self.split_pane.add(hseg_tree_panel)
        self.main_panel.add(self.split_pane, 'grow, wrap')

        # self.log_text = JTextArea()
        self.main_panel.add(self.log_text, 'grow, wrap')
        self.log_text.setLineWrap(True)
        self.log_text.setWrapStyleWord(True)

        self.revalidate()

    def make_chf_panel(self):
        """ chf --> common hseg files """

        chf_panel = JPanel()
        chf_panel.setLayout(MigLayout('insets 0'))

        chf_files_label = JLabel('Hemisegment cells')
        chf_files_text = JTextArea(
            BobGui.archetype_to_str(
                self.exper.hseg_cell_files_cab().archetype))

        chf_panel.add(chf_files_label, 'growx, wrap')
        chf_panel.add(chf_files_text, 'grow, wrap')

        chf_files_label = JLabel('Hemisegment binary image files')
        chf_files_text = JTextArea(
            BobGui.archetype_to_str(self.exper.hseg_bin_files_cab().archetype))

        chf_panel.add(chf_files_label, 'growx, wrap')
        chf_panel.add(chf_files_text, 'grow, wrap')

        chf_files_label = JLabel('Intensity Image Files')
        # chf_files_text = JTextArea(BobGui.archetype_to_str(self.exper.hseg_intens_im_files_cab().archetype))
        # print(self.exper.hseg_intens_im_files_cab().archetype)

        # chf_panel.add(chf_files_label, 'growx, wrap')
        # chf_panel.add(chf_files_text, 'grow, wrap')

        self.intens_im_boxes = []
        intens_im_panel = JPanel()
        intens_im_panel.setLayout(MigLayout('insets 0'))
        for poss_im_file in self.exper.hseg_intens_im_files_cab().archetype:
            self.intens_im_boxes.append(JCheckBox(poss_im_file))
            intens_im_panel.add(self.intens_im_boxes[-1], 'wrap')

        chf_panel.add(chf_files_label, 'growx, wrap')
        chf_panel.add(intens_im_panel, 'grow, wrap')

        mdf_create_button = JButton(
            'Create meta_data file from default outline')
        # mdf_create_button = JButton('<html>Create meta_data file<br>from default outline</html>')
        mdf_create_button.addActionListener(
            ActionListenerFactory(self, self.mdf_create_al))
        mdf_open_button = JButton('Open existing meta_data file')
        mdf_open_button.addActionListener(
            ActionListenerFactory(self, self.mdf_open_al))

        # meta_data_file_buttton = JButton('Open/Create meta_data file')
        # meta_data_file_buttton.addActionListener(ActionListenerFactory(self, self.meta_data_al))

        # chf_panel.add(meta_data_file_buttton)
        chf_panel.add(mdf_create_button, 'wrap')
        chf_panel.add(mdf_open_button, 'wrap')
        chf_scroll_pane = JScrollPane()
        chf_scroll_pane.getViewport().setView(chf_panel)

        return chf_scroll_pane

    @staticmethod
    def archetype_to_str(archetype):

        at_str = ''
        for val in archetype:
            at_str += str(val) + '\n'
        return at_str

    def make_hseg_tree_panel(self):
        root = DefaultMutableTreeNode(self.exper.name)

        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            hseg_at_deviations = self.exper.hseg_files_cab(
            ).archetype_deviations
            if len(hseg_at_deviations[hseg.name]) > 0:
                for definer, file_names in hseg_at_deviations[
                        hseg.name].items():
                    for file_name in file_names:
                        node_str = definer + ': ' + file_name

                        temp = DefaultMutableTreeNode(node_str)
                        hseg_node.add(temp)

        hseg_tree = JTree(root)
        hseg_tree.setCellRenderer(BobPyTreeCellRenderer())

        hseg_scroll_pane = JScrollPane()
        hseg_scroll_pane.getViewport().setView((hseg_tree))

        hseg_panel = JPanel(MigLayout('insets 0'))
        hseg_panel.add(hseg_scroll_pane, 'grow, span, push, wrap')

        run_button = JButton('Run')
        run_button.addActionListener(ActionListenerFactory(self, self.run_al))
        rerun_button = JButton('Rerun')
        rerun_button.addActionListener(
            ActionListenerFactory(self, self.rerun_al))

        hseg_panel.add(run_button)
        hseg_panel.add(rerun_button)

        return hseg_panel

    def log(self, text):
        self.log_text.append(str(text) + '\n')

    def text_field_al(self, e):
        # self.dir_path =
        self.got_exper(self.dir_text_field.getText())

    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        # self.dir_path = dc.getDirectory()

        # self.dir_text_field.setText(self.dir_path)
        # self.dir_text_field.setText('blerg')
        # IJ.log('blerg')
        # print('boop')
        self.got_exper(dc.getDirectory())

    def close_al(self, e):
        self.dispatchEvent(WindowEvent(self, WindowEvent.WINDOW_CLOSING))

    def run_al(self, e):
        # dt = br.dtic('Processed experiment {}'.format(self.exper.name))
        t = br.tic()
        self.exper.make_data()
        self.exper.output_cell_cols_def()
        self.exper.output_nuc_cols_def()
        self.exper.output_new_hdings()

        self.exper.log('Processed experiment {} in {:.3f} seconds'.format(
            self.exper.name, br.toc(t)))
        # br.dtoc(dt)

    def rerun_al(self, e):
        # dt = br.dtic('Processed experiment {}'.format(self.exper.name))
        # t = br.tic()
        self.exper = None
        self.got_exper(self.dir_path)
        self.run_al(None)
        # self.exper =
        # self.exper.make_data()
        # self.exper.output_cell_cols_def()
        # self.exper.output_nuc_cols_def()
        # self.exper.output_new_hdings()
        #
        # self.exper.log('Created and processed experiment {} in {:.3f} seconds'.format(self.exper.name, br.toc(t)))
        # br.dtoc(dt)

    # def meta_data_al(self, e) :
    #     meta_data_path = self.exper.meta_data_path()
    #     if not os.path.exists(meta_data_path) :
    #         txt = make_meta_data_str(self.exper)
    #         with open(meta_data_path, 'w') as f :
    #             f.write(txt)
    #
    #     IJ.open(meta_data_path)

    def mdf_create_al(self, e):
        meta_data_path = self.exper.meta_data_path()
        # if not os.path.exists(meta_data_path) :
        intens_im_list = []
        for check_box in self.intens_im_boxes:
            if check_box.isSelected():
                intens_im_list.append(check_box.getLabel())
        txt = make_meta_data_str2(self.exper, intens_im_list)
        with open(meta_data_path, 'w') as f:
            f.write(txt)

        # IJ.open(meta_data_path)

    def mdf_open_al(self, e):
        meta_data_path = self.exper.meta_data_path()

        IJ.open(meta_data_path)

    def got_exper(self, dir_path):
        # IJ.log('exper')
        self.dir_path = dir_path
        self.dir_text_field.setText(self.dir_path)

        self.log_text = JTextArea()

        self.exper = bob_py.Exper(dir_path, gui=self)
        self.show_exper_info()
예제 #46
0
파일: mpconfig.py 프로젝트: DMDhariya/core
class CustomCellEditor(TreeCellEditor, ActionListener):
    """Renders the various tree edit controls (checkbox, tristate checkbox, text box etc.)"""
    def __init__(self, tree):
        TreeCellEditor.__init__(self)
        self.editor = None
        self.tree = tree

        flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0)

        self.cbPanel = JPanel(flowLayout)
        self.cb = JCheckBox(actionPerformed=self.checked)
        self.cbPanel.add(self.cb)
        self.cbLabel = JLabel()
        self.cbPanel.add(self.cbLabel)

        self.tcbPanel = JPanel(flowLayout)
        self.tcb = TristateCheckBox(self.checked)
        self.tcbPanel.add(self.tcb)
        self.tcbLabel = JLabel()
        self.tcbPanel.add(self.tcbLabel)

        self.rbPanel = JPanel(flowLayout)
        self.rb = JRadioButton(actionPerformed=self.checked)
        self.rbPanel.add(self.rb)
        self.rbLabel = JLabel()
        self.rbPanel.add(self.rbLabel)

        self.tfPanel = JPanel(flowLayout)
        self.tfLabel = JLabel()
        self.tfPanel.add(self.tfLabel)
        self.tf = JTextField()
        self.tf.setColumns(12)
        self.tf.addActionListener(self)
        self.tfPanel.add(self.tf)

    def addCellEditorListener(self, l):
        """Register for edit events"""
        self.listener = l

    def isCellEditable(self, event):
        if event != None and isinstance(
                event.getSource(), JTree) and isinstance(event, MouseEvent):
            tree = event.getSource()
            path = tree.getPathForLocation(event.getX(), event.getY())
            userData = path.getLastPathComponent().getUserObject()
            if isinstance(userData,
                          TreeNodeData) and (not userData.getNodeType().isType(
                              [NodeType._comment, NodeType._menu
                               ])) and (userData.getVisible() > 0):
                return True

        return False

    def shouldSelectCell(self, event):
        # log.info("shouldSelectCell")
        return True

    def cancelCellEditing(self):
        # log.info("Cancel editing, please!")
        # super(CustomCellEditor, self).cancelCellEditing()
        pass

    def stopCellEditing(self):
        # log.info("stopCellEditing")
        if self.nodeData.getNodeType().isType([NodeType._text]):
            # log.info("stopCellEditing for sure!")
            self.nodeData.setValue(str(self.tf.getText()))
        return True

    def getTreeCellEditorComponent(self, tree, value, selected, expanded, leaf,
                                   row):
        """Return a swing edit control appropriate for the node type of the supplied value"""
        self.nodeData = self.getNodeUserData(value)
        if self.nodeData:
            text = self.nodeData.getText()
            t = self.nodeData.getNodeType()

            # Boolean checkbox
            if t.isType([NodeType._bool]):
                self.editor = self.cbPanel
                self.cbLabel.setText(text)
                if self.nodeData.getTriValue() > 0:
                    self.cb.setSelected(True)
                else:
                    self.cb.setSelected(False)

            # Tristate checkbox
            elif t.isType([NodeType._tri]):
                # log.info("getTreeCellEditorComponent tristate")
                self.editor = self.tcbPanel
                self.tcbLabel.setText(text)
                self.tcb.setTriState(self.nodeData.getTriValue())

            # Radio button
            elif t.isType([NodeType._radio]):
                self.editor = self.rbPanel
                self.rbLabel.setText(text)
                if self.nodeData.getTriValue() > 0:
                    self.rb.setSelected(True)
                else:
                    self.rb.setSelected(False)

            # Text field
            elif t.isType([NodeType._text]):
                self.editor = self.tfPanel
                self.tfLabel.setText(str(self.nodeData.getText()) + ":")
                self.tf.setText(str(self.nodeData.getValue()))

            else:
                self.editor = self.tcb
                self.editor.setText(text)

        return self.editor

    def getNodeUserData(self, value):
        """Gets the TreeNodeData from the tree node"""
        if isinstance(value, DefaultMutableTreeNode):
            nodeData = value.getUserObject()
            if isinstance(nodeData, TreeNodeData):
                return nodeData

        return None

    def getCellEditorValue(self):
        newNode = TreeNodeData(self.nodeData.knode, self.tree)

        if isinstance(self.editor, JTextField):
            newNode.setValue(str(self.editor.getText()))

        return newNode

    def checked(self, e):
        """Updates the node data when a checkbox has been clicked"""
        control = e.getSource()

        if isinstance(control, TristateCheckBox):
            # log.info("tristate checked")
            self.nodeData.setTriValue(control.getTriState())
        else:
            # log.info("checkbox checked")
            if control.isSelected():
                self.nodeData.setValue(2)
            else:
                self.nodeData.setValue(0)

    def actionPerformed(self, event):
        """ ENTER pressed in text field, stop editing."""
        tf = event.getSource()
        self.listener.editingStopped(ChangeEvent(tf))
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

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

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

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

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

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

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

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
    text = feld.getText()
    name = feld2.getText() + ".csv"
    with open(name,"w") as f:
        f.write(text)
        print(name + " gespeichert")
        return(text)

button = JButton('Lektion speichern!', actionPerformed=change_text,size=(10,20))
button.setBounds(20,40,20,40);
pnl = JPanel()
pnl.setLayout(BoxLayout(pnl, BoxLayout.Y_AXIS))
feld = JTextArea()
feld.editable = True
feld.setText("Deutsch,Englisch\n")
feld2 = JTextField()
feld2.setText("Ersetzen durch Namen der Lektion")
pnl.add(feld2)
pnl.add(feld)
pnl.add(button)
frame.add(pnl)
frame.setVisible(True) 


class Main(Client):
    def __init__(self):
        pass

    def stateChanged(self, cs):
        print "new state: " + str(cs)

    def sessionStarted(self):
예제 #49
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener):

    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):
        print "PhantomJS RIA Crawler extension"
        print "Nikolay Matyunin @autorak <*****@*****.**>"

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

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

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

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

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

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

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

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

        _separator = JSeparator(SwingConstants.HORIZONTAL)

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

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

        self._commandClient = CommandClient(self)

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

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

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

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


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

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

        return

    #
    # implement ITab and Tab ChangeListener
    #
    def getTabCaption(self):
        return "Phantom RIA Crawler"
    def getUiComponent(self):
        return self._jPanel
    def stateChanged(self, ev):
        self._configUpdated()

    def _configUpdated(self, ev):
        config = self._callbacks.saveConfig()

        # update proxy listeners
        index = 0
        listeners = DefaultComboBoxModel()
        while (("proxy.listener" + str(index)) in config):
            listenerItem = config["proxy.listener" + str(index)]
            listenerItems = listenerItem.split(".")
            if (listenerItems[0] == "1"):
                address = ".".join(listenerItems[2][1:].split("|"))
                if (len(address) == 0):
                    address = "127.0.0.1"
                listeners.addElement(address + " : " + listenerItems[1])

            index = index + 1
        self._listenersCombo.setModel(listeners)
        return;

    #
    # implement button actions
    #
    def startToggled(self, ev):
        if (self._startButton.getModel().isSelected()):
            try:
                os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts")
            except Exception as e:
                print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror)
                self._startButton.setSelected(False)
                return

            phantomJsPath = self._phantomJsPathField.text
            target = self._addressTextField.text

            config = "crawler.config"
            if (self._configFile):
                config = self._configFile

            listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "")
            p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True)
            self._running = True
            self._requestsMadeInfo.setText("")
            self._statesFoundInfo.setText("")
            self._commandClient.startCrawling()
        else:
            if (self._running):
                self._commandClient.stopCrawling()
            self._running = False

    def syncCrawlingState(self, result):
        print "RIA crawling state: ", result
        self._requestsMadeInfo.setText(str(result["requests_made"]))
        self._statesFoundInfo.setText(str(result["states_detected"]))
        if (result["running"] == False):
            self._commandClient.stopCrawling()
            self._running = False
            self._startButton.setSelected(False)

    def loadConfigClicked(self, ev):
        openFile = JFileChooser();
        openFile.showOpenDialog(None);
        self._configFile = openFile.getSelectedFile()

    #
    # implement DocumentListener for _addressTextField
    #
    def removeUpdate(self, ev):
        self.updateStartButton()
    def insertUpdate(self, ev):
        self.updateStartButton()
    def updateStartButton(self):
        self._startButton.setEnabled(len(self._addressTextField.text) > 0)


    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, contextMenuInvocation):
        menuItemList = ArrayList()

        context = contextMenuInvocation.getInvocationContext()
        if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or
            context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE):

            self._contextMenuData = contextMenuInvocation.getSelectedMessages()
            menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked))

        return menuItemList


    def menuItemClicked(self, event):
        if (self._running == True):
            self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.")
            return;

        dataIsSet = False;
        for message in self._contextMenuData:
            request = self._helpers.analyzeRequest(message)

            url = request.getUrl().toString()
            print url
            if (url):
                dataisSet = True;
                self._addressTextField.setText(url)
예제 #50
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   ActionListener, DocumentListener):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):

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

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

        # set our extension name
        callbacks.setExtensionName("Response Clusterer")

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

        # main split pane
        self._main_jtabedpane = JTabbedPane()

        # The split pane with the log and request/respponse details
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

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

        # List of log entries
        self._log_entries = []

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

        #Setup the options
        self._optionsJPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gbc = GridBagConstraints()
        self._optionsJPanel.setLayout(gridBagLayout)

        self.max_clusters = 500
        self.JLabel_max_clusters = JLabel("Maximum amount of clusters: ")
        gbc.gridy = 0
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_max_clusters, gbc)
        self.JTextField_max_clusters = JTextField(str(self.max_clusters), 5)
        self.JTextField_max_clusters.getDocument().addDocumentListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_max_clusters, gbc)
        callbacks.customizeUiComponent(self.JLabel_max_clusters)
        callbacks.customizeUiComponent(self.JTextField_max_clusters)

        self.similarity = 0.95
        self.JLabel_similarity = JLabel("Similarity (between 0 and 1)")
        gbc.gridy = 1
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_similarity, gbc)
        self.JTextField_similarity = JTextField(str(self.similarity), 5)
        self.JTextField_similarity.getDocument().addDocumentListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_similarity, gbc)
        callbacks.customizeUiComponent(self.JLabel_similarity)
        callbacks.customizeUiComponent(self.JTextField_similarity)

        self.use_quick_similar = False
        self.JLabel_use_quick_similar = JLabel(
            "Use set intersection of space splitted tokens for similarity (default: optimized difflib.SequenceMatcher.quick_ratio)"
        )
        gbc.gridy = 2
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_use_quick_similar, gbc)
        self.JCheckBox_use_quick_similar = JCheckBox("")
        self.JCheckBox_use_quick_similar.addActionListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JCheckBox_use_quick_similar, gbc)
        callbacks.customizeUiComponent(self.JCheckBox_use_quick_similar)

        self.response_max_size = 10 * 1024  #10kb
        self.JLabel_response_max_size = JLabel("Response max size (bytes)")
        gbc.gridy = 3
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_response_max_size, gbc)
        self.JTextField_response_max_size = JTextField(
            str(self.response_max_size), 5)
        self.JTextField_response_max_size.getDocument().addDocumentListener(
            self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_response_max_size, gbc)
        callbacks.customizeUiComponent(self.JLabel_response_max_size)
        callbacks.customizeUiComponent(self.JTextField_response_max_size)

        self.uninteresting_mime_types = ('JPEG', 'CSS', 'GIF', 'script', 'GIF',
                                         'PNG', 'image')
        self.uninteresting_status_codes = ()
        self.uninteresting_url_file_extensions = ('js', 'css', 'zip', 'war',
                                                  'jar', 'doc', 'docx', 'xls',
                                                  'xlsx', 'pdf', 'exe', 'dll',
                                                  'png', 'jpeg', 'jpg', 'bmp',
                                                  'tif', 'tiff', 'gif', 'webp',
                                                  'm3u', 'mp4', 'm4a', 'ogg',
                                                  'aac', 'flac', 'mp3', 'wav',
                                                  'avi', 'mov', 'mpeg', 'wmv',
                                                  'swf', 'woff', 'woff2')

        about = "<html>"
        about += "Author: floyd, @floyd_ch, http://www.floyd.ch<br>"
        about += "modzero AG, http://www.modzero.ch<br>"
        about += "<br>"
        about += "<h3>Getting an overview of the tested website</h3>"
        about += "<p style=\"width:500px\">"
        about += "This plugin clusters all response bodies by similarity and shows a summary, one request/response per cluster. "
        about += 'Adjust similarity in the options if you get too few or too many entries in the "One member of each cluster" '
        about += "tab. The plugin will allow a tester to get an overview of the tested website's responses from all tools (scanner, proxy, etc.). "
        about += "As similarity comparison "
        about += "can use a lot of ressources, only small, in-scope responses that have interesting response codes, "
        about += "file extensions and mime types are processed. "
        about += "</p>"
        about += "</html>"
        self.JLabel_about = JLabel(about)
        self.JLabel_about.setLayout(GridBagLayout())
        self._aboutJPanel = JScrollPane(self.JLabel_about)

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

        # add the splitpane and options to the main jtabedpane
        self._main_jtabedpane.addTab("One member of each cluster", None,
                                     self._splitpane, None)
        self._main_jtabedpane.addTab("Options", None, self._optionsJPanel,
                                     None)
        self._main_jtabedpane.addTab("About & README", None, self._aboutJPanel,
                                     None)

        # clusters will grow up to self.max_clusters response bodies...
        self._clusters = set()
        self.Similarity = Similarity()

        # Now load the already stored
        with self._lock:
            log_entries_from_storage = self.load_project_setting("log_entries")
            if log_entries_from_storage:
                for toolFlag, req, resp, url in log_entries_from_storage:
                    try:
                        self.add_new_log_entry(toolFlag, req, resp, url)
                    except Exception as e:
                        print "Exception when deserializing a stored log entry", toolFlag, url
                        print e

        # Important: Do this at the very end (otherwise we could run into troubles locking up entire threads)
        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

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

    #
    # implement what happens when options are changed
    #

    def changedUpdate(self, document):
        pass

    def removeUpdate(self, document):
        self.actionPerformed(None)

    def insertUpdate(self, document):
        self.actionPerformed(None)

    def actionPerformed(self, actionEvent):
        self.use_quick_similar = self.JCheckBox_use_quick_similar.isSelected()
        try:
            self.max_clusters = int(self.JTextField_max_clusters.getText())
        except:
            self.JTextField_max_clusters.setText("200")

        try:
            self.similarity = float(self.JTextField_similarity.getText())
            if self.similarity > 1.0 or self.similarity < 0.0:
                self.JTextField_similarity.setText("0.9")
        except:
            self.JTextField_similarity.setText("0.9")

        try:
            self.response_max_size = float(
                self.JTextField_response_max_size.getText())
            if self.response_max_size < 0.0:
                self.JTextField_response_max_size.setText(str(10 * 1024))
        except:
            self.JTextField_response_max_size.setText(str(10 * 1024))

        print self.JCheckBox_use_quick_similar.isSelected(
        ), self.JTextField_max_clusters.getText(
        ), self.JTextField_similarity.getText(
        ), self.JTextField_response_max_size.getText()

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "Response Clusterer"

    def getUiComponent(self):
        return self._main_jtabedpane

    #
    # implement IHttpListener
    #

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if not messageIsRequest:
            if len(self._clusters) >= self.max_clusters:
                return
            resp = messageInfo.getResponse()
            if len(resp) >= self.response_max_size:
                print "Message was too long"
                return
            iResponseInfo = self._helpers.analyzeResponse(resp)
            mime_type = iResponseInfo.getStatedMimeType()
            if mime_type in self.uninteresting_mime_types:
                print "Mime type", mime_type, "is ignored"
                return
            if iResponseInfo.getStatusCode(
            ) in self.uninteresting_status_codes:
                print "Status code", iResponseInfo.getStatusCode(
                ), "is ignored"
                return
            req = messageInfo.getRequest()
            iRequestInfo = self._helpers.analyzeRequest(messageInfo)
            if not iRequestInfo.getUrl():
                print "iRequestInfo.getUrl() returned None, so bailing out of analyzing this request"
                return
            if '.' in iRequestInfo.getUrl().getFile() and iRequestInfo.getUrl(
            ).getFile().split(
                    '.')[-1] in self.uninteresting_url_file_extensions:
                print iRequestInfo.getUrl().getFile().split(
                    '.')[-1], "is an ignored file extension"
                return
            if not self._callbacks.isInScope(iRequestInfo.getUrl()):
                print iRequestInfo.getUrl(), "is not in scope"
                return
            body = resp[iResponseInfo.getBodyOffset():]
            with self._lock:
                similarity_func = self.Similarity.similar
                if self.use_quick_similar:
                    similarity_func = self.Similarity.quick_similar
                start_time = time.time()
                for response_code, item in self._clusters:
                    if not response_code == iResponseInfo.getStatusCode():
                        #Different response codes -> different clusters
                        continue
                    if similarity_func(str(body), str(item), self.similarity):
                        return  #break
                else:  #when no break/return occures in the for loop
                    self.add_new_log_entry(toolFlag, req, resp,
                                           iRequestInfo.getUrl().toString())
                    self.save_project_setting("log_entries", self._log_entries)
                taken_time = time.time() - start_time
                if taken_time > 0.5:
                    print "Plugin took", taken_time, "seconds to process request... body length:", len(
                        body), "current cluster length:", len(self._clusters)
                    print "URL:", str(iRequestInfo.getUrl()),

    def add_new_log_entry(self, toolFlag, request, response, service_url):
        self._log_entries.append((toolFlag, request, response, service_url))
        iResponseInfo = self._helpers.analyzeResponse(response)
        body = response[iResponseInfo.getBodyOffset():]
        self._clusters.add((iResponseInfo.getStatusCode(), str(body)))
        row = self._log.size()
        service = CustomHttpService(service_url)
        r = CustomRequestResponse(None, None, service, request, response)
        iRequestInfo = self._helpers.analyzeRequest(r)
        self._log.add(
            LogEntry(toolFlag, self._callbacks.saveBuffersToTempFiles(r),
                     iRequestInfo.getUrl()))
        self.fireTableRowsInserted(row, row)

    #
    # 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 "Tool"
        if columnIndex == 1:
            return "URL"
        return ""

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

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

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

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

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

    def save_project_setting(self, name, value):
        value = pickle.dumps(value).encode("base64")
        request = "GET /"+name+" HTTP/1.0\r\n\r\n" \
                  "You can ignore this item in the site map. It was created by the ResponseClusterer extension. The \n" \
                  "reason is that the Burp API is missing a certain functionality to save settings. \n" \
                  "TODO Burp API limitation: This is a hackish way to be able to store project-scope settings.\n" \
                  "We don't want to restore requests/responses of tabs in a totally different Burp project.\n" \
                  "However, unfortunately there is no saveExtensionProjectSetting in the Burp API :(\n" \
                  "So we have to abuse the addToSiteMap API to store project-specific things\n" \
                  "Even when using this hack we currently cannot persist Collaborator interaction checks\n" \
                  "(IBurpCollaboratorClientContext is not serializable and Threads loose their Python class\n" \
                  "functionality when unloaded) due to Burp API limitations."
        response = None
        if value:
            response = "HTTP/1.1 200 OK\r\n" + value
        rr = CustomRequestResponse(
            name, '',
            CustomHttpService('http://responseclustererextension.local/'),
            request, response)
        self._callbacks.addToSiteMap(rr)

    def load_project_setting(self, name):
        rrs = self._callbacks.getSiteMap(
            'http://responseclustererextension.local/' + name)
        if rrs:
            rr = rrs[0]
            if rr.getResponse():
                val = "\r\n".join(
                    FloydsHelpers.jb2ps(rr.getResponse()).split("\r\n")[1:])
                return pickle.loads(val.decode("base64"))
            else:
                return None
        else:
            return None
예제 #51
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
예제 #52
0
class EditSettingsView(JDialog):
    def __init__(self, controller, working_dir, servers, keystrokes, languages,
                 projects):
        self.logger = logging.getLogger("NammuController")
        self.setAlwaysOnTop(True)
        self.controller = controller
        self.working_dir = working_dir
        self.servers = servers
        self.keystrokes = keystrokes
        self.languages = languages
        self.projects = projects
        self.pane = self.getContentPane()

    def build(self):
        '''
        Create all tab panels and put together to form the settings window.
        '''
        self.setLayout(BorderLayout())
        self.add(self.build_tabbed_panel(), BorderLayout.CENTER)
        self.add(self.build_buttons_panel(), BorderLayout.SOUTH)

    def build_tabbed_panel(self):
        '''
        Build panel with tabs for each of the settings editable sections.
        '''
        tabbed_pane = JTabbedPane()
        tab_titles = ["General", "Keystrokes", "Languages", "Projects"]
        for title in tab_titles:
            panel = self.build_settings_panel(title.lower())
            tabbed_pane.addTab(title, panel)
        return tabbed_pane

    def build_settings_panel(self, text):
        '''
        Call correspondent method to create panel for given tab text.
        '''
        panel = getattr(self, "build_{}_panel".format(text))()
        return panel

    def build_general_panel(self):
        '''
        Create the panel that'll go in the General tab. This should contain
        options for choosing which server to use for validation as well as
        default working dir.
        '''
        panel = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.insets = Insets(10, 10, 10, 10)
        panel = self.build_working_dir_panel(constraints, panel)
        panel = self.build_servers_panel(constraints, panel)
        return panel

    def build_working_dir_panel(self, constraints, panel):
        '''
        Working directory row: label + field + button
        This is for users to browse for their preferred default directory
        when opening/creating a new file.
        '''
        working_dir_label = JLabel("Working directory:")
        constraints.weightx = 0.30
        constraints.gridx = 0
        constraints.gridy = 0
        constraints.anchor = GridBagConstraints.EAST
        panel.add(working_dir_label, constraints)

        self.field = JTextField()
        self.field.setEditable(False)
        # Can't find an elegant way to default to something that would be
        # crossplatform, and I can't leave the default field empty.
        if self.working_dir['default'] != "None":
            self.field.setText(self.working_dir['default'])
        else:
            self.field.setText(os.getcwd())
        constraints.weightx = 0.60
        constraints.gridx = 1
        constraints.gridy = 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.insets = Insets(10, 10, 10, 5)
        panel.add(self.field, constraints)

        constraints.fill = 0
        button = JButton("Browse", actionPerformed=self.browse)
        constraints.weightx = 0.10
        constraints.gridx = 2
        constraints.gridy = 0
        constraints.insets = Insets(10, 0, 10, 10)
        panel.add(button, constraints)

        return panel

    def build_servers_panel(self, constraints, panel):
        '''
        Server location row: label + dropdown
        Contains a drop down with the servers to choose from.
        '''
        constraints.insets = Insets(10, 10, 80, 10)
        server_label = JLabel("ORACC server location:")
        constraints.weightx = 0.30
        constraints.gridx = 0
        constraints.gridy = 1
        panel.add(server_label, constraints)

        self.combo = self.build_servers_combobox()
        constraints.weightx = 0.70
        constraints.gridx = 1
        constraints.gridy = 1
        constraints.gridwidth = 2
        constraints.fill = GridBagConstraints.HORIZONTAL
        panel.add(self.combo, constraints)

        return panel

    def build_servers_combobox(self):
        combo = JComboBox()
        # Go through list of servers and add to combo box.
        for server in self.servers.keys():
            if server != "default":
                combo_item = "{}: {}:{}".format(server,
                                                self.servers[server]['url'],
                                                self.servers[server]['port'])
                combo.addItem(combo_item)
                # If this item is the default one, set it as selected
                if server == self.servers['default']:
                    combo.setSelectedItem(combo_item)
        return combo

    def build_buttons_panel(self):
        '''
        Builds the buttons panel to save or cancel changes.
        TODO: Reset button to reset to defaults?
        '''
        panel = JPanel(FlowLayout())
        panel.add(JButton('Cancel', actionPerformed=self.cancel))
        panel.add(JButton('Save', actionPerformed=self.save))
        return panel

    def build_keystrokes_panel(self):
        '''
        Create the panel that'll go in the Keystrokes tab. This should contain
        options for choosing which keystrokes are to be assigned to which
        actions.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_languages_panel(self):
        '''
        Create the panel that'll go in the Languages tab. This should contain
        options for choosing which is the list of languages that can be
        included from the new ATF window and their abbrv.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def build_projects_panel(self):
        '''
        Create the panel that'll go in the Projects tab. This should contain
        the list of preferred projects and a means to select which is the
        preferred default.
        '''
        panel = JPanel()
        label = JLabel("Coming soon...")
        panel.add(label, BorderLayout.CENTER)
        return panel

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("Edit settings")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def display_error(self, keyword):
        '''
        Display error message when keyword is not in settings file.
        '''
        pass

    def cancel(self, event=None):
        '''
        Close window and don't save changes.
        '''
        self.dispose()

    def save(self, event=None):
        '''
        Save changes made by user on local settings file.
        '''
        # Update only the working_dir and the server for now
        # TODO: update keystrokes, projects list, etc.
        working_dir = self.field.getText()
        # The server format is "name: url:port". We only need "name"
        server = self.combo.getSelectedItem().split(':')[0]
        self.controller.update_config(working_dir, server)
        # Close window
        self.dispose()

    def browse(self, event=None):
        '''
        Open new dialog for the user to select a path as default working dir.
        '''
        default_path = self.field.getText()
        if not os.path.isdir(default_path):
            default_path = os.getcwd()
        fileChooser = JFileChooser(default_path)
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        # Fixed showDialog bug using showOpenDialog instead. The former was
        # duplicating the last folder name in the path due to a Java bug in
        # OSX in the implementation of JFileChooser!
        status = fileChooser.showOpenDialog(self)
        if status == JFileChooser.APPROVE_OPTION:
            self.field.setText(fileChooser.getSelectedFile().toString())
예제 #53
0
class Menue(object):
    def __init__(self, p):
        self.cellCounter = 1
        self.olay = Overlay()
        self.position = p
        print p.getRoiPath()
        if p.getRoiPath() != None:         # check if there is an existing overlay file and load it!
            p.loadRois()

        self.frame = JFrame("CellCropper", size=(200,200))
        self.frame.setLocation(20,120)
        self.Panel = JPanel(GridLayout(0,1))
        self.frame.add(self.Panel)
        #self.nameField = JTextField("p" + "_c",15)
        self.nameField = JTextField("p" + str(self.position.getID()) + "_c",15)
        self.Panel.add(self.nameField)
        self.cutoutButton = JButton("Cut out cell",actionPerformed=cut)
        self.Panel.add(self.cutoutButton)
        self.delOlButton = JButton("Delete Overlay",actionPerformed=delOverlay)
        self.Panel.add(self.delOlButton)
        self.saveOlButton = JButton("Save Overlay",actionPerformed=saveOverlay)
        self.Panel.add(self.saveOlButton) 
        self.quitButton = JButton("Quit script",actionPerformed=quit)
        self.Panel.add(self.quitButton)
        self.frame.pack()
        WindowManager.addWindow(self.frame)
        self.show()
        #IJ.setTool("freehand")

    '''def getPosition(self, path, filename):
       moved to containers.position.determineID(path, filename)'''

    def eventtest(self, event):
        print "eventtest"

    def setTextField(self, pos):
        name = "p" + str(pos) + "_c"
        self.nameField.setText(name)

    def openOl(self, path, fileName):
        print "aaaaah"

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

    def close(self):
        if self.olay != None:
            yncd = YesNoCancelDialog(self.frame, "Save overlay?", "Save overlay?") #frame, title, message
            if yncd.yesPressed():
                self.saveOverlay()
        WindowManager.removeWindow(self.frame)
        self.frame.dispose()
        
    def resetCounter(self):
        self.cellCounter = 0
        
    def increaseCounter(self):
        self.cellCounter += 1
        
    def setCounter(self):
        self.cellCounter += 1
        
    #'get' functions
    def getImp(self):
        return self.imp
    
    def getCounter(self):
        return self.cellCounter
        
    def getFrame(self):
        return self.frame
        
    def getFilePath(self):
        return self.filePath

    def getTextField(self):
        return self.nameField.text
    
    def getPosition(self):
        return self.position
    
    # overlay functions
    def addOlay(self, roi):
        self.olay.add(roi)

    def getOverlay(self):
        return self.olay

    def clearOverlay(self):
        self.olay.clear()
        self.cellCounter = 1

    def saveOverlay(self):
        self.position.saveRois()   
예제 #54
0
class RegForm(JPanel):
    def __init__(self):

        self.nameLabel = JLabel('Owner Name : ')
        self.nameField = JTextField(10)
        self.mobLabel = JLabel('Mob No : ')
        self.mobField = JTextField(10)
        self.emailLabel = JLabel('Email : ')
        self.emailField = JTextField(10)
        self.vehicleLabel = JLabel('Vehicle No : ')
        self.vehicleField = JTextField(10)
        self.regBtn = JButton('Register', actionPerformed=self.registerVehicle)
        icon = ImageIcon("Refreshp.png")
        self.automateRecogBtn = JButton(
            'Auto', icon, actionPerformed=self.automateRecognition)

        self.setPreferredSize(Dimension(400, CENTER_Y))
        self.initComponents()

    def initComponents(self):

        self.setLayout(GridBagLayout())

        gc = GridBagConstraints()

        gc.weightx = 1
        gc.weighty = 1

        # First Row
        gc.gridy = 0

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.fill = GridBagConstraints.NONE
        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.nameLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.nameField, gc)

        # Second Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.mobLabel, gc)

        gc.gridx = 1

        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.mobField, gc)

        #Third Row
        gc.gridy += 1

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.emailLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.emailField, gc)

        #Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.vehicleLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.vehicleField, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 2
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.automateRecogBtn, gc)

        #Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 2.0
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        self.add(self.regBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Register Vehicle')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))

    def registerVehicle(self, e):
        print 'panel done'

        name = self.nameField.getText()
        mob = self.mobField.getText()
        email = self.emailField.getText()
        lplate = self.vehicleField.getText()

        fields = [name, mob, email, lplate]
        if isFieldsEmpty(fields):
            dialog.improperInput('One or more fields are missing!', 'No Input')
        elif not rut.isMobileNo(mob):
            dialog.improperInput('Invalid mobile number', 'Invalid Input')
        elif not rut.isEmail(email):
            dialog.improperInput('Enter a valid email address',
                                 'Invalid email')
        else:
            name = self.nameField.getText()
            mob = self.mobField.getText()
            email = self.emailField.getText()
            lplate = self.vehicleField.getText()
            lplate = rut.removeSpace(lplate)
            owner = [name, mob, email]
            vehicle = [lplate]
            client.register_vehicle(owner, vehicle)
            self.validate()

    def automateRecognition(self, e):
        print 'Add automate recog here !!'
        plate = client.recognize_plate()
        if plate:
            msg = 'confirm plate:' + plate
            response = dialog.dispQuestion(msg, 'confirm')

            if response:
                self.vehicleField.setText(plate)
                client.set_progress([1, 1, 0, 0])
            else:
                client.set_progress([1, 0, 0, 0])
                self.vehicleField.setText('')
        else:
            client.set_progress([1, 0, 0, 0])
            dialog.dispErrorMsg('coudnot reocnize!')
예제 #55
0
    class ConsoleController:
        def __init__(self, parent):
            self._parent = parent
            self._sessions = self._parent.sessions()
            self._request = None #TODO I'll need a request in order to connect to something
            self._position = None #TODO I'll need a position, something to change in the header to insert the command
            self._pwd = None
            self._commandHistory = []
            self._historyIndex = 0
            self._tabComplete = []

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            # input
            self._consolePwd = JTextField()
            self._consolePwd.setEditable(False)
            self._consolePwd.setText("Not initialized")
            self._consoleInput = JTextField()
            #Remove 'tab' low-level tab-function of jumping to other component, so I can use it
            self._consoleInput.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET)
            self._consoleInput.addActionListener(self.EnterPress())
            self._consoleInput.addKeyListener(self.KeyPress())
            self._inputPanel = JPanel(BorderLayout())
            self._inputPanel.add(self._consolePwd, BorderLayout.WEST)
            self._inputPanel.add(self._consoleInput, BorderLayout.CENTER)
            # output
            self._consoleOutput = JTextArea()
            self._consoleOutput.setEditable(False)
            self._consoleOutput.setForeground(Color.WHITE)
            self._consoleOutput.setBackground(Color.BLACK)
            self._consoleOutput.setFont(self._consoleOutput.getFont().deriveFont(12.0))

            self._scrollPaneConsoleOutput = JScrollPane(self._consoleOutput)

            # Add to main panel and return the main panel
            self._mainPanel.add(self._scrollPaneConsoleOutput, BorderLayout.CENTER)
            self._mainPanel.add(self._inputPanel, BorderLayout.SOUTH)
            return self._mainPanel

        def sendCommand(self, requestId, cmd, directTo):
            Utils.out("ConsoleController > sendCommand > 'cmd'")
            Utils.out(cmd)
            if cmd == 'clear':
                self.resetOutput()
                self._commandHistory.append(cmd)
                self.resetHistoryIndex()
                self.clearCmd()
                return
            cmdModified = cmd
            requestHttpMethod = self._parent.getRequestHttpService(requestId)
            #If I use virtual persistence and there's already a pwd set
            if Utils.shellController._virtualPersistence and self.pwd():
                #Then always prepend 'cd <pwd>' to any command executed. In reality we
                # always enter in the same directory, but because this shell keeps track
                # of where the user thinks he is, and always goes to that directory first
                # the illusion of a persistence is created
                cmdVirtual = "cd " + self.pwd()
                cmdModified = cmdVirtual + "; " + cmd
            requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified)
            Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start()
            self._commandHistory.append(cmd)
            self.resetHistoryIndex()
            self.clearCmd()

            if Utils.shellController._virtualPersistence:
                if cmd.startswith('cd '):
                    Utils.out("ConsoleController > sendCommand: detected 'cd '")
                    #ask for pwd
                    cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start()
                if Utils.shellController._tabCompletion:
                    #ask 'ls -1a' for tab-completion
                    # The first command, pwd is set here, but cmdVirtual ain't. But this
                    # also means we are at the entry directory anyway, so we can just ask ls
                    # and get the correct tab completion anyway
                    try:
                        cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX)
                    except:
                        cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
            else:
                if Utils.shellController._tabCompletion:
                    cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()

            #either way execute the requested command

        def startSession(self):
            #TODO when starting a session I want to test for a number of things:
            # if I can reform the request to a post request and still have it work
            # if base 64 is available
            # if bash is available
            self.setPwd(None)
            if Utils.shellController._virtualPersistence and Utils.shellController._outputIsolator:
                Utils.out("startSession > virtualPersistence enabled > Requesting pwd")
                self.sendCommand(self._parent.currentRequestId(), Commands.pwd(Commands.OS_LINUX), 'pwd')

        def appendOutput(self, text, printCommand=True):
            try:
                if printCommand:
                    self.printCommand(self._commandHistory[-1])
            except:
                pass

            self._consoleOutput.append("\n" + text)
            #auto scroll down if needed
            self._consoleOutput.setCaretPosition(self._consoleOutput.getDocument().getLength())

        def resetOutput(self):
            Utils.setConsole('')

        def printCommand(self, cmd):
            self._consoleOutput.append("\n" + self._pwd + "# " + cmd)

        def printCurrentCommand(self):
            self.printCommand(self.cmd())

        def setPwd(self, pwd):
            self._pwd = pwd
            if pwd is None:
                self._consolePwd.setText('')
            else:
                self._consolePwd.setText(pwd)
            Utils.consoleController._mainPanel.revalidate()

        def pwd(self):
            return self._pwd

        def cmdHistoryCount(self):
            return len(self._commandHistory) #TODO - 1

        def setCmd(self, cmd):
            self._consoleInput.setText(cmd)

        def cmd (self):
            return self._consoleInput.getText()

        def clearCmd(self):
            self._consoleInput.setText('')

        def resetHistoryIndex(self):
            self._historyIndex = self.cmdHistoryCount()

        def previousCommand(self):
            if self._historyIndex > 0:
                self._historyIndex -= 1
                self.setCmd(self._commandHistory[self._historyIndex])

        def nextCommand(self):
            if self._historyIndex < self.cmdHistoryCount():
                self._historyIndex += 1
                self.setCmd(self._commandHistory[self._historyIndex])
            else:
                self.clearCmd()
                self.resetHistoryIndex()

        def setTabComplete(self, text):
            self._tabComplete = text.splitlines()

        def findTabComplete(self, beginCharacters=''):
            suggestions = []
            if beginCharacters:
                for suggestion in self._tabComplete:
                    Utils.debug("suggestion", suggestion)
                    Utils.debug("text", beginCharacters)
                    if suggestion[0:len(beginCharacters)] == beginCharacters:
                        suggestions.append(suggestion)
            else:
                suggestions = self._tabComplete
            return suggestions

        def tabComplete(self):
            currentCommand = self.cmd()
            Utils.debug("currentCommand", currentCommand)
            if currentCommand:
                commandArray = currentCommand.split(' ')
                lastword = commandArray.pop()
                Utils.debug("lastword", lastword)
                suggestions = self.findTabComplete(lastword)
                if suggestions:
                    if len(suggestions) > 1:
                        self.printCurrentCommand()
                        for suggestion in suggestions:
                            self.appendOutput(suggestion, False)
                    if len(suggestions) == 1:
                        self.setCmd(' '.join(commandArray) + ' ' + suggestions.pop())
            else:
                suggestions = self.findTabComplete()
                if len(suggestions) > 1:
                    self.printCurrentCommand()
                    for suggestion in suggestions:
                        self.appendOutput(suggestion, False)

        class EnterPress(ActionListener): #TODO remove: AbstractAction
            def actionPerformed(self, e):
                Utils.consoleController.sendCommand(Utils.shellController.currentRequestId(), Utils.consoleInput.getText(), 'console')

            def keyPressed(self, e):
                Utils.out("key pressed")

        class KeyPress(KeyListener):
            def keyTyped(self, e):
                pass

            def keyReleased(self, e):
                if e.getKeyCode() == e.VK_DOWN:
                    Utils.consoleController.nextCommand()
                    Utils.out("released down")
                if e.getKeyCode() == e.VK_UP:
                    Utils.consoleController.previousCommand()
                    Utils.out("released up")

                if e.getKeyCode() == e.VK_TAB:
                    Utils.out("pressed tab")
                    Utils.consoleController.tabComplete()

            def keyPressed(self, e):
                pass
예제 #56
0
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, ComponentListener,
                   ActionListener, MouseAdapter):
    # contains the messages to show in the messages table
    _table_data = []

    # contains the messages to translate
    _messages = []

    # used to keep track when to refresh the table
    _reload_table = False

    _sql_file = None

    def registerExtenderCallbacks(self, callbacks):

        self._panel = JPanel()
        self._panel.setLayout(BorderLayout())
        #self._panel.setSize(400,400)

        # sourrounding try\except because Burp is not giving enough info
        try:

            # creating all the UI elements
            # create the split pane
            self._split_pane_horizontal = JSplitPane(
                JSplitPane.HORIZONTAL_SPLIT)
            self._split_panel_vertical = JSplitPane(JSplitPane.VERTICAL_SPLIT)

            # create panels
            self._panel_top = JPanel()
            self._panel_top.setLayout(BorderLayout())
            self._panel_bottom = JPanel()
            self._panel_bottom.setLayout(BorderLayout())
            self._panel_right = JPanel()
            self._panel_right.setLayout(BorderLayout())
            self._panel_request = JPanel()
            self._panel_request.setLayout(BorderLayout())
            self._panel_response = JPanel()
            self._panel_response.setLayout(BorderLayout())

            # create the tabbed pane used to show request\response
            self._tabbed_pane = JTabbedPane(JTabbedPane.TOP)

            # create the tabbed pane used to show aslan++\concretization file
            self._tabbed_pane_editor = JTabbedPane(JTabbedPane.TOP)

            # create the bottom command for selecting the SQL file and
            # generating the model
            self._button_generate = JButton(
                'Generate!', actionPerformed=self._generate_model)
            self._button_save = JButton('Save',
                                        actionPerformed=self._save_model)
            self._button_select_sql = JButton(
                'Select SQL', actionPerformed=self._select_sql_file)
            self._text_field_sql_file = JTextField(20)

            self._panel_bottom_commands = JPanel()
            layout = GroupLayout(self._panel_bottom_commands)
            layout.setAutoCreateGaps(True)
            layout.setAutoCreateContainerGaps(True)
            seq_layout = layout.createSequentialGroup()
            seq_layout.addComponent(self._text_field_sql_file)
            seq_layout.addComponent(self._button_select_sql)
            seq_layout.addComponent(self._button_generate)
            seq_layout.addComponent(self._button_save)
            layout.setHorizontalGroup(seq_layout)

            # create the message editors that will be used to show request and response
            self._message_editor_request = callbacks.createMessageEditor(
                None, True)
            self._message_editor_response = callbacks.createMessageEditor(
                None, True)

            # create the table that will be used to show the messages selected for
            # the translation

            self._columns_names = ('Host', 'Method', 'URL')
            dataModel = NonEditableModel(self._table_data, self._columns_names)
            self._table = JTable(dataModel)
            self._scrollPane = JScrollPane()
            self._scrollPane.getViewport().setView((self._table))

            popmenu = JPopupMenu()
            delete_item = JMenuItem("Delete")
            delete_item.addActionListener(self)
            popmenu.add(delete_item)
            self._table.setComponentPopupMenu(popmenu)
            self._table.addMouseListener(self)

            # add all the elements
            self._panel_request.add(
                self._message_editor_request.getComponent())
            self._panel_response.add(
                self._message_editor_response.getComponent())

            self._tabbed_pane.addTab("Request", self._panel_request)
            self._tabbed_pane.addTab("Response", self._panel_response)

            self._panel_top.add(self._scrollPane, BorderLayout.CENTER)

            self._panel_bottom.add(self._tabbed_pane, BorderLayout.CENTER)
            scroll = JScrollPane(self._panel_bottom)

            self._panel_right.add(self._tabbed_pane_editor,
                                  BorderLayout.CENTER)
            self._panel_right.add(self._panel_bottom_commands,
                                  BorderLayout.PAGE_END)

            self._split_panel_vertical.setTopComponent(self._panel_top)
            self._split_panel_vertical.setBottomComponent(scroll)
            self._split_pane_horizontal.setLeftComponent(
                self._split_panel_vertical)
            self._split_pane_horizontal.setRightComponent(self._panel_right)

            self._panel.addComponentListener(self)
            self._panel.add(self._split_pane_horizontal)

            self._callbacks = callbacks
            callbacks.setExtensionName("WAFEx")
            callbacks.addSuiteTab(self)
            callbacks.registerContextMenuFactory(self)
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)

    def getTabCaption(self):
        return "WAFEx"

    def getUiComponent(self):
        try:
            Platform.runLater(EditorTabUI(self))
            return self._panel
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)

    def componentShown(self, e):
        self._split_pane_horizontal.setDividerLocation(0.25)
        # populate the table with the selected requests\response
        try:
            if self._reload_table:
                print("reload")
                self._table_data = [
                ]  # empty _table_data (not too cool but quick)
                for c in self._messages:
                    msg = c[0]
                    http_request = converter._byte_array_to_string(
                        msg.getRequest())
                    request_parser = HttpParser()
                    request_parser.execute(http_request, len(http_request))

                    host = msg.getHttpService().getHost()
                    page = request_parser.get_url()
                    method = request_parser.get_method()

                    tmp = [host, method, page]
                    self._table_data += [tmp]
                self._table.getModel().setDataVector(self._table_data,
                                                     self._columns_names)
                self._reload_table = False
        except Exception as e:
            print(e)

    def componentHidden(self, e):
        return

    def componentMoved(self, e):
        return

    def componentResized(self, e):
        self._split_pane_horizontal.setDividerLocation(0.25)

    def createMenuItems(self, invocation):
        ret = []
        try:
            if (invocation.getInvocationContext() ==
                    invocation.CONTEXT_TARGET_SITE_MAP_TABLE):
                menu = JMenuItem("Send to WAFEx")
                messages = invocation.getSelectedMessages()

                def listener(e):
                    """ Generates a new WAFEx model. """
                    #self._generateWAFExModel(messages)
                    self._addToGeneration(messages)

                menu.addActionListener(listener)
                ret.append(menu)
        except Exception as e:
            print(e)
        return ret

    def mouseClicked(self, e):
        """ Positions the Aslan++ editor to the selected request position. """
        try:
            index = self._table.getSelectedRow()
            c = self._messages[index]
            print(len(c))
            message = c[0]
            tag = c[1]
            self._message_editor_request.setMessage(message.getRequest(), True)
            self._message_editor_response.setMessage(message.getResponse(),
                                                     False)
            if tag != None:
                document = self._jfxp_aslanpp._editor.getText()
                start, end = self._search_tag_position(tag, document)
                self._jfxp_aslanpp._editor.moveTo(start)
                self._jfxp_aslanpp._editor.selectRange(start, end)
                self._jfxp_aslanpp._editor.requestFollowCaret()
                self._jfxp_aslanpp._editor.requestFocus()
        except Exception as e:
            print(e)

    def actionPerformed(self, e):
        """ Performs the delete action. """
        try:
            index = self._table.getSelectedRow()
            del self._table_data[index]
            del self._messages[index]
            self._table.getModel().setDataVector(self._table_data,
                                                 self._columns_names)
        except Exception as e:
            print(e)

    def _search_tag_position(self, tag, text):
        """ Searches for a particular tag in a given text and return its position. """
        pattern = self._search_pattern.format(tag)
        for m in re.finditer(pattern, text):
            return m.start(), m.end()

    def _save_model(self, e):
        """ Saves the current Aslan++ model and concretization file. """
        try:
            chooseFile = JFileChooser()
            filter_ = FileNameExtensionFilter("txt files", ["txt"])
            chooseFile.addChoosableFileFilter(filter_)

            ret = chooseFile.showDialog(self._panel, "Choose file")

            if ret == JFileChooser.APPROVE_OPTION:
                self._model_name = chooseFile.getSelectedFile().getPath()
                with open("{}.aslan++".format(self._model_name), "w") as f:
                    skeleton = self._jfxp_aslanpp._editor.getText()
                    skeleton = skeleton.replace("@filename",
                                                basename(self._model_name))
                    f.write(skeleton)
                print("model created")

                with open("{}.txt".format(self._model_name), "w") as f:
                    f.write(self._jfxp_concretization._editor.getText())

        except Exception as e:
            print(e)

    def _select_sql_file(self, e):
        """ Shows a JFileChooser dialog to select the SQL file to use for creating
        the model. """
        try:
            chooseFile = JFileChooser()
            filter_ = FileNameExtensionFilter("txt files", ["txt"])
            chooseFile.addChoosableFileFilter(filter_)

            ret = chooseFile.showDialog(self._panel, "Choose file")

            if ret == JFileChooser.APPROVE_OPTION:
                self._sql_file = chooseFile.getSelectedFile().getPath()
            else:
                self._sql_file = None
            self._text_field_sql_file.setText("" + self._sql_file)
        except Exception as e:
            print(e)

    def _addToGeneration(self, messages):
        for msg in messages:
            self._messages += [[msg, None]]
        self._reload_table = True

    def _generate_model(self, e):
        if len(self._messages) <= 0:
            frame = JFrame("Error")
            JOptionPane.showMessageDialog(frame, "No messages!", "Error",
                                          JOptionPane.ERROR_MESSAGE)
            return
        if self._sql_file == None:
            frame = JFrame("Error")
            replay = JOptionPane.showConfirmDialog(
                frame, "No SQL file selected!\nDo you want to continue?",
                "Info", JOptionPane.YES_NO_OPTION)
            if replay == JOptionPane.NO_OPTION:
                return

        # create a new AslanppModel
        model = AslanppModel()
        # save _sql_file
        model._sql_file = self._sql_file

        for c in self._messages:
            # from byte to char Request and Response
            # for some reason b can be a negative value causing a crash
            # so I put a check to ensure b is in the right range
            msg = c[0]
            if msg.getRequest() == None or msg.getResponse() == None:
                # do not convert empty messages
                continue
            http_request = "".join(
                chr(b) for b in msg.getRequest() if b >= 0 and b <= 256)
            http_response = "".join(
                chr(b) for b in msg.getResponse() if b >= 0 and b <= 256)
            protocol = msg.getHttpService().getProtocol()
            # save the tag number generate by _parseHttpRequestResponse in the _messages array
            c[1] = converter._parseHttpRequestResponse(model, http_request,
                                                       http_response, protocol)

        # generate the ASLan++ code
        self._model, self._concrete = converter._generateWAFExModel(model)
        Platform.runLater(
            UpdateEditor(self._jfxp_aslanpp._editor,
                         self._jfxp_concretization._editor, self._model,
                         self._concrete))
예제 #57
0
class GroupConversationWindow(GroupConversation):
    """A GUI window of a conversation witha  group of people"""
    def __init__(self, group, chatui):
        GroupConversation.__init__(self, group, chatui)
        self.mainframe = JFrame(self.group.name)
        self.headers = ["Member"]
        self.memberdata = UneditableTableModel([], self.headers)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def showGroupMessage(self, sender, text, metadata=None):
        self.displayText(sender + ": " + text)

    def setGroupMembers(self, members):
        GroupConversation.setGroupMembers(self, members)
        self.updatelist()

    def setTopic(self, topic, author):
        topictext = "Topic: " + topic + ", set by " + author
        self.mainframe.setTitle(self.group.name + ": " + topictext)
        self.displayText(topictext)

    def memberJoined(self, member):
        GroupConversation.memberJoined(self, member)
        self.updatelist()

    def memberChangedNick(self, oldnick, newnick):
        GroupConversation.memberChangedNick(self, oldnick, newnick)
        self.updatelist()

    def memberLeft(self, member):
        GroupConversation.memberLeft(self, member)
        self.updatelist()

    #GUI code
    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        memberpane = JTable(self.memberdata)
        memberframe = JScrollPane(memberpane)

        chat = JPanel(doublebuffered)
        chat.setLayout(BoxLayout(chat, BoxLayout.Y_AXIS))
        chat.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        chat.add(self.typepad)
        chat.add(buttons)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.X_AXIS))
        mainpane.add(chat)
        mainpane.add(memberframe)

    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    def updatelist(self):
        self.memberdata.setDataVector([self.members], self.headers)

    #actionListener
    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            GroupConversation.sendText(self, text)

    def hidewindow(self, ae):
        self.hide()