예제 #1
0
class DialogDemo(JDialog):
    def __init__(self,table):

        self.setTitle("Add Proxy")
        self.setSize(200,100)
        self.setVisible(True)
        self.table = table
        #self.getContentPane().add(about,BorderLayout.CENTER)

        boxHorizontal = Box.createHorizontalBox()
        boxVertical = Box.createVerticalBox()
        boxHorizontal.add(JLabel("IP:"))
        self.jIpText = JTextField(20)
        boxHorizontal.add(self.jIpText)
        boxVertical.add(boxHorizontal)

        boxHorizontal = Box.createHorizontalBox()
        boxHorizontal.add(JLabel("PROT:"))
        self.jPortText = JTextField(20)
        boxHorizontal.add(self.jPortText)
        boxVertical.add(boxHorizontal)

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

        self.getContentPane().add(boxVertical,BorderLayout.CENTER)
    def addIP(self,button):
        TableModel = self.table.getModel()
        TableModel.addRow([self.jIpText.getText(),self.jPortText.getText()])
예제 #2
0
class win(JFrame):
    def __init__(self, title="Consumo Electrico"):
        JFrame(title)
        self.setLayout(None)
        self.setBounds(10, 10, 300, 180)
        self.show()
        self.build()

    def build(self):
        self.label = JLabel("Cup")
        self.label.setBounds(120, 10, 45, 15)
        self.label2 = JLabel("KWh")
        self.label2.setBounds(20, 10, 45, 15)
        self.label3 = JLabel()
        self.label3.setBounds(120, 30, 55, 15)
        self.textfield = JTextField()
        self.textfield.setBounds(15, 30, 75, 20)
        self.textfield.addActionListener(lambda x: self.label3.setText(
            str(calculate(self.textfield.getText()))))
        button = JButton("Calcular")
        button.setBounds(10, 55, 290, 35)
        button.addActionListener(lambda x: self.label3.setText(
            str(calculate(self.textfield.getText()))))

        for var in [
                self.label, self.label2, self.label3, self.textfield, button
        ]:
            self.add(var)
예제 #3
0
class DialogDemo(JDialog):
    def __init__(self, table):

        self.setTitle("Add Proxy")
        self.setSize(200, 100)
        self.setVisible(True)
        self.table = table
        #self.getContentPane().add(about,BorderLayout.CENTER)

        boxHorizontal = Box.createHorizontalBox()
        boxVertical = Box.createVerticalBox()
        boxHorizontal.add(JLabel("IP:"))
        self.jIpText = JTextField(20)
        boxHorizontal.add(self.jIpText)
        boxVertical.add(boxHorizontal)

        boxHorizontal = Box.createHorizontalBox()
        boxHorizontal.add(JLabel("PROT:"))
        self.jPortText = JTextField(20)
        boxHorizontal.add(self.jPortText)
        boxVertical.add(boxHorizontal)

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

        self.getContentPane().add(boxVertical, BorderLayout.CENTER)

    def addIP(self, button):
        TableModel = self.table.getModel()
        TableModel.addRow([self.jIpText.getText(), self.jPortText.getText()])
예제 #4
0
 class SetKey(JDialog):
     def __init__(self, button=None):
         super(ConfigPanel.SetKey, self).__init__()
         self.setTitle('Enter version label')
         self.setModal(True)
         if button is None:
             self.button = JButton()
         else:
             self.button = button
         self.initUI()
         
     def initUI(self):
         self.JP = JPanel()
         self.JL = JLabel('Set version label: enter to validate')
         self.JP.add(self.JL)
         self.JTF = JTextField(self.button.getText(), 10)
         self.JTF.actionPerformed = self.doit
         self.JP.add(self.JTF)
         self.add(self.JP)
         self.pack()
         self.setLocation(150,150)
         self.setVisible(True)
         
     def doit(self,event):
         key = self.JTF.getText()
         self.button.setText(self.JTF.getText())
         self.dispose()
예제 #5
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
예제 #6
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
예제 #7
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
예제 #8
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
예제 #9
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())
        ))
예제 #10
0
class EditSymbolAttr(JPanel):
    def __init__(self, sattr):
	self.attr = sattr
	self.cbox = JColorChooser(self.attr.color)
	self.sz_field = JTextField(str(self.attr.size))
	szpanel = JPanel()
	szpanel.add(self.sz_field)
	szpanel.setBorder(BorderFactory.createTitledBorder("symbol size (integer)"))
	self.filled_box = JCheckBox("Filled ?:",self.attr.filled)
	self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
	self.shape_cbox.setSelectedItem(self.attr.shape)
	self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
	panel1 = JPanel()
	panel1.setLayout(BorderLayout())
	panel1.add(szpanel,BorderLayout.NORTH)
	panel2 = JPanel()
	panel2.setLayout(GridLayout(1,2))
	panel2.add(self.shape_cbox)
	panel2.add(self.filled_box)
	panel1.add(panel2,BorderLayout.SOUTH)
	self.setLayout(BorderLayout())
	self.add(self.cbox,BorderLayout.CENTER)
	self.add(panel1,BorderLayout.SOUTH)
    def setAttribute(self,sattr):
	self.attr = sattr
	self.cbox.color = self.attr.color
	self.sz_field.text = str(self.attr.size)
	self.shape_cbox.setSelectedItem(self.attr.shape)
    def update(self):
	self.attr.color = self.cbox.getColor()
	self.attr.size = string.atoi(self.sz_field.getText())
	self.attr.filled = self.filled_box.isSelected()
	self.attr.shape = self.shape_cbox.getSelectedItem()
	self.attr.sym = self.attr.createSymbol()
예제 #11
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)
예제 #12
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)
예제 #13
0
class DeregisterForm(JPanel):
    def __init__(self):
        self.vehicleLabel = JLabel('Vehicle No : ')
        self.vehicleField = JTextField(10)
        self.deregisterBtn = JButton('De-Register',
                                     actionPerformed=self.deRegister)
        self.inintComponents()

    def inintComponents(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.vehicleLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.vehicleField, 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.deregisterBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('De-Register Vehicle')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))

    def deRegister(self, e):
        lplate = self.vehicleField.getText()

        if isFieldsEmpty([lplate]):
            dialog.improperInput('One or more fields are missing!', 'No Input')
        else:
            lplate = rut.removeSpace(lplate)
            client.deregister_vehicle(lplate)
예제 #14
0
   def initUI(self):

       global outputTextField
       self.panel = JPanel()
       self.panel.setLayout(BorderLayout())

       toolbar = JToolBar()
       openb = JButton("Choose input file", actionPerformed=self.onClick)
       outputLabel = JLabel("   Enter output file name:  ")
       outputTextField = JTextField("hl7OutputReport.txt", 5)
       print outputTextField.getText()


     


       toolbar.add(openb)
       toolbar.add(outputLabel)
       toolbar.add(outputTextField)
      

       self.area = JTextArea()
       self.area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.area.setText("Select your HL7 ORU messages text file to be converted to tab-delimited flat \nfile with select HL7 fields.\n")
       self.area.append("You can enter the path + file name for your output file or it will default to the current \nfile name in the text field above in your current working directory.")

       pane = JScrollPane()
       pane.getViewport().add(self.area)

       self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.panel.add(pane)
       self.add(self.panel)

       self.add(toolbar, BorderLayout.NORTH)


       self.setTitle("HL7 ORU Results Reporter")
       self.setSize(600, 300)
       self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
       self.setLocationRelativeTo(None)
       self.setVisible(True)
       return outputTextField.getText()
예제 #15
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() )
예제 #16
0
파일: sti.py 프로젝트: bradh/IDV
def loadStiData(idv):
	hostField = JTextField('',30);
	userField = JTextField('',30);
	passwordField = JPasswordField('',30);
	comps = ArrayList();
	comps.add(JLabel("Database Host:"));
	comps.add(GuiUtils.inset(hostField,4));
	comps.add(JLabel("User Name:"));
	comps.add(GuiUtils.inset(userField,5));
	comps.add(JLabel("Password:"));
	comps.add(GuiUtils.inset(passwordField,5));
	contents = GuiUtils.doLayout(comps, 2,GuiUtils.WT_N, GuiUtils.WT_N);	
	contents =GuiUtils.inset(contents,5);
	ok = GuiUtils.showOkCancelDialog(None,'foo',	contents, None);
	if(ok==0):
		return;
	url = 'jdbc:mysql://' + hostField.getText() +':3306/typhoon?zeroDateTimeBehavior=convertToNull&user='******'&password='******'DB.STORMTRACK', None);
예제 #17
0
class SwingLoginDialog(JDialog):
    
    def __init__(self):
        self.username=""
        self.password=""
        self.okPressed=False
        self.userField=JTextField(15)
        self.passField=JPasswordField(15)
        
        self.setTitle("Login")
        self.setModal(True)
        self.setAlwaysOnTop(True)
        self.setLocationRelativeTo(None)
        pane = self.getContentPane()
        pane.setLayout(GridLayout(4,2))
        pane.add(JLabel("Username:"******"Password:"******"OK", actionPerformed=self.okClick)
        pane.add(okButton)
        cancelButton=JButton("Cancel", actionPerformed=self.cancelClick)
        pane.add(cancelButton)
        self.pack() 
        
    def okClick(self, e):
        self.okPressed=True
        self.username=self.userField.getText()
        self.password=str(String(self.passField.getPassword()))
        self.setVisible(False)
    
    def cancelClick(self, e):
        self.okPressed=False
        self.setVisible(False)
        
        
    def getLoginInfo(self):
        if self.okPressed:            
            return [self.username, self.password]
        return None
예제 #18
0
    def changeDomainPopup(self, oldDomain, index):
        hostField = JTextField(25)
        checkbox = JCheckBox()
        domainPanel = JPanel(GridLayout(0,1))
        domainPanel.add(JLabel("Request %s: Domain %s inaccessible. Enter new domain." % (str(index),oldDomain)))

        firstline = JPanel()
        firstline.add(JLabel("Host:"))
        firstline.add(hostField)
        domainPanel.add(firstline)
        secondline = JPanel()
        secondline.add(JLabel("Replace domain for all requests?"))
        secondline.add(checkbox)
        domainPanel.add(secondline)
        result = JOptionPane.showConfirmDialog(
            self._splitpane,domainPanel, "Domain Inaccessible", JOptionPane.OK_CANCEL_OPTION)
        cancelled = (result == JOptionPane.CANCEL_OPTION)
        if cancelled:
            return (False, None, False)
        return (True, hostField.getText(), checkbox.isSelected())
예제 #19
0
파일: gui.py 프로젝트: thecesrom/incendium
def input(message, title="Input"):
    """Open 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. This will be translated
            to the selected Locale. Will accept html formatting.
        title (str): A title for the input box. This will be translated
            to the selected Locale. Optional.

    Returns:
        str: The string value that was entered in the input box.
    """
    options = [
        system.util.translate(constants.OK_TEXT),
        system.util.translate(constants.CANCEL_TEXT),
    ]

    panel = JPanel()
    label = JLabel("{}: ".format(system.util.translate(message)))
    panel.add(label)
    text_field = JTextField(25)
    panel.add(text_field)

    choice = JOptionPane.showOptionDialog(
        None,
        panel,
        system.util.translate(title),
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.PLAIN_MESSAGE,
        None,
        options,
        options[0],
    )

    return text_field.getText() if choice == JOptionPane.OK_OPTION else None
class SwingLoginDialog(JDialog):
    def __init__(self):
        self.username = ""
        self.password = ""
        self.okPressed = False
        self.userField = JTextField(15)
        self.passField = JPasswordField(15)

        self.setTitle("Login")
        self.setModal(True)
        self.setAlwaysOnTop(True)
        self.setLocationRelativeTo(None)
        pane = self.getContentPane()
        pane.setLayout(GridLayout(4, 2))
        pane.add(JLabel("Username:"******"Password:"******"OK", actionPerformed=self.okClick)
        pane.add(okButton)
        cancelButton = JButton("Cancel", actionPerformed=self.cancelClick)
        pane.add(cancelButton)
        self.pack()

    def okClick(self, e):
        self.okPressed = True
        self.username = self.userField.getText()
        self.password = str(String(self.passField.getPassword()))
        self.setVisible(False)

    def cancelClick(self, e):
        self.okPressed = False
        self.setVisible(False)

    def getLoginInfo(self):
        if self.okPressed:
            return [self.username, self.password]
        return None
예제 #21
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
예제 #22
0
class EditSymbolAttr(JPanel):
    def __init__(self, sattr):
        self.attr = sattr
        self.cbox = JColorChooser(self.attr.color)
        self.sz_field = JTextField(str(self.attr.size))
        szpanel = JPanel()
        szpanel.add(self.sz_field)
        szpanel.setBorder(
            BorderFactory.createTitledBorder("symbol size (integer)"))
        self.filled_box = JCheckBox("Filled ?:", self.attr.filled)
        self.shape_cbox = JComboBox(SymbolProps.sym_shape_map.keys())
        self.shape_cbox.setSelectedItem(self.attr.shape)
        self.shape_cbox.setBorder(BorderFactory.createTitledBorder("Shape"))
        panel1 = JPanel()
        panel1.setLayout(BorderLayout())
        panel1.add(szpanel, BorderLayout.NORTH)
        panel2 = JPanel()
        panel2.setLayout(GridLayout(1, 2))
        panel2.add(self.shape_cbox)
        panel2.add(self.filled_box)
        panel1.add(panel2, BorderLayout.SOUTH)
        self.setLayout(BorderLayout())
        self.add(self.cbox, BorderLayout.CENTER)
        self.add(panel1, BorderLayout.SOUTH)

    def setAttribute(self, sattr):
        self.attr = sattr
        self.cbox.color = self.attr.color
        self.sz_field.text = str(self.attr.size)
        self.shape_cbox.setSelectedItem(self.attr.shape)

    def update(self):
        self.attr.color = self.cbox.getColor()
        self.attr.size = string.atoi(self.sz_field.getText())
        self.attr.filled = self.filled_box.isSelected()
        self.attr.shape = self.shape_cbox.getSelectedItem()
        self.attr.sym = self.attr.createSymbol()
예제 #23
0
class portEditor(DefaultCellEditor):

    #---------------------------------------------------------------------------
    # Name: __init__()
    # Role: Constructor - invoke the DefaultTableModel constructor
    #---------------------------------------------------------------------------
    def __init__(self):
        self.textfield = JTextField(horizontalAlignment=JTextField.RIGHT)
        DefaultCellEditor.__init__(self, self.textfield)

    #---------------------------------------------------------------------------
    # Name: stopCellEditing()
    # Role: Verify user input
    #---------------------------------------------------------------------------
    def stopCellEditing(self):
        try:
            val = Integer.valueOf(self.textfield.getText())
            if not (-1 < val < 65536):
                raise NumberFormatException()
            result = DefaultCellEditor.stopCellEditing(self)
        except:
            self.textfield.setBorder(LineBorder(Color.red))
            result = 0  # false
        return result
예제 #24
0
class AddAdminForm(JPanel):
    def __init__(self):
        self.nameLabel = JLabel('Name : ')
        self.nameField = JTextField(10)
        self.mobLabel = JLabel('Mob : ')
        self.mobField = JTextField(10)
        self.emailLabel = JLabel('Email : ')
        self.emailField = JTextField(10)
        self.userNameLabel = JLabel('Username : '******'Password : '******'Confirm Password : '******'Super Password : '******'Add', actionPerformed=self.addAdminToDb)
        self.setPreferredSize(Dimension(400, CENTER_Y))
        self.initComponents()

    def initComponents(self):

        #set the layout and add form components
        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.userNameLabel, 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.userNameField, 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.passwordLabel, 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.passwordField, 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.confirmPasswordLabel, 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.confirmPasswordField, 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.superPassLabel, 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.superPassField, 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.addAdminBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Add Admin')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))

    def addAdminToDb(self, e):
        # print 'yolo'
        name = self.nameField.getText()
        mob = self.mobField.getText()
        email = self.emailField.getText()
        username = self.userNameField.getText()
        password = self.passwordField.getText()
        confirmPassword = self.confirmPasswordField.getText()
        supePassword = self.superPassField.getText()

        fields = [
            name, mob, email, username, password, confirmPassword, supePassword
        ]

        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')
        elif confirmPassword != password:
            dialog.improperInput('Password and Confirm Password missmatch!',
                                 'Mismatch Password')
        else:
            values = [name, mob, email, username, password, supePassword]
            client.add_admin(values)
예제 #25
0
class initDialog(JDialog): # JFrame
    
    def __init__(self, pP):
        # fields
        self.tPath = ""
        self.cPath = ""
        self.exPath = ""
        self.picPicker = pP
        self.annotationType = self.picPicker.getAnnotationType()
    
        super(initDialog, self).__init__()
        
        self.initUI()


    def initUI(self):
        
        inputPanel = JPanel()
        inputPanel.setBorder(BorderFactory.createTitledBorder("Where are your control and treament images?"))
        inputLayout = GroupLayout(inputPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        inputPanel.setLayout(inputLayout)
        
        annotatePanel = JPanel()
        annotatePanel.setBorder(BorderFactory.createTitledBorder("How do you want to annotate your data?"))
        anLayout = GroupLayout(annotatePanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        annotatePanel.setLayout(anLayout)
        
        exportPanel = JPanel()
        exportPanel.setBorder(BorderFactory.createTitledBorder("Where do you want to export your data"))
        exportLayout = GroupLayout(exportPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        exportPanel.setLayout(exportLayout)
        
        btnPanel = JPanel()
        btnLayout = GroupLayout(btnPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        btnPanel.setLayout(btnLayout)
        
        layout = GroupLayout(self.getContentPane(), autoCreateContainerGaps=True, autoCreateGaps=True)
        self.getContentPane().setLayout(layout)

        self.setModalityType(ModalityType.APPLICATION_MODAL)
        self.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)# JFrame.EXIT_ON_CLOSE)
        # definition of elements
        # labels
        cPathLabel = JLabel("Control Path:")
        tPathLabel = JLabel("Treatment Path:")
        exPathLabel = JLabel("Save Results in:")
        
        #textfields
        self.cPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        self.tPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        self.exPathField = JTextField("/Users/schiklen/DotData/131118_dummy/131118_2926/cutout/", 16)
        
        #Radiobuttons
        yesNoRButton = JRadioButton("Yes / No / Ignore", selected=True, actionCommand="yesNoIgnore", actionPerformed=self.setAnnotationTypeDialog)
        intRButton = JRadioButton("Integer", actionCommand="int", actionPerformed=self.setAnnotationTypeDialog)
        nRButton = JRadioButton("Number", actionCommand="float", actionPerformed=self.setAnnotationTypeDialog)
        listRButton = JRadioButton("From List...", actionCommand="list", actionPerformed=self.openListDialog)

        self.rBGroup = ButtonGroup()
        self.rBGroup.add(yesNoRButton)
        self.rBGroup.add(intRButton)
        self.rBGroup.add(nRButton)
        self.rBGroup.add(listRButton)
        
        #self.customListButton = JButton("Custom List...", actionPerformed=self.makeCustomList, enabled=0)
        
        #buttons
        cPathButton = JButton("Browse...", actionPerformed=self.browseC) # lambda on fieldvalue
        tPathButton = JButton("Browse...", actionPerformed=self.browseT) # lambda on fieldvalue
        exPathButton = JButton("Browse...", actionPerformed=self.browseE)
        OKButton = JButton("OK", actionPerformed=self.okayEvent)
        CancelButton = JButton("Cancel", actionPerformed=self.cancel)
        
        '''General ContentPane Layout'''
        layout.setHorizontalGroup(layout.createParallelGroup()
                                  .addComponent(inputPanel)
                                  .addComponent(annotatePanel)
                                  .addComponent(exportPanel)
                                  .addComponent(btnPanel)
                                  )
        layout.linkSize(SwingConstants.HORIZONTAL, inputPanel, annotatePanel, exportPanel, btnPanel)
        layout.setVerticalGroup(layout.createSequentialGroup()
                                .addComponent(inputPanel)
                                .addComponent(annotatePanel)
                                .addComponent(exportPanel)
                                .addComponent(btnPanel)
                                )
        
        ''' Input panel Layout '''
        inputLayout.setHorizontalGroup(inputLayout.createSequentialGroup()
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                 .addComponent(cPathLabel)
                                                 .addComponent(tPathLabel))
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                 .addComponent(self.cPathField)
                                                 .addComponent(self.tPathField))
                                       .addGroup(inputLayout.createParallelGroup()
                                                 .addComponent(cPathButton)
                                                 .addComponent(tPathButton))
                                       )
        
        inputLayout.setVerticalGroup(inputLayout.createSequentialGroup()
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                 .addComponent(cPathLabel)
                                                 .addComponent(self.cPathField)
                                                 .addComponent(cPathButton))
                                       .addGroup(inputLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                 .addComponent(tPathLabel)
                                                 .addComponent(self.tPathField)
                                                 .addComponent(tPathButton))
                                     )
        
        '''Annotate panel layout'''
        anLayout.setHorizontalGroup(anLayout.createParallelGroup()
                                    .addComponent(yesNoRButton)
                                    .addComponent(intRButton)
                                    .addComponent(nRButton)
                                    .addComponent(listRButton)
                                    #.addComponent(self.customListButton)
                                    )
        anLayout.setVerticalGroup(anLayout.createSequentialGroup()
                                    .addComponent(yesNoRButton)
                                    .addComponent(intRButton)
                                    .addComponent(nRButton)
                                    .addComponent(listRButton)
                                    #.addComponent(self.customListButton)
                                    )
        
        
        '''Export panel layout'''
        exportLayout.setHorizontalGroup(exportLayout.createSequentialGroup()
                                        .addComponent(exPathLabel)
                                        .addComponent(self.exPathField)
                                        .addComponent(exPathButton))
        exportLayout.setVerticalGroup(exportLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                        .addComponent(exPathLabel)
                                        .addComponent(self.exPathField)
                                        .addComponent(exPathButton))
        
        
        '''Buttons Panel Layout'''
        btnLayout.setHorizontalGroup(btnLayout.createSequentialGroup()
                                     .addComponent(CancelButton)
                                     .addComponent(OKButton)
                                     )
        btnLayout.setVerticalGroup(btnLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                   .addComponent(CancelButton)
                                   .addComponent(OKButton)
                                   )

        self.setTitle("Random Picture Picker")

        self.pack()
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def addDirToList(self, p):
        self.dirPathList.append(p)

    def browseT(self, event):
        self.tPathField.text = DirectoryChooser("Select Treatment Folder").getDirectory()
        
    def browseC(self, event):
        self.cPathField.text = DirectoryChooser("Select Control Folder").getDirectory()

    def browseE(self, event):
        self.exPathField.text = DirectoryChooser("Select Export Folder").getDirectory()
        self.picPicker.setOutputPath(self.exPathField.text)

    def makeCustomList(self):
        ld = listDialog(self)
        ld.startUI()
        
    def cancel(self, event):
        exit(0)

    def okayEvent(self, event):
        inputDict = {self.tPathField.getText():"treatment", self.cPathField.getText():"control"} # this is for later extension
        self.picPicker.setInputPathDict(inputDict)
        self.picPicker.setOutputPath(self.exPathField.getText())
        
        self.dispose()
        
    def getPicPicker(self):
        return self.picPicker

    def setAnnotationTypeDialog(self, event):
        annotype = self.rBGroup.getSelection().getActionCommand()
        if annotype == "int" or "float":
            self.picPicker.setAnnotationType(["text"])
        if annotype == "yesNoIgnore":
            self.picPicker.setAnnotationType(["Yes", "No", "Ignore"])
    
    def openListDialog(self,event):
        self.makeCustomList()
        #self.customListButton.setEnabled(True)
예제 #26
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!')
예제 #27
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())
예제 #28
0
class BurpExtender(IBurpExtender, ITab):

    def registerExtenderCallbacks(self, callbacks):

        self._cb = callbacks
        self._hp = callbacks.getHelpers()

        self._cb.setExtensionName('MiniProgram Decrypto')
        print 'successful!'

        self.mainPanel = JPanel()

        

        self.sessionKey = JLabel("sessionKey:")
        self.sessionKey.setHorizontalAlignment(SwingConstants.LEFT);
        
        self.iv = JLabel("iv:")
        self.tfsessionKey = JTextField(50)
        
        self.tfiv = JTextField(50)
        
        self.textAreaPlaintext = JTextArea(30, 40)
        self.textAreaPlaintext.setLineWrap(True)
        self.textAreaPlaintext2 = JTextArea(30, 40)
        self.textAreaPlaintext2.setLineWrap(True)
        self.DecryptoBtn = JButton('Decrypto >', actionPerformed=self.decrypto_onClick)
        self.CryptoBtn = JButton('< Crypto', actionPerformed=self.encrypto_onClick)
        
        self.mainPanel.add(self.sessionKey)
        self.mainPanel.add(self.tfsessionKey)
        self.mainPanel.add(self.iv)
        self.mainPanel.add(self.tfiv)
        
        self.mainPanel.add(self.textAreaPlaintext)
        self.mainPanel.add(self.CryptoBtn)
        self.mainPanel.add(self.DecryptoBtn)
        

        self.mainPanel.add(self.textAreaPlaintext2)

        self._cb.customizeUiComponent(self.mainPanel)
        self._cb.addSuiteTab(self)

    def decrypto_onClick(self, event):
        self.textAreaPlaintext2.setText("")
        session_key = self.tfsessionKey.getText()
        iv = self.tfiv.getText()
        payload = self.textAreaPlaintext.getText().rstrip()
        
        str = self.decrypto(payload, session_key, iv)
        
        self.textAreaPlaintext2.append(str)

    def encrypto_onClick(self, event):
        self.textAreaPlaintext.setText("")
        session_key = self.tfsessionKey.getText()
        iv = self.tfiv.getText()
        payload = self.textAreaPlaintext2.getText().rstrip()
        
        str = self.encrypto(payload, session_key, iv)
        
        self.textAreaPlaintext.append(String(str))


    def getTabCaption(self):
    	return 'MiniProgram Decrypto'

    def getUiComponent(self):
        return self.mainPanel


    def encrypto(self, payload, key, iv):
		aesKey = SecretKeySpec(base64.b64decode(key), "AES")
		aesIV = IvParameterSpec(base64.b64decode(iv))
		cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
		cipher.init(Cipher.ENCRYPT_MODE, aesKey, aesIV)
		encrypted = cipher.doFinal(payload)
		return Base64.getEncoder().encode(encrypted)


    def decrypto(self, payload, key, iv):
		decoded = base64.b64decode(payload)
		
		aesKey = SecretKeySpec(base64.b64decode(key), "AES")
		
		aesIV = IvParameterSpec(base64.b64decode(iv))
		
		cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC")
		cipher.init(Cipher.DECRYPT_MODE, aesKey, aesIV)
		return String(cipher.doFinal(decoded)) 
예제 #29
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())
예제 #30
0
class JTabbedPaneClass:


    #判断域名返回IP地址
    def getIp(self, domain):
        domain = domain.split(":")[0]
        ipExpression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")
        if ipExpression.match(domain):
            return domain
        elif domainExpression.match(domain):
            myAddr = socket.getaddrinfo(domain,'http')[0][4][0]
            return myAddr
        
        else:
            return "domain error"


    #提取域名或IP信息
    def getDomain1(self, theDomain):
        domain1 = theDomain.split(":")[0]

        return domain1



    def __init__(self):
        

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None);
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"  

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed = self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)                  #激活自动换行功能 
        self.textArea.setWrapStyleWord(True);            # 激活断行不断字功能
                   
        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))            #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)
        



        #第二个Tab用来做子域名查询



        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)                  #激活自动换行功能 
        self.textArea2.setWrapStyleWord(True)           # 激活断行不断字功能
                   


        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed = self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)


        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url','http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
##
 
        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)                  #激活自动换行功能 
        self.textArea3.setWrapStyleWord(True)          # 激活断行不断字功能
        a = 0
        b = 0 
        self.label4 = JLabel(str(a) + "/" + str(b))
#
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed = self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))


#
        tabPane.addTab("Sebsitive File", panel3)
#
        frame.add(tabPane)
        frame.setVisible(True)
    #用来在第一个TAB打印nmap信息  
    def setResult(self,text):
        self.textArea.append(text)

    #用来在第二个TAB打印获得信息
    def setResult2(self,textId, textDomain, textIp):
        text = str(textId) + "----------------" + textDomain + "----------------" + str(textIp) + os.linesep
        self.textArea2.append(text)
        #self.textArea2.append("----------------------------------------" + os.linesep)

    #用来在第三个TAB打印文件扫描的结果
    def setResult3(self, theMess01):

    	self.textArea3.append(theMess01)


    def setLabel(self, a, b):
    	hg = str(a) + "/" + str(b)
    	self.label4.setText(hg)


    #C段扫描的主引擎
    def cNmapScan(self, event):

        self.textArea.setText("")
            #-------------------------------------------------------------------------------
        def ipRange(ipaddr):
            """
            Creates a generator that iterates through all of the IP addresses.
            The range can be specified in multiple formats.
        
                "192.168.1.0-192.168.1.255"    : beginning-end
                "192.168.1.0/24"               : CIDR
                "192.168.1.*"                  : wildcard
            
        
            """
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
               
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
           
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            #-------------------------------------------------------------------------------
            def cidr_iprange(ipaddr, cidrmask):
                """
                Creates a generator that iterated through all of the IP addresses
                in a range given in CIDR notation
                """
                # Get all the binary one's
                mask = (long(2)**long(32-long(cidrmask))) - 1
            
                b = ipaddr_to_binary(ipaddr) 
                e = ipaddr_to_binary(ipaddr) 
                b = long(b & ~mask)
                e = long(e | mask)
            
                while (b <= e):
                    yield binary_to_ipaddr(b)
                    b = b + 1
         
            #-------------------------------------------------------------------------------
            def wildcard_iprange(ipaddr):
                """
                Creates a generator that iterates through all of the IP address
                in a range given with wild card notation
                """
                beginning = [] 
                end = [] 
                
                tmp = ipaddr.split('.')
                for i in tmp:
                    if i == '*':
                        beginning.append("0")
                        end.append("255") 
                    else:
                        beginning.append(i)
                        end.append(i) 
            
                b = beginning[:]
                e = end[:]
                
                while int(b[0]) <= int(e[0]):
                    while int(b[1]) <= int(e[1]):
                        while int(b[2]) <= int(e[2]):
                            while int(b[3]) <= int(e[3]):
                                yield b[0] + '.' + b[1] + '.' + b[2] + '.' + b[3]
                                b[3] = "%d" % (int(b[3]) + 1)
            
                            b[2] = "%d" % (int(b[2]) + 1)
                            b[3] = beginning[3]
            
                        b[1] = "%d" % (int(b[1]) + 1)
                        b[2] = beginning[2]
            
                    b[0] = "%d" % (int(b[0]) + 1)
                    b[1] = beginning[1]       
            
            # Did we get the IP address in the span format? 
            span_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The beginning IP Address
                                     \s*-\s*
                                     (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The end IP Address
                                  ''', re.VERBOSE)
        
            res = span_re.match(ipaddr)
            if res:
                beginning = res.group(1)
                end = res.group(2)
                return span_iprange(beginning, end)
                                         
            # Did we get the IP address in the CIDR format? 
            cidr_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The IP Address
                                     /(\d{1,2})                             # The mask
                                  ''', re.VERBOSE)
        
            res = cidr_re.match(ipaddr)
            if res:
                addr = res.group(1)
                cidrmask = res.group(2)
                return cidr_iprange(addr, cidrmask)
        
            # Did we get the IP address in the wildcard format? 
            wild_re = re.compile(r'''(\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)   # The IP Address
                                  ''', re.VERBOSE)
        
            res = wild_re.match(ipaddr)
            if res:
                return wildcard_iprange(ipaddr)
            return "The ip address given to ipaddr is improperly formatted"


        ipCidr = self.textfield1.getText()

        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")

        if domainExpression.match(ipCidr):
            JOptionPane.showMessageDialog(None, "You must enter IP", "s1riu5", JOptionPane.INFORMATION_MESSAGE)
        

        else:
            ipList = list(ipRange(ipCidr))
            print len(ipList)
            if len(ipList) == 256:
                del ipList[0]
                del ipList[254]
    
            global NMAPPATH

            scan=ScanList(ipList, self, [NMAPPATH,"-Pn", "-sT", "-sV", "--open"])
            scan.start()

    
  

    def subDomain(self, event):
    	print self.textfield2.getText()
        b = subDomainThread(self.textfield2.getText(), self)
        b.start()

        


    def senFileScan(self, event):
        #print "Hello"

        urlListASP = ["/admin.asp"]
        urlListASPX = ["/admin.aspx"]
        urlListJSP = ["/admin.jsp"]
        urlListPHP = ["/admin.php"]
        urlListMDB = ["/admin.mdb"]
        urlListDIR = ["/admin/"]
        

        if self.chkbox1.isSelected():
            
            domainTextObj1 = open("path/ASP.txt", "r")
            for each1 in domainTextObj1.readlines():
                each1 = each1.strip()
                urlListASP.append(each1)
            domainTextObj1.close()

        if self.chkbox2.isSelected():
            domainTextObj2 = open("path/ASPX.txt", "r")
            for each2 in domainTextObj2.readlines():
                each2 = each2.strip()
                urlListASPX.append(each2)
            domainTextObj2.close()
            
        if self.chkbox3.isSelected():
            domainTextObj3 = open("path/JSP.txt", "r")
            for each3 in domainTextObj3.readlines():
                each3 = each3.strip()
                urlListJSP.append(each3)
            domainTextObj3.close()
        if self.chkbox4.isSelected():
            domainTextObj4 = open("path/PHP.txt", "r")
            for each4 in domainTextObj4.readlines():
                each4 = each4.strip()
                urlListPHP.append(each4)
            domainTextObj4.close()
        if self.chkbox5.isSelected():
            domainTextObj5 = open("path/MDB.txt", "r")
            for each5 in domainTextObj5.readlines():
                each5 = each5.strip()
                urlListMDB.append(each5)
            domainTextObj5.close()
        if self.chkbox6.isSelected():
            domainTextObj6 = open("path/DIR.txt", "r")
            for each6 in domainTextObj6.readlines():
                each6 = each6.strip()
                urlListDIR.append(each6)
            domainTextObj6.close()

        app = []
        app = urlListASP + urlListASPX + urlListJSP + urlListPHP + urlListMDB + urlListDIR
        app1 = list(set(app))
        

        theUrlText = self.textfield3.getText()

        


        #if str(theUrlText[0 : 7]) == "http://":
         #   theUrlText = "http://" + theUrlText
        

        print len(app1)
        print len(app)


        #fileObj1 = eachFileScan(theUrlText, app)
        #fileObj1.start()
        ab = numControl(theUrlText, app1, self)
        ab.start()
class BurpExtender(IBurpExtender, IContextMenuFactory):
    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        self.printHeader()

        # Set extension name
        callbacks.setExtensionName("Directory Listing Parser for Burp Suite")

        # Callbacks object
        self._callbacks = callbacks

        # Helpers object
        self._helpers = callbacks.getHelpers()

        # Register a factory for custom context menu items
        callbacks.registerContextMenuFactory(self)

        return

    # Create a menu item if the appropriate section of the UI is selected
    def createMenuItems(self, invocation):
        menu = []

        # Which part of the interface the user selects
        ctx = invocation.getInvocationContext()

        # Message Viewer Req/Res, Site Map Table, and Proxy History will show menu item if selected by the user
        if ctx == 2 or ctx == 3 or  ctx == 4 or ctx == 5 or ctx == 6:
            menu.append(JMenuItem("Import Directory Listing", None, actionPerformed=lambda x, inv=invocation: self.openGUI(inv)))

        return menu if menu else None

    # Create and place GUI components on JFrame
    def openGUI(self, invocation):
        try:
            # Get values from request or response the extension is invoked from and prepopulate GUI values
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0]
            originalHttpService = message.getHttpService()
            self.originalMsgProtocol = originalHttpService.getProtocol()
            self.originalMsgHost = originalHttpService.getHost()
            self.originalMsgPort = originalHttpService.getPort()
        except:
            self.originalMsgProtocol = ''
            self.originalMsgHost = ''
            self.originalMsgPort = ''

        try:
            self.cookies = self._callbacks.getCookieJarContents()
            self.cookie = ''
        except:
            pass

        self.SSL = 'http://'
        self.listType = ''
        self.parsedList = []

        # Set up main window (JFrame)
        self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10)
        self.window.contentPane.setBorder(emptyBorder)
        self.window.contentPane.layout = BorderLayout()

        # Main window title placed at the top of the main window with an invisible bottom border
        titlePanel = JPanel()
        titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0)
        title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER)
        title.setBorder(titleBorder)
        title.setFont(Font("Default", Font.PLAIN, 18))
        titlePanel.add(title)
        self.window.contentPane.add("North", titlePanel)

        # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file
        self.leftPanel = JPanel()
        self.leftPanel.layout = GridLayout(14, 1, 3, 3)
        hostnameLabel = JLabel("Hostname:")

        if self.originalMsgHost:
            self.hostnameTextField = JTextField(self.originalMsgHost.rstrip())
        else:
            self.hostnameTextField = JTextField('Hostname')

        dirPrefixLabel = JLabel("Full Directory Prefix (Windows):")
        self.dirPrefixField = JTextField('C:\\var\www\\')
        
        sslLabel = JLabel("SSL:")
        self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl)
        self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl)
        sslButtonGroup = ButtonGroup()
        sslButtonGroup.add(self.radioBtnSslEnabled)
        sslButtonGroup.add(self.radioBtnSslDisabled)
        
        if self.originalMsgProtocol == "https":
            self.radioBtnSslEnabled.setSelected(True)
        else:
            self.radioBtnSslDisabled.setSelected(True)
        
        portLabel = JLabel("Port:")

        if self.originalMsgPort:
            self.portTextField = JTextField(str(self.originalMsgPort).rstrip())
        else:
            self.portTextField = JTextField('80')

        osLabel = JLabel("Type of File Listing:")
        self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'')
        self.comboListingType = JComboBox(self.types)
        uploadLabel = JLabel("Directory Listing File:")
        self.uploadTextField = JTextField('')
        uploadButton = JButton('Choose File', actionPerformed=self.chooseFile)

        self.leftPanel.add(hostnameLabel)
        self.leftPanel.add(self.hostnameTextField)
        self.leftPanel.add(dirPrefixLabel)
        self.leftPanel.add(self.dirPrefixField)
        self.leftPanel.add(sslLabel)
        self.leftPanel.add(self.radioBtnSslEnabled)
        self.leftPanel.add(self.radioBtnSslDisabled)
        self.leftPanel.add(portLabel)
        self.leftPanel.add(self.portTextField)
        self.leftPanel.add(osLabel)
        self.leftPanel.add(self.comboListingType)
        self.leftPanel.add(uploadLabel)
        self.leftPanel.add(self.uploadTextField)
        self.leftPanel.add(uploadButton)

        # Right panel consisting of a text area for the URL list
        self.UrlPanelLabel = JLabel("URL List:")
        self.textArea = JTextArea()
        self.textArea.setEditable(True)
        self.textArea.setFont(Font("Default", Font.PLAIN, 14))
        if self.cookies:
            self.textArea.append('Cookies Found:\n')
            for cookie in self.cookies:
                if cookie.getDomain() in self.originalMsgHost:
                    self.cookie += cookie.getName() + '=' + cookie.getValue() + '; '
                    self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n')
        scrollArea = JScrollPane(self.textArea)
        scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        scrollArea.setPreferredSize(Dimension(400, 200))
        self.rightPanel = JPanel()
        self.rightPanel.setLayout(BorderLayout(3, 3))
        self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH)
        self.rightPanel.add(scrollArea, BorderLayout.CENTER)
        
        # Panel for the generate URL list and import URL list buttons
        generatePanel = JPanel()
        generatePanel.layout = BorderLayout(3, 3)
        generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList)
        importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport)
        generatePanel.add("North", generateButton)
        generatePanel.add("South", importButton)
        self.rightPanel.add("South", generatePanel)

        # Add the two main panels to the left and right sides
        self.window.contentPane.add("East", self.rightPanel)
        self.window.contentPane.add("West", self.leftPanel)

        # Create a panel to be used for the file chooser window
        self.uploadPanel = JPanel()
        
        self.window.pack()
        self.window.show()

    # JFileChooser and showDialog for the user to specify their directory listing input file
    def chooseFile(self, event):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        chooseFile.addChoosableFileFilter(filter)
        chooseFile.showDialog(self.uploadPanel, "Choose File")
        chosenFile = chooseFile.getSelectedFile()
        self.uploadTextField.text = str(chosenFile)

    # Set whether https is enabled.  Default is disabled (http)
    def radioSsl(self, event):
        if self.radioBtnSslEnabled.isSelected():
            self.SSL = 'https://'
        else:
            self.SSL = 'http://'

    # Create a parser object and pass the user's specified options.  Retrieve the results and print them to a text area
    def generateUrlList(self, event):
        fileListingType = self.comboListingType.selectedIndex
        self.listType = self.types[fileListingType]
        urlsMade = 0
        if os.path.isfile(self.uploadTextField.text):
            parser = ListingParser()
            parser.parse(self.hostnameTextField.getText(), self.dirPrefixField.getText().rstrip(), self.SSL, self.portTextField.getText(), self.listType, self.uploadTextField.getText())
            self.parsedList = parser.returnList()
            self.textArea.setText('')
            for item in self.parsedList:
                self.textArea.append(item + '\n')

            urlsMade = str(len(self.parsedList))
            if self.parsedList and urlsMade:
                self.textArea.append('\n' + 'Total Directories Found: ' + str(parser.directoryCount))
                self.textArea.append('\n' + 'Total URLs Created: ' + urlsMade)
            else:
                self.textArea.append('Error occurred during parsing.\n')
                self.textArea.append('Please make sure the directory listing is a valid format and all input is correct.\n')
                self.textArea.append('E-mail [email protected] with errors or for further help.')
        else:
            JOptionPane.showMessageDialog(None, 'ERROR: File is not valid file or not found!')

    def closeUI(self, event):
        self.window.setVisible(False)
        self.window.dispose()

    # This is initiated by the user selecting the 'import to burp' button.  Checks each generated URL for a valid response and adds it to the site map
    def importList(self):
        if self.parsedList:
            urlsAdded = 0
            # Loop through each URL and check the response.  If the response code is less than 404, add to site map
            for item in self.parsedList:
                # Pass exception if urlopen returns an http error if the URL is not reachable
                try:
                    code = urlopen(item).code
                    if code < 404:
                        javaURL = URL(item)
                        newRequest = self._helpers.buildHttpRequest(javaURL)
                        stringNewRequest = self._helpers.bytesToString(newRequest).rstrip()
                        if self.cookie:
                            stringNewRequest += '\nCookie: ' + self.cookie.rstrip('; ') + '\r\n\r\n'
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), stringNewRequest)
                        else:
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), newRequest)
                        self._callbacks.addToSiteMap(requestResponse)
                        urlsAdded += 1
                except Exception, e:
                    print e
                    pass
            JOptionPane.showMessageDialog(None, str(urlsAdded) + " URL(s) added to Burp site map.")
        else:
예제 #32
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()
예제 #33
0
파일: main.py 프로젝트: pavithra03/neofelis
  def getArguments(self):
    """
    This function brings up a window to retreive any required arguments.  It uses a window with fields for each argument, filled with any arguments already given.
    While this window is visible the program will wait, once it is no longer visible all the arguments will be filled with the entries in the fields.
    """

    class LocationAction(AbstractAction):
      """
      Action to set the text of a text field to a folder or directory.
      """
      def __init__(self, field):
        AbstractAction.__init__(self, "...")
        self.field = field

      def actionPerformed(self, event):
        fileChooser = JFileChooser()
        fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
          self.field.text = fileChooser.selectedFile.absolutePath
    
    class HelpAction(AbstractAction):
      """
      Displays a help page in a web browser.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Help")

      def actionPerformed(self, event):
        browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
        osName = System.getProperty("os.name")
        helpHTML = ClassLoader.getSystemResource("help.html").toString()
        if osName.find("Mac OS") == 0:
          Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
        elif osName.find("Windows") == 0:
          Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
        else:
          browser = None
          for b in browsers:
            if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
              browser = b
              Runtime.getRuntime().exec([browser, helpHTML])

    class OKAction(AbstractAction):
      """
      Action for starting the pipeline.  This action will simply make the window invisible.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Ok")

      def actionPerformed(self, event):
        frame.setVisible(False)

    class CancelAction(AbstractAction):
      """
      Action for canceling the pipeline.  Exits the program.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Cancel")

      def actionPerformed(self, event):
        sys.exit(0)

    frame = JFrame("Neofelis")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    constraints = GridBagConstraints()
    contentPane = JPanel(GridBagLayout())
    frame.setContentPane(contentPane)
    blastField = JTextField(self.blastLocation)
    genemarkField = JTextField(self.genemarkLocation)
    transtermField = JTextField(self.transtermLocation)
    tRNAscanField = JTextField(self.tRNAscanLocation)
    databaseLocationField = JTextField(os.path.split(self.database)[0])
    databaseField = JTextField(os.path.split(self.database)[1])
    matrixField = JTextField(str(self.matrix))
    eValueField = JTextField(str(self.eValue))
    minLengthField = JTextField(str(self.minLength))
    scaffoldingDistanceField = JTextField(str(self.scaffoldingDistance))
    promoterScoreField = JTextField(str(self.promoterScoreCutoff))
    queryField = JTextField(self.sources[0])

    constraints.gridx = 0
    constraints.gridy = 0
    constraints.gridwidth = 1
    constraints.gridheight = 1
    constraints.fill = GridBagConstraints.HORIZONTAL
    constraints.weightx = 0
    constraints.weighty = 0
    contentPane.add(JLabel("Blast Location"), constraints)
    constraints.gridy = 1
    contentPane.add(JLabel("Genemark Location"), constraints)
    constraints.gridy = 2
    contentPane.add(JLabel("Transterm Location"), constraints)
    constraints.gridy = 3
    contentPane.add(JLabel("tRNAscan Location"), constraints)
    constraints.gridy = 4
    contentPane.add(JLabel("Databases Location"), constraints)
    constraints.gridy = 5
    contentPane.add(JLabel("Database"), constraints)
    constraints.gridy = 6
    contentPane.add(JLabel("Matrix(Leave blank to use heuristic matrix)"), constraints)
    constraints.gridy = 7
    contentPane.add(JLabel("E Value"), constraints)
    constraints.gridy = 8
    contentPane.add(JLabel("Minimum Intergenic Length"), constraints)
    constraints.gridy = 9
    contentPane.add(JLabel("Scaffold Distance"), constraints)
    constraints.gridy = 10
    contentPane.add(JLabel("Promoter Score Cutoff"), constraints)
    constraints.gridy = 11
    contentPane.add(JLabel("Query"), constraints)
    constraints.gridx = 1
    constraints.gridy = 0
    constraints.weightx = 1
    contentPane.add(blastField, constraints)
    constraints.gridy = 1
    contentPane.add(genemarkField, constraints)
    constraints.gridy = 2
    contentPane.add(transtermField, constraints)
    constraints.gridy = 3
    contentPane.add(tRNAscanField, constraints)
    constraints.gridy = 4
    contentPane.add(databaseLocationField, constraints)
    constraints.gridy = 5
    contentPane.add(databaseField, constraints)
    constraints.gridy = 6
    contentPane.add(matrixField, constraints)
    constraints.gridy = 7
    contentPane.add(eValueField, constraints)
    constraints.gridy = 8
    contentPane.add(minLengthField, constraints)
    constraints.gridy = 9
    contentPane.add(scaffoldingDistanceField, constraints)
    constraints.gridy = 10
    contentPane.add(promoterScoreField, constraints)
    constraints.gridy = 11
    contentPane.add(queryField, constraints)
    constraints.gridx = 2
    constraints.gridy = 0
    constraints.weightx = 0
    constraints.fill = GridBagConstraints.NONE
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(LocationAction(blastField)), constraints)
    constraints.gridy = 1
    contentPane.add(JButton(LocationAction(genemarkField)), constraints)
    constraints.gridy = 2
    contentPane.add(JButton(LocationAction(transtermField)), constraints)
    constraints.gridy = 3
    contentPane.add(JButton(LocationAction(tRNAscanField)), constraints)
    constraints.gridy = 4
    contentPane.add(JButton(LocationAction(databaseLocationField)), constraints)
    constraints.gridy = 11
    contentPane.add(JButton(LocationAction(queryField)), constraints)

    constraints.gridx = 0
    constraints.gridy = 12
    constraints.anchor = GridBagConstraints.LINE_START
    contentPane.add(JButton(HelpAction()), constraints)
    constraints.gridx = 1
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(OKAction()), constraints)
    constraints.gridx = 2
    contentPane.add(JButton(CancelAction()), constraints)

    frame.pack()
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)

    while frame.isVisible():
      pass

    self.blastLocation = blastField.getText()
    self.genemarkLocation = genemarkField.getText()
    self.transtermLocation = transtermField.getText()
    self.database = databaseLocationField.getText() + "/" + databaseField.getText()
    self.matrix = matrixField.getText()
    self.eValue = float(eValueField.getText())
    self.minLength = int(minLengthField.getText())
    self.scaffoldingDistance = int(scaffoldingDistanceField.getText())
    self.promoterScoreCutoff = float(promoterScoreField.getText())
    self.sources = [queryField.getText()]
예제 #34
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)
예제 #35
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)"
예제 #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 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()
예제 #38
0
class BurpExtender(IBurpExtender, IBurpExtenderCallbacks, IIntruderPayloadProcessor, ITab, IExtensionStateListener):
    def registerExtenderCallbacks( self, callbacks):
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JWT FuzzHelper")
        callbacks.registerIntruderPayloadProcessor(self)
        callbacks.registerExtensionStateListener(self)
        
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # Holds values passed by user from Configuration panel
        self._fuzzoptions = { 
                                "target" : "Header", 
                                "selector" : None, 
                                "signature" : False,
                                "algorithm" : "HS256",
                                "key" : "",
                                "key_cmd" : ""
                            }

        self._isNone = lambda val: isinstance(val, type(None))

        # Configuration panel Layout
        self._configurationPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [ 0, 0, 0]
        gridBagLayout.rowHeights = [ 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
        gridBagLayout.columnWeights = [ 0.0, 0.0, 0.0 ]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
        self._configurationPanel.setLayout(gridBagLayout)

        # Setup tabs
        self._tabs = JTabbedPane()
        self._tabs.addTab('Configuration',self._configurationPanel)
        #self._tabs.addTab('Help',self._helpPanel)

        # Target Options
        targetLabel = JLabel("Target Selection (Required): ")
        targetLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 1
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(targetLabel,c)

        options = [ 'Header', 'Payload' ]
        self._targetComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 1
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._targetComboBox,c)

        # Help Button
        self._helpButton = JButton("Help", actionPerformed=self.helpMenu)
        c = GridBagConstraints()
        c.gridx = 2
        c.gridy = 1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._helpButton,c)

        # Selector Options
        self._selectorLabel = JLabel("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._selectorLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._selectorLabel, c)

        self._selectorTextField = JTextField('',50)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 2
        self._configurationPanel.add(self._selectorTextField, c)

        # Regex option

        self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ")
        self._regexLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 3
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._regexLabel,c)

        self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 3
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._regexCheckBox,c)

        # Signature Options
        generateSignatureLabel = JLabel("Generate signature? (Required): ")
        generateSignatureLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 4
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(generateSignatureLabel,c)

        options = ["False", "True"]
        self._generateSignatureComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 4
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._generateSignatureComboBox,c)

        signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ")
        signatureAlgorithmLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 5
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(signatureAlgorithmLabel,c)

        options = ["None", "HS256","HS384","HS512","ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS256","PS384","PS512"]
        self._algorithmSelectionComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 5
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._algorithmSelectionComboBox,c)

        # Signing key options
        self._signingKeyLabel = JLabel("Signing Key (Optional): ")
        self._signingKeyLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 6
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._signingKeyLabel,c)

        self.addSigningKeyTextArea()
        self._fromFileTextField = JTextField('',50) 

        fromFileLabel = JLabel("Signing key from file? (Optional): ")
        fromFileLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 7
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromFileLabel,c)

        self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 7
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromFileCheckBox,c)

        self._fromCmdTextField = JTextField('',50)

        fromCmdLabel = JLabel("Signing key from command? (Optional): ")
        fromCmdLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 8
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromCmdLabel,c)

        self._fromCmdCheckBox = JCheckBox("", actionPerformed=self.fromCmd)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 8
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromCmdCheckBox,c)

        self._saveButton = JButton("Save Configuration", actionPerformed=self.saveOptions)
        self._saveButton.setText("Save Configuration")
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 9
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._saveButton,c)

        
        callbacks.customizeUiComponent(self._configurationPanel)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.addSuiteTab(self)

        self._stdout.println("[JWT FuzzHelper] Loaded successfully")
        return


    def getProcessorName(self):
        return "JWT Fuzzer"

    def extensionUnloaded(self):
        del self._configurationPanel
        return

    # Intruder logic function
    def processPayload(self, currentPayload, originalPayload, baseValue):
        dataParameter = self._helpers.bytesToString(
                         self._helpers.urlDecode(baseValue)
                       )

        # utf-8 encode
        header,payload,signature = [unicode(s).encode('utf-8') for s in dataParameter.split(".",3)]
        decoded_header = self._helpers.bytesToString(
                            self._helpers.base64Decode(header + "=" * (-len(header) % 4))
                        )
        decoded_payload = self._helpers.bytesToString(
                            self._helpers.base64Decode(payload+"=" * (-len(payload) % 4))
                        )

        # Decode header and payload, preserving order if they are JSON objects

        # Decode header
        try:
            header_dict = json.loads(decoded_header, object_pairs_hook=OrderedDict)
        except ValueError:
            raise RuntimeException("[JWT FuzzHelper] Error: ValueError. Failed to decode header!")
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on...".format(e))

        # Decode payload
        # Payload does not have to be a JSON object.
        #   Ref: https://github.com/auth0/node-jsonwebtoken#usage
        payload_is_string = False
        try:
            payload_dict = json.loads(decoded_payload, object_pairs_hook=OrderedDict)
        except ValueError:
            payload_is_string = True
            payload_dict = decoded_payload
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on...".format(e))

        target = header_dict if self._fuzzoptions["target"] == "Header" else payload_dict
        selector = self._fuzzoptions["selector"]

        # If using Object Identifier-Index then retrieve the 
        # value specified by the selector, 
        # if this value does not exist, assume the user
        # wants to add the value that would have been specified
        # by the selector to the desired JWT segment (this behavior will 
        # be noted in the help docs)

        intruderPayload = self._helpers.bytesToString(currentPayload)
        if not self._fuzzoptions["regex"]:
            if selector != [""]:
                try:
                    value = self.getValue(target, selector)
                except Exception:
                    target = self.buildDict(target, selector)

            if not self._isNone(selector) and selector != [""]:
                target = self.setValue(target, selector, intruderPayload)
        
        # Simple match-replace for regex
        if self._fuzzoptions["regex"]:
            target_string = target if payload_is_string else json.dumps(target)
            target_string = re.sub(selector, intruderPayload, target_string)
            target = target_string if payload_is_string else json.loads(target_string, object_pairs_hook=OrderedDict)
            if self._fuzzoptions["target"] == "Payload":
                payload_dict = target
            else:
                header_dict = target
                

        algorithm = self._fuzzoptions["algorithm"]
        if self._fuzzoptions["signature"]: 
            # pyjwt requires lowercase 'none'. If user wants to try
            # "none", "NonE", "nOnE", etc... they should use .alg
            # as selector, delete sig from intruder and use those
            # permutations as their fuzz list (outlined in help docs)
            # and keep "Generate Signature" as False
            algorithm = "none" if algorithm.lower() == "none" else algorithm
            header_dict["alg"] = algorithm

        header = json.dumps(header_dict, separators=(",",":"))
        payload = payload_dict if payload_is_string else json.dumps(payload_dict, separators=(",",":"))
        header = self._helpers.base64Encode(header).strip("=")
        payload = self._helpers.base64Encode(payload).strip("=")

        contents = header + "." + payload
        
        key = self._fuzzoptions["key"]

        if len(self._fuzzoptions["key_cmd"]) > 0:
            # we provide 'contents' value as an only argument to key-generating command
            # it is expected that the command will print only the signature
            signature = check_output([self._fuzzoptions["key_cmd"], contents])
            modified_jwt = contents + "." + signature
        elif self._fuzzoptions["signature"]:
            # pyjwt throws error when using a public key in symmetric alg (for good reason of course),
            # must do natively to support algorithmic sub attacks
            if algorithm.startswith("HS"):
                if algorithm == "HS256":
                    hmac_algorithm = hashlib.sha256
                elif algorithm == "HS384":
                    hmac_algorithm = hashlib.sha384
                else:
                    hmac_algorithm = hashlib.sha512
            
                signature = self._helpers.base64Encode(
                            hmac.new(
                                    key, contents, hmac_algorithm
                                ).digest()
                    ).strip("=")

                modified_jwt = contents + "." +signature

            # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads.
            elif algorithm.startswith("RS") and payload_is_string:
                if algorithm == "RS256":
                    rsa_algorithm = "SHA-256"
                elif algorithm == "RS384":
                    rsa_algorithm = "SHA-384"
                else:
                    rsa_algorithm = "SHA-512"
                privkey = rsa.PrivateKey.load_pkcs1(key)
                signature = rsa.sign(contents,privkey,rsa_algorithm)
                signature = base64.b64encode(signature).encode('utf-8').replace("=", "")
                modified_jwt = contents + "." + signature
            else:
                # Use pyjwt when using asymmetric alg
                if algorithm == "none":
                    key = ""
                modified_jwt = jwt.encode(payload_dict,key,algorithm=algorithm,headers=header_dict)
        else:
            modified_jwt = contents + "." + signature

        return self._helpers.stringToBytes(modified_jwt)

    
    #-----------------------
    # getValue:
    #   @return: A value at arbitrary depth in dictionary
    #   @throws: TypeError
    #-----------------------
    def getValue(self, dictionary, values):
        return reduce(dict.__getitem__, values, dictionary)

    #-----------------------
    # buildDict:
    #   @note: Will build dictionary of arbitrary depth
    #-----------------------
    def buildDict(self, dictionary, keys):
        if self._isNone(keys):
            return dictionary

        root = current = dictionary
        for key in keys:
            if key not in current:
                current[key] = {}
            current = current[key]
        return root

    #----------------------
    # setValue:
    #   @note: Will set key of arbitrary depth
    #-----------------------
    def setValue(self, dictionary, keys, value):
        root = current = dictionary
        for i,key in enumerate(keys):
            if i == len(keys) - 1:
                current[key] = value
                break
            if key in current:
                current = current[key]
            else:
                # Should never happen
                current = self.buildDict(current, keys)
        return root
    
    #-----------------------
    # addSigningKeyTextArea:
    #   @note: Will toggle if fromFile selected. Be DRY.
    #----------------------
    def addSigningKeyTextArea(self):
        self._signingKeyTextArea = JTextArea()
        self._signingKeyTextArea.setColumns(50)
        self._signingKeyTextArea.setRows(10)
        self._signingKeyScrollPane = JScrollPane(self._signingKeyTextArea)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._signingKeyScrollPane,c)

    def addSigningKeyFromFileTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromFileTextField, c)

    def addSigningKeyFromCmdTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromCmdTextField, c)
    #-----------------------
    # End Helpers
    #-----------------------

    #-----------------------
    # Implement ITab
    #-----------------------

    def getTabCaption(self):
        return "JWT FuzzHelper"

    def getUiComponent(self):
        return self._tabs

    #---------------------------
    # Save configuration options
    #---------------------------

    def saveOptions(self,event):
        self._fuzzoptions["target"]     = self._targetComboBox.getSelectedItem()
        self._fuzzoptions["selector"]   = self._selectorTextField.getText()
        self._fuzzoptions["signature"]  = True if self._generateSignatureComboBox.getSelectedItem() == "True" else False
        self._fuzzoptions["algorithm"]  = self._algorithmSelectionComboBox.getSelectedItem()
        self._fuzzoptions["key_cmd"]    = ""
        
        if self._fromFileCheckBox.isSelected():
            filename = self._fromFileTextField.getText()
            if os.path.isdir(filename):
                self._stderr.println("{} is a directory".format(filename))
                return
            if os.path.exists(filename):
                with open(filename, 'rb') as f:
                    self._fuzzoptions["key"] = f.read()
        elif self._fromCmdCheckBox.isSelected():
            self._fuzzoptions["key_cmd"] = self._fromCmdTextField.getText()
        else:
            self._fuzzoptions["key"]    = unicode(self._signingKeyTextArea.getText()).encode("utf-8")
        # RSA keys need to end with a line break. Many headaches because of this.
        if not self._fuzzoptions["key"].endswith("\n") and self._fuzzoptions["algorithm"].startswith("RS"):
            self._fuzzoptions["key"] += "\n"
        self._stdout.println("[JWT FuzzHelper] Saved options:\n{}".format(self._fuzzoptions))


        # Sanity check selector if it's not a regular expression
        self._fuzzoptions["regex"] = self._regexCheckBox.isSelected()
        if not self._regexCheckBox.isSelected():
            m = re.search("(\.\w+)+",self._fuzzoptions["selector"])
            if self._fuzzoptions["selector"] != "." and (isinstance(m,type(None)) or m.group(0) != self._fuzzoptions["selector"]):
                self._saveButton.setText("Invalid JSON Selector!")
            else:
                self._fuzzoptions["selector"] = self._fuzzoptions["selector"].split(".")[1:]
                self._saveButton.setText("Saved!")
        # Sanity check the regular expression
        else:
            try:
                re.compile(self._fuzzoptions["selector"])
                self._saveButton.setText("Saved!")
            except re.error:
                self._saveButton.setText("Invalid Regex!")
        return

    #-------------------------
    # From file options
    #------------------------
    def fromFile(self,event):
        if self._fromFileCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Key (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromFileTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromFileTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def fromCmd(self,event):
        if self._fromCmdCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Cmd (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromCmdTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromCmdTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def regexSelector(self,event):
        if self._regexCheckBox.isSelected():
            self._selectorLabel.setText("Selector [Regex] (Required): ")
        else:
            self._selectorLabel.setText("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._configurationPanel.repaint()
        return
    #-------------------------
    # Help popup
    #-------------------------
    def helpMenu(self,event):
        self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450) );
        self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        helpPanel = JPanel()
        helpPanel.setPreferredSize(Dimension(550, 450))
        helpPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        self._helpPopup.setContentPane(helpPanel)
        helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>")
        authorText = JLabel("<html><p>@author: &lt;pinnace&gt;</p></html>")
        aboutText = JLabel("<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>")
        repositoryText = JLabel("<html>Documentation and source code:</html>")
        repositoryLink = JLabel("<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>")
        licenseText = JLabel("<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>") 
        dependencyLink = JLabel("<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>")
        dependencyLink.addMouseListener(ClickListener())
        dependencyLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        repositoryLink.addMouseListener(ClickListener())
        repositoryLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        
        helpPanel.add(helpHeadingText)
        helpPanel.add(authorText)
        helpPanel.add(aboutText)
        helpPanel.add(repositoryText)
        helpPanel.add(repositoryLink)
        helpPanel.add(licenseText)
        helpPanel.add(dependencyLink)

        self._helpPopup.setSize(Dimension(550, 450))
        self._helpPopup.pack()
        self._helpPopup.setLocationRelativeTo(None)
        self._helpPopup.setVisible(True)
        return
예제 #39
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))

예제 #40
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))
예제 #41
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
예제 #42
0
파일: FindView.py 프로젝트: oracc/nammu
class FindView(JDialog):
    '''
    Prompt user to choose some options to find and replace text in ATF area.
    '''
    def __init__(self, controller):
        self.logger = logging.getLogger("NammuController")
        self.setAlwaysOnTop(True)
        self.controller = controller
        self.pane = self.getContentPane()

        # Get key bindings configuration from settings
        key_strokes = self.controller.config['find_keystrokes']

        # Configure key bindings for undo/redo
        # First decide when key bindings can be triggered:
        condition = JComponent.WHEN_IN_FOCUSED_WINDOW

        # InputMap maps key strokes to actions in string format (e.g. 'undo')
        # ActionMap maps string actions (e.g. 'undo') with a custom
        # AbstractAction subclass.
        pane = self.getContentPane()
        for action, key in key_strokes.iteritems():
            key_stroke = KeyStroke.getKeyStroke(
                        getattr(KeyEvent, key),
                        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())
            pane.getInputMap(condition).put(key_stroke, action)
            pane.getActionMap().put(action, KeyStrokeAction(self, action))

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

    def build(self):
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        find_panel = self.build_find_row()
        replace_panel = self.build_replace_row()
        options_panel = self.build_options_row()
        buttons_panel = self.build_buttons_row()
        # replace_panel = self.build_find_panel()

        # Add panels to main JFrame
        self.add(find_panel)
        self.add(replace_panel)
        self.add(options_panel)
        self.add(buttons_panel)
        # self.add(self.build_find_replace_rows())

    def build_find_replace_rows(self):
        labels = ("Find: ", "Replace: ")

        # Create and populate the panel.
        panel = JPanel()
        for label in labels:
            row_panel = JPanel(FlowLayout())
            label = JLabel(label, JLabel.TRAILING)
            row_panel.add(label, FlowLayout.LEFT)
            textfield = JTextField(20)
            label.setLabelFor(textfield)
            row_panel.add(textfield, FlowLayout.RIGHT)
            panel.add(row_panel)

        return panel

    def build_find_row(self):
        '''
        Builds the find row.
        '''
        panel = JPanel(FlowLayout())
        label = JLabel("Find:     ")
        panel.add(label)
        self.find_field = JTextField(20, actionPerformed=self.find_next)
        label.setLabelFor(self.find_field)
        panel.add(self.find_field)
        return panel

    def build_replace_row(self):
        '''
        Builds the replace row.
        '''
        panel = JPanel(FlowLayout())
        label = JLabel("Replace: ")
        panel.add(label)
        self.replace_field = JTextField(20, actionPerformed=self.find_next)
        label.setLabelFor(self.replace_field)
        panel.add(self.replace_field)
        return panel

    def build_options_row(self):
        '''
        Builds the panel with ignore case, regex, etc. options.
        '''
        panel = JPanel(FlowLayout())
        self.ignore_case_box = JCheckBox('Ignore Case')
        self.regex_box = JCheckBox('Regular Expression')
        self.selection_box = JCheckBox('Selection only')
        panel.add(self.ignore_case_box)
        panel.add(self.regex_box)
        panel.add(self.selection_box)
        return panel

    def build_buttons_row(self):
        '''
        Builds the buttons row.
        '''
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        find_next_button = JButton('Find Next',
                                   actionPerformed=self.find_next)
        replace_one_button = JButton('Replace',
                                     actionPerformed=self.replace_one)
        replace_all_button = JButton('Replace All',
                                     actionPerformed=self.replace_all)
        done_button = JButton('Done', actionPerformed=self.done)
        panel.add(find_next_button)
        panel.add(replace_one_button)
        panel.add(replace_all_button)
        panel.add(done_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             find_next_button,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             find_next_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             replace_one_button,
                             5,
                             SpringLayout.EAST,
                             find_next_button)
        layout.putConstraint(SpringLayout.NORTH,
                             replace_one_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             replace_all_button,
                             5,
                             SpringLayout.EAST,
                             replace_one_button)
        layout.putConstraint(SpringLayout.NORTH,
                             replace_all_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             done_button,
                             5,
                             SpringLayout.EAST,
                             replace_all_button)
        layout.putConstraint(SpringLayout.NORTH,
                             done_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             done_button)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             done_button)
        # Add this to NewAtf JFrame
        return panel

    def find_next(self, event=None):
        self.controller.find_next(self.find_field.getText(),
                                  self.ignore_case_box.isSelected(),
                                  self.regex_box.isSelected(),
                                  self.selection_box.isSelected())

    def replace_one(self, event=None):
        self.controller.replace_one(self.find_field.getText(),
                                    self.replace_field.getText(),
                                    self.ignore_case_box.isSelected(),
                                    self.regex_box.isSelected(),
                                    self.selection_box.isSelected())

    def replace_all(self, event=None):
        self.controller.replace_all(self.find_field.getText(),
                                    self.replace_field.getText(),
                                    self.ignore_case_box.isSelected(),
                                    self.regex_box.isSelected(),
                                    self.selection_box.isSelected())

    def done(self, event):
        '''
        Reset list of matches and close window.
        '''
        self.controller.matches = None
        self.controller.text = None
        self.controller.controller.find_controller = None
        self.controller.atfAreaController.restore_highlight()
        self.dispose()
예제 #43
0
class InfoFrame(JFrame):
    def __init__(self, title=""):
        JFrame.__init__(self, title)
        self.size = 400,500
        self.windowClosing = self.closing
        
        label = JLabel(text="Class Name:") 
        label.horizontalAlignment = JLabel.RIGHT
        tpanel = JPanel(layout = awt.FlowLayout())
        self.text = JTextField(20, actionPerformed = self.entered)
        btn = JButton("Enter", actionPerformed = self.entered)
        tpanel.add(label)
        tpanel.add(self.text)
        tpanel.add(btn)
    
        bpanel = JPanel()
        self.tree = JTree(default_tree())
        scrollpane = JScrollPane(self.tree)
        scrollpane.setMinimumSize(awt.Dimension(200,200))
        scrollpane.setPreferredSize(awt.Dimension(350,400))
        bpanel.add(scrollpane)
        
        bag = GridBag(self.contentPane)
        bag.addRow(tpanel, fill='HORIZONTAL', weightx=1.0, weighty=0.5)
        bag.addRow(bpanel, fill='BOTH', weightx=0.5, weighty=1.0) 

    def closing(self, event):
        self.hide()
        self.dispose()
        
    def entered(self, event):
        name = self.text.getText()
        try:
            mod = __import__(name)
            components = name.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)            
        except ImportError:
            mod = None
            self.setupTree("Invalid Class", {})
            return None
        edict, pdict, mdict = getBeanInfo(mod)
        pedict = parseEventDict(edict)
        ppdict = parsePropDict(pdict)
        pmdict = parseMethDict(mdict)
        
        self.setupTree(mod.__name__, pedict, ppdict, pmdict)     
          

    def setupTree(self, top, pedict, ppdict, pmdict):
        tree_model = SampleModel(top)
        events = tree_model.addNode("Events",["<<Events of the class and its ancestors>>"])
        props = tree_model.addNode("Properties",["<<Properties of the class and its ancestors>>"])
        meths = tree_model.addNode("Methods",["<<Methods of the class and its ancestors>>"])        
        
        for key in pedict.keys():
            tree_model.addNode(key, pedict[key], parent=events)
        for key in ppdict.keys():
            tree_model.addNode(key, ppdict[key], parent=props)
        for key in pmdict.keys():
            tree_model.addNode(key, pmdict[key], parent=meths)
        
        self.tree.setModel(tree_model)
예제 #44
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
예제 #45
0
파일: NewAtfView.py 프로젝트: oracc/nammu
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

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

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation."
                        )
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             ampersand_label,
                             20,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             ampersand_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_field,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             equals_label,
                             5,
                             SpringLayout.EAST,
                             self.left_field)
        layout.putConstraint(SpringLayout.NORTH,
                             equals_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_field,
                             5,
                             SpringLayout.EAST,
                             equals_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_field)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo,
                                              self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             project_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             project_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             slash_label,
                             5,
                             SpringLayout.EAST,
                             self.left_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             slash_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_combo,
                             5,
                             SpringLayout.EAST,
                             slash_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             language_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             language_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.language_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.language_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.language_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             create_button,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             create_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             leave_button,
                             5,
                             SpringLayout.EAST,
                             create_button)
        layout.putConstraint(SpringLayout.NORTH,
                             leave_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             cancel_button,
                             5,
                             SpringLayout.EAST,
                             leave_button)
        layout.putConstraint(SpringLayout.NORTH,
                             cancel_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
                            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                            project_line,
                            self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols)
                                    )
        self.controller.show_template()
        self.dispose()
예제 #46
0
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

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

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation.")
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, ampersand_label, 20,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_field, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, equals_label, 5,
                             SpringLayout.EAST, self.left_field)
        layout.putConstraint(SpringLayout.NORTH, equals_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_field, 5,
                             SpringLayout.EAST, equals_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_field)
        layout.putConstraint(SpringLayout.NORTH, help_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo, self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, project_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, project_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, slash_label, 5,
                             SpringLayout.EAST, self.left_combo)
        layout.putConstraint(SpringLayout.NORTH, slash_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_combo, 5,
                             SpringLayout.EAST, slash_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, language_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, language_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.language_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.language_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, create_button, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, create_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, leave_button, 5,
                             SpringLayout.EAST, create_button)
        layout.putConstraint(SpringLayout.NORTH, leave_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, cancel_button, 5,
                             SpringLayout.EAST, leave_button)
        layout.putConstraint(SpringLayout.NORTH, cancel_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                project_line,
                self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols))
        self.controller.show_template()
        self.dispose()
예제 #47
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())
예제 #48
0
class DeleteAdminForm(JPanel):
    def __init__(self):
        self.usernameLabel = JLabel('Username : '******'Super Password : '******'Delete',
                                      actionPerformed=self.deleteAdmin)
        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.usernameLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.usernameField, 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.superPassLabel, gc)

        gc.gridx = 1

        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.superPassField, 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.deleteAdminBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Delete Admin')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))

    def deleteAdmin(self, e):
        username = self.usernameField.getText()
        superPass = self.superPassField.getText()

        if isFieldsEmpty([username, superPass]):
            dialog.improperInput('One or more fields are missing!', 'No Input')
        else:
            client.delete_admin(username, superPass)
예제 #49
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
예제 #50
0
class LoginForm(JPanel):
    def __init__(self):
        self.usernameLabel = JLabel('Username : '******'Password : '******'Login', actionPerformed=self.login)
        self.initComponents()

    def initComponents(self):

        self.setLayout(GridBagLayout())

        gc = GridBagConstraints()

        # 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.usernameLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.usernameField, 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.passwordLabel, gc)

        gc.gridx = 1

        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.passwordField, 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.loginBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Login ')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))

    def login(self, e):
        username = self.usernameField.getText()
        password = self.passwordField.getText()

        fields = [username, password]

        if isFieldsEmpty(fields):
            dialog.improperInput('One or more fields are missing!', 'No Input')
        else:
            client.login(username, password)
            method = 'refresh'
            callMethod = getattr(TopPanel(), method)
예제 #51
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
예제 #52
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
예제 #53
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()
예제 #54
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory, ActionListener,
                   AbstractTableModel, Runnable):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def getUiComponent(self):
        return self._mainTabs

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

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

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

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

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

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

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

    def getColumnCount(self):
        return 2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Print a completion notification
        JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
예제 #55
0
class Demo(JFrame, Runnable):

    def __init__(self):
        super(Demo, self).__init__()

        self.initUI()

    def initUI(self):
       
        self.panel = JPanel(size=(50,50))
        

        self.panel.setLayout(FlowLayout( ))
        self.panel.setToolTipText("GPU Demo")

#TODO- change this so that it deletes itself when text is entered
        self.textfield1 = JTextField('Smoothing Parameter',15)        
        self.panel.add(self.textfield1)
      
        joclButton = JButton("JOCL",actionPerformed=self.onJocl)
        joclButton.setBounds(100, 500, 100, 30)
        joclButton.setToolTipText("JOCL Button")
        self.panel.add(joclButton)
        
        javaButton = JButton("Java",actionPerformed=self.onJava)
        javaButton.setBounds(100, 500, 100, 30)
        javaButton.setToolTipText("Java Button")
        self.panel.add(javaButton)

        qButton = JButton("Quit", actionPerformed=self.onQuit)
        qButton.setBounds(200, 500, 80, 30)
        qButton.setToolTipText("Quit Button")
        self.panel.add(qButton)
        newImage = ImageIO.read(io.File(getDataDir() + "input.png"))
        resizedImage =  newImage.getScaledInstance(600, 600,10)
        newIcon = ImageIcon(resizedImage)
        label1 = JLabel("Input Image",newIcon, JLabel.CENTER)

        label1.setVerticalTextPosition(JLabel.TOP)
        label1.setHorizontalTextPosition(JLabel.RIGHT)
        label1.setSize(10,10)
        label1.setBackground(Color.orange)
        self.panel.add(label1)
        
        self.getContentPane().add(self.panel)
        
        self.clockLabel = JLabel()
        self.clockLabel.setSize(1,1)
        self.clockLabel.setBackground(Color.orange)
        
        self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM)
        self.clockLabel.setHorizontalTextPosition(JLabel.LEFT)
        
        myClockFont = Font("Serif", Font.PLAIN, 50)
        self.clockLabel.setFont(myClockFont)
        
        
        self.panel.add(self.clockLabel)
        
        self.setTitle("Structure-oriented smoothing OpenCL Demo")
        self.setSize(1200, 700)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)
        
    def onQuit(self, e): System.exit(0)
    
    def onJocl(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     jocl_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'JOCL Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
    
    def onJava(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     java_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'Java Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
예제 #56
0
class Interfaz(JFrame):
    def __init__(self):
        super(Interfaz, self).__init__()
        self.filename = ''
        self.initUI()

    def initUI(self):

        self.panel = JPanel()
        self.panel.setLayout(GridLayout(6, 3))
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        labelVacio1 = JLabel(' ')
        labelVacio2 = JLabel(' ')
        labelVacio3 = JLabel(' ')
        labelVacio4 = JLabel(' ')
        labelVacio5 = JLabel(' ')
        labelVacio6 = JLabel(' ')
        labelVacio7 = JLabel(' ')
        labelVacio8 = JLabel(' ')
        labelVacio9 = JLabel(' ')
        labelVacio10 = JLabel(' ')
        labelVacio11 = JLabel(' ')
        labelVacio12 = JLabel(' ')
        labelVacio13 = JLabel(' ')
        labelVacio14 = JLabel(' ')
        labelVacio15 = JLabel(' ')
        labelVacio16 = JLabel(' ')

        labelURL = JLabel(' Introduzca las URL que desee analizar:')
        chkboxSync = JCheckBox('Sincronizacion de cookies')
        self.textfieldURL = JTextField(15)
        chkboxResp = JCheckBox('Restauracion de cookies')
        labelFichero = JLabel(' O seleccione un fichero que las contenga:')

        self.area = JTextArea()
        pane = JScrollPane()
        pane.getViewport().add(self.area)

        panelFichero = JPanel()
        panelFichero.setLayout(None)
        buttonFichero = JButton("Seleccionar fichero",
                                actionPerformed=self.open)
        buttonFichero.setBounds(10, 0, 200, 25)
        panelFichero.add(buttonFichero)
        buttonEjecutar = JButton("Ejecutar", actionPerformed=self.ejecutar)

        buttonEjecutar.setFont(Font("Tahoma", Font.BOLD, 24))

        self.panel.add(labelURL)
        self.panel.add(labelVacio4)
        self.panel.add(chkboxSync)

        self.panel.add(self.textfieldURL)
        self.panel.add(labelVacio6)
        self.panel.add(chkboxResp)

        self.panel.add(labelFichero)
        self.panel.add(labelVacio9)
        self.panel.add(labelVacio10)

        self.panel.add(pane)
        self.panel.add(panelFichero)
        #self.panel.add(buttonFichero)
        self.panel.add(labelVacio11)

        self.panel.add(labelVacio12)
        self.panel.add(labelVacio13)
        self.panel.add(labelVacio14)

        self.panel.add(labelVacio15)
        self.panel.add(buttonEjecutar)
        self.panel.add(labelVacio16)

        self.add(self.panel)

        self.setTitle(
            "HERRAMIENTA PARA LA DETECCION DE TECNICAS DE SEGUIMIENTO DE USUARIOS EN LA WEB"
        )
        self.setSize(1000, 450)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def open(self, e):
        filechooser = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        filechooser.addChoosableFileFilter(filter)
        ret = filechooser.showDialog(self.panel, "Elegir fichero")
        if ret == JFileChooser.APPROVE_OPTION:
            file = filechooser.getSelectedFile()
            text = self.readFile(file)
            self.area.setText(text)

    def readFile(self, file):
        filename = file.getCanonicalPath()
        self.filename = filename
        f = open(filename, "r")
        text = f.read()
        return text

    def ejecutar(self, e):
        JOptionPane.showMessageDialog(self.panel,
                                      "Ejecutando...\n Espere unos minutos.",
                                      "Info", JOptionPane.INFORMATION_MESSAGE)
        print("Ejecutando...")
        url = self.textfieldURL.getText()
        fichero = self.area.getText()
        urls_finales = ''

        if url == '' and fichero == '':
            self.error()
            return
        elif url != '' and fichero != '':
            print("Hay url y fichero")
            urls_finales = url + "\n" + fichero
            #self.writeFile(urls,1)

        elif fichero != '':
            print("Hay fichero")
            urls_finales = fichero
            #self.writeFile(fichero,1)

        elif url != '':
            print("Hay url")
            self.filename = "url"
            urls_finales = url
            #self.writeFile(url,1)

        else:
            print("Ha habido un error")

        self.writeFile(urls_finales, 1)
        f = open("bbdd.txt", "w")
        f.write(self.filename + "1\n")
        f.close()
        subprocess.call("python demo.py", shell=True)
        self.writeFile(urls_finales, 2)
        f = open("bbdd.txt", "a")
        f.write(self.filename + "2")
        f.close()
        subprocess.call("python demo.py", shell=True)
        subprocess.call("python rastreo_analisis.py", shell=True)

        self.initResultados()

    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)

    def readResultados(self):
        count = 0
        f = open("resultados.txt", "r")
        resultados = f.read()
        self.areaResultados.setText(resultados)

        for linea in f:
            self.lineas.append(linea)
            count += 1

        return count

    def writeFile(self, urls, crawl):
        self.filename = self.filename.replace(".txt", '')
        f = open("URLs.txt", "w")
        f.write(self.filename + str(crawl) + ".txt" + '\n')
        f.write(urls)
        f.close()

    def error(self):
        JOptionPane.showMessageDialog(self.panel,
                                      "Debes introducir una URL o un fichero",
                                      "Error", JOptionPane.ERROR_MESSAGE)
class BurpExtender(IBurpExtender, IHttpListener, IMessageEditorTabFactory, ITab):
    #
    # implement IBurpExtender
    #
    def	registerExtenderCallbacks(self, callbacks):
        global EXTENSION_NAME
        
        sys.stdout = callbacks.getStdout()
        sys.stderr = callbacks.getStderr()
        # 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(EXTENSION_NAME)
        
        # register ourselves as a Http Listener
        callbacks.registerHttpListener(self)

        # register ourselves as a message editor tab factory
        callbacks.registerMessageEditorTabFactory(self) 
        
        # setup the UI
        self.initGui()        
        
        # add the custom tab to Burp's UI
        self._callbacks.addSuiteTab(self)  
        
        return
    #
    # create the Gui
    #    
    def initGui(self):
        #~ if DEBUG:
            #~ import pdb;
            #~ pdb.set_trace()
        tabPane = JTabbedPane(JTabbedPane.TOP)
        CreditsText = "<html># Burp Custom Deserializer<br/># Copyright (c) 2016, Marco Tinari<br/>#<br/># This program is free software: you can redistribute it and/or modify<br/># it under the terms of the GNU General Public License as published by<br/># the Free Software Foundation, either version 3 of the License, or<br/># (at your option) any later version.<br/>#<br/># This program is distributed in the hope that it will be useful,<br/># but WITHOUT ANY WARRANTY; without even the implied warranty of<br/># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the<br/># GNU General Public License for more details.<br/>#<br/># You should have received a copy of the GNU General Public License<br/># along with this program.  If not, see <http://www.gnu.org/licenses/>.)<br/></html>"
        label1 = JLabel("<html>Usage:<br>1 - Select the desired encoding functions<br>2 - Enter the name of the parameter in the input field below and press the Apply button!</html>")
        label2 = JLabel(CreditsText)
        panel1 = JPanel()
        #set layout
        panel1.setLayout(GridLayout(11,1))
        panel2 = JPanel()
        panel1.add(label1)
        panel2.add(label2)
        tabPane.addTab("Configuration", panel1)
        tabPane.addTab("Credits", panel2)

        applyButton = JButton('Apply',actionPerformed=self.reloadConf)
        panel1.add(applyButton, BorderLayout.SOUTH)
        
        #define GET/POST/COOKIE radio button
        self.GETparameterTypeRadioButton = JRadioButton('GET parameter')
        self.POSTparameterTypeRadioButton = JRadioButton('POST parameter')
        self.COOKIEparameterTypeRadioButton = JRadioButton('COOKIE parameter')
        self.POSTparameterTypeRadioButton.setSelected(True)
        group = ButtonGroup()
        group.add(self.GETparameterTypeRadioButton)
        group.add(self.POSTparameterTypeRadioButton)
        group.add(self.COOKIEparameterTypeRadioButton)
        self.base64Enabled = JCheckBox("Base64 encode")
        self.URLEnabled = JCheckBox("URL encode")
        self.ASCII2HexEnabled = JCheckBox("ASCII to Hex")
        self.ScannerEnabled = JCheckBox("<html>Enable serialization in Burp Scanner<br>Usage:<br>1.Place unencoded values inside intruder request and define the placeholder positions<br>2.rightclick->Actively scan defined insertion points)</html>")
        self.IntruderEnabled = JCheckBox("<html>Enable serialization in Burp Intruder<br>Usage:<br>1.Place unencoded values inside intruder request and define the placeholder positions<br>2.Start the attack</html>")
        self.parameterName = JTextField("Parameter name goes here...",60)
        
        #set the tooltips
        self.parameterName.setToolTipText("Fill in the parameter name and apply")
        self.base64Enabled.setToolTipText("Enable base64 encoding/decoding")
        self.ASCII2HexEnabled.setToolTipText("Enable ASCII 2 Hex encoding/decoding") 
        self.URLEnabled.setToolTipText("Enable URL encoding/decoding")
        self.IntruderEnabled.setToolTipText("Check this if You want the extension to intercept and modify every request made by the Burp Intruder containing the selected paramter")
        self.ScannerEnabled.setToolTipText("Check this if You want the extension to intercept and modify every request made by the Burp Scanner containing the selected paramter")

        #add checkboxes to the panel            
        panel1.add(self.parameterName)
        panel1.add(self.POSTparameterTypeRadioButton)
        panel1.add(self.GETparameterTypeRadioButton)
        panel1.add(self.COOKIEparameterTypeRadioButton)
        panel1.add(self.base64Enabled)
        panel1.add(self.URLEnabled)
        panel1.add(self.ASCII2HexEnabled)
        panel1.add(self.IntruderEnabled)
        panel1.add(self.ScannerEnabled)
        #assign tabPane
        self.tab = tabPane
        
    def reloadConf(self,event):
        #~ if DEBUG:
            #~ import pdb; pdb.set_trace()
        source = event.getSource()
        print 'APPLY button clicked. New configuration loaded.'
        global MAGIC_PARAMETER
        global PARAMETERISPOST
        global PARAMETERISGET
        global PARAMETERISCOOKIE
        global BASE64ENCODINGENABLED
        global ASCII2HEXENCODINGENABLED
        global URLENCODINGENABLED
        global INTRUDERENABLED
        global SCANNERENABLED
        MAGIC_PARAMETER=self.parameterName.getText()
        print 'Base64 checkbox is: '+str(self.base64Enabled.isSelected())
        if self.base64Enabled.isSelected(): 
            BASE64ENCODINGENABLED=True
        else:
            BASE64ENCODINGENABLED=False
        print 'ASCII2Hex checkbox is: '+str(self.ASCII2HexEnabled.isSelected())
        if self.ASCII2HexEnabled.isSelected(): 
            ASCII2HEXENCODINGENABLED=True
        else:
            ASCII2HEXENCODINGENABLED=False
        print 'URL checkbox is: '+str(self.URLEnabled.isSelected())
        if self.URLEnabled.isSelected(): 
            URLENCODINGENABLED=True
        else:
            URLENCODINGENABLED=False
        print 'New Magic parameter is: '+str(MAGIC_PARAMETER)
        if self.POSTparameterTypeRadioButton.isSelected(): #BODYPARAM
            PARAMETERISPOST=True
            print "parameterispost has been set to: " + str(PARAMETERISPOST)
        else:
            PARAMETERISPOST=False
            print "parameterispost has been set to: " + str(PARAMETERISPOST)
        if self.GETparameterTypeRadioButton.isSelected(): #GETPARAM
            PARAMETERISGET=True
            print "parameterisget has been set to: " + str(PARAMETERISGET)
        else:
            PARAMETERISGET=False
            print "parameterisget has been set to: " + str(PARAMETERISGET)
        if self.COOKIEparameterTypeRadioButton.isSelected(): #COOKIEPARAM
            PARAMETERISCOOKIE=True
            print "parameteriscookie has been set to: " + str(PARAMETERISCOOKIE)
        else:
            PARAMETERISCOOKIE=False
            print "parameteriscookie has been set to: " + str(PARAMETERISCOOKIE)
        if self.ScannerEnabled.isSelected(): 
            SCANNERENABLED=True
            print "Scanner Enabled"
        else:
            SCANNERENABLED=False
        if self.IntruderEnabled.isSelected(): 
            INTRUDERENABLED=True
            print "Intruder Enabled"
        else:
            INTRUDERENABLED=False
    #
    # implement IHTTPListener
    #
    def processHttpMessage(self, toolFlag, messageIsRequest, currentRequest):
        global PARAMETERISPOST
        global PARAMETERISGET
        global PARAMETERISCOOKIE
        global URLENCODINGENABLED
        global BASE64ENCODINGENABLED
        global ASCII2HEXENCODINGENABLED
        global INTRUDERENABLED
        global SCANNERENABLED
        #only process requests
        if not messageIsRequest:
            return
        #only process messages from Intruder and Scanner, otherwise exit
        #if (not self._callbacks.TOOL_INTRUDER == toolFlag):
        if ((not ((self._callbacks.TOOL_INTRUDER == toolFlag) and INTRUDERENABLED)) and (not ((self._callbacks.TOOL_SCANNER == toolFlag) and SCANNERENABLED))):
            #print "exiting- toolflag:"+str(toolFlag)+' INTRUDERENABLED='+str(INTRUDERENABLED)+' SCANNERENABLED='+str(SCANNERENABLED)
            return
        #if ((not self._callbacks.TOOL_INTRUDER == toolFlag)) and ((not self._callbacks.TOOL_SCANNER == toolFlag)):#remove the comment to always enable
        if DEBUG:
            print "IHTTPListener Enabled in: " + str(toolFlag)
        requestInfo = self._helpers.analyzeRequest(currentRequest)
        timestamp = datetime.now()
        if DEBUG: 
            print "Intercepting message at: ", timestamp.isoformat()
        #parameters = requestInfo.getParameters()
        dataParameter = self._helpers.getRequestParameter(currentRequest.getRequest(), MAGIC_PARAMETER)
        #FIXME: add exception handling for multiple parameters with the same name and/or in a different position!!!
        if DEBUG:
            print 'dataparameter:'+str(dataParameter)
        if (dataParameter == None):
            if DEBUG:
                print 'Parameter does not exist'
            return
        serializedValue = dataParameter.getValue()
        #FIXME: substitute '[AND]' placeholder with '&' charachter - we should do something more elegant here :/
        serializedValue = re.sub(r'\[AND\]', '&', serializedValue) 
        print "unserialized parameter value: ", str(serializedValue)
        if BASE64ENCODINGENABLED: #if base64Encode is selected
            serializedValue = self._helpers.base64Encode(serializedValue)
            if DEBUG:
                print "base64 encoded parameter value: ", str(serializedValue)
        if URLENCODINGENABLED: #if URLEncode is selected
            serializedValue = self._helpers.urlEncode(serializedValue)
            if DEBUG:
                print "URL ecoded parameter value: ", str(serializedValue)
        if ASCII2HEXENCODINGENABLED: #if ASCII2HexEncode is selected
            serializedValue = convert_ascii2hex(serializedValue)
            if DEBUG:
                print "ASCII2Hex ecoded parameter value: ", str(serializedValue)
        print "serialized parameter value: ", serializedValue
        if PARAMETERISPOST:
            if DEBUG:
                print "parameter is BODY"
            currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_BODY)))
        elif PARAMETERISGET:
            if DEBUG:
                print "parameter is in URL"
            currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_URL)))       
        elif PARAMETERISCOOKIE:
            if DEBUG:
                print "parameter is a COOKIE"
            currentRequest.setRequest(self._helpers.updateParameter(currentRequest.getRequest(),self._helpers.buildParameter(MAGIC_PARAMETER, serializedValue,IParameter.PARAM_COOKIE)))       
        return
    
    # 
    # implement ITab
    #
    
    def getTabCaption(self):
        global EXTENSION_TABCAPTION
        return(EXTENSION_TABCAPTION)

    def getUiComponent(self):
        #~ return self._splitpane
        return self.tab


    # 
    # implement IMessageEditorTabFactory
    #
    def createNewInstance(self, controller, editable):
        
        # create a new instance of our custom editor tab
        return CustomInputTab(self, controller, editable)