Пример #1
0
    def __init__(self, window, api):
        self.api = api
        self.component = JPanel(BorderLayout())
        
        scrollpane = JScrollPane()
        inputPanel = JPanel()
        inputPanel.layout = GridLayout(1, 1)
        self.check_disabled = LockManager()
        self.input = InteractiveInput(
            window,
            self.check_disabled,
            self.runcode
        )
        self.input.undo = UndoManager()
        self.input.component.document.addDocumentListener(self)
        inputPanel.add(self.input.component)
        self.outputpane = OutputPane()
        scrollpane.viewport.view = self.outputpane.textpane
        self.component.add(scrollpane, BorderLayout.CENTER)
        self.component.add(inputPanel, BorderLayout.PAGE_END)
        self.history = InputHistory()

        self.stdout = MyStream(self.write)
        self.stderr = MyStream(self.error)
        
        self.running_thread = None
Пример #2
0
 def __init__(self):
     self.frame = JFrame("Python Window")
     self.historyList = JList(DefaultListModel())
     self.historyList.cellRenderer = MyListCellRenderer()
     #self.historyPanel.layout = BoxLayout(
     #    self.historyPanel,
     #    BoxLayout.Y_AXIS
     #)
     scrollpane = JScrollPane()
     #    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
     #    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
     #)
     # scrollpane.preferredSize = 400, 800
     inputPanel = JPanel()
     inputPanel.layout = GridLayout(1, 1)
     self.input = JTextArea("")
     self.input.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
     self.input.tabSize = 4
     self.input.font = Font("Monospaced", Font.PLAIN, 12)
     #self.input.preferredSize = 500, 200 
     self.input.addKeyListener(self)
     #self.button = JButton('Run', actionPerformed=self.run)
     inputPanel.add(self.input)
     #inputPanel.add(self.button)
     scrollpane.viewport.view = self.historyList
     self.frame.add(scrollpane, BorderLayout.CENTER)
     self.frame.add(inputPanel, BorderLayout.PAGE_END)
     self.frame.size = 500, 600
     self.frame.visible = False
Пример #3
0
def tree():
  """
  tree(xmlfile="dsm2.xml")
    creates a tree view on a given xml file of dsm2 input data
  """
  tv = TreeViewer()
  mp2 = JPanel()
  mp2.setLayout(BorderLayout())
  tf = JTextField("dsm2.inp")
  pb = JButton("parse")
  mp2.add(tf,BorderLayout.CENTER)
  mp2.add(pb,BorderLayout.EAST)
  class ParseListener(ActionListener):
    def __init__(self,tf,tv,fr):
      self.tf = tf
      self.tv = tv
      self.fr = fr
    def actionPerformed(self,evt):
      dsm2file = self.tf.getText()
      parser = DSM2Parser(dsm2file)
      self.tv.xdoc = parser.dsm2_data.toXml()
      self.fr.getContentPane().add(self.tv.gui(),BorderLayout.CENTER)
      self.fr.pack()
      self.fr.setVisible(1)
  fr = JFrame()
  fr.setTitle("DSM2Tree")
  fr.setLocation(100,100)
  fr.setSize(600,60)
  fr.getContentPane().setLayout(BorderLayout())
  fr.getContentPane().add(mp2,BorderLayout.NORTH)
  al = ParseListener(tf,tv,fr)
  pb.addActionListener(al)
  fr.pack()
  fr.setVisible(1)
Пример #4
0
class ScriptPane(WindowPane):

    def __init__(self, window, api):
        self.api = api
        self.component = JPanel(BorderLayout())

        # Create editor pane
        scrollpane = JScrollPane()
        self.script_area = InputPane(window)
        line_numbers = LineNumbering(self.script_area.component)
        scrollpane.viewport.view = self.script_area.component
        scrollpane.rowHeaderView = line_numbers.component
        self.component.add(scrollpane, BorderLayout.CENTER)
        
        self.script_area.undo = UndoManager()
        self.reset()
        
    def indent_selection(self):
        self.script_area.indent_selection()
    def dedent_selection(self):
        self.script_area.dedent_selection()

    def reset(self):
        self.script_area.input = self.api.getInitScript()
        self.script_area.reset_undo()
        
    def save_script(self):
        self.api.setInitScript(self.script_area.input)
Пример #5
0
    def __init__(self, channels):
        JFrame.__init__(self, "Informa Example News Client")
        self.setSize(400, 400)
        self.addWindowListener(BasicWindowMonitor())

        self.channels = channels
        self.channel_dict = None

        self.channelTree = None
        self.channelPanel = None
        self.itemTable = None

        self.mediator = MainMediator(self)
        
        # items (in table)
        itemScrollPane = JScrollPane(self.getItemTable())

        # channels (as tree)
        channelScrollPane = JScrollPane(self.getChannelTree())

        # put together channel info with item table
        ch_and_items = JPanel()
        ch_and_items.setLayout(BorderLayout())
        ch_and_items.add(self.getChannelPanel(), BorderLayout.NORTH)
        ch_and_items.add(itemScrollPane, BorderLayout.CENTER)

        # final step
        sp = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                        channelScrollPane, ch_and_items)
        # print "dividerLocation", sp.getDividerLocation()
        # sp.setDividerLocation(0.5)
        self.getContentPane().add(sp, BorderLayout.CENTER)
Пример #6
0
    def initUI(self):

        panel = JPanel()
        panel.setLayout(None)
        panel.setBackground(Color(66, 66, 66))
        self.getContentPane().add(panel)

        rot = ImageIcon("input.png")
        rotLabel = JLabel(rot)
        rotLabel.setBounds(20, 20, rot.getIconWidth(), rot.getIconHeight())

        min = ImageIcon("cpuoutput.png")
        minLabel = JLabel(min)
        minLabel.setBounds(40, 160, min.getIconWidth(), min.getIconHeight())

        bar = ImageIcon("inputdata.png")
        barLabel = JLabel(bar)
        barLabel.setBounds(170, 50, bar.getIconWidth(), bar.getIconHeight())


        panel.add(rotLabel)
        panel.add(minLabel)
        panel.add(barLabel)


        self.setTitle("Absolute")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(350, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)
Пример #7
0
class UI(object):
    def __init__(self, game):

        self.frame = JFrame("Tic Tac Toe",
                             defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE)

        self.panel = JPanel(GridLayout(3,3))
        self.buttons = []
        self.game = game
        for row in range(3):
            for col in range(3):
                self.buttons.append(TicTacButton(row,col,'',actionPerformed=self.clicked_button))

        self.panel.add
        self.frame.add(self.panel)
        for b in self.buttons:
            self.panel.add(b)

        self.frame.pack()
        self.show()


    def show(self):
        self.frame.size = 600,600
        self.frame.visible = True


    def clicked_button(self, event):
        button = event.getSource()
        print 'current_player', self.game.current_player
        if self.game.current_player.level == 'human' and self.game.state=='next':
            button.text = self.game.current_player.xo
            self.game.update(button)
        else:
            pass
Пример #8
0
    def __init__(self, frame, what, entries, pingFun):
        JDialog(frame, what)
        self.frame   = frame
        self.entries = entries
        self.pingFun = pingFun
        pane = self.getRootPane().getContentPane()

        self.ent_pane, self.ent_list, self.ent = self.createList(entries)
        pane.add(self.ent_pane, BorderLayout.WEST)

        actionPanel = JPanel()
        actionPanel.setLayout(GridLayout(20, 1))
        self.text = JTextField(20)
        actionPanel.add(self.text)
        change = JButton('Change')
        change.setActionCommand('Change')
        change.addActionListener(self)
        actionPanel.add(change)
        actionPanel.add(JLabel(''))
        quit = JButton('Exit')
        quit.setActionCommand('Exit')
        quit.addActionListener(self)
        actionPanel.add(quit)
        actionPanel.add(JLabel(''))
        pane.add(actionPanel, BorderLayout.CENTER)

        self.pack()
Пример #9
0
    def add_template(self,name,constructor,image):
        icon = ImageIcon(image)
        if icon.iconWidth>self.max_icon_width:
            icon = ImageIcon(icon.image.getScaledInstance(self.max_icon_width,icon.iconHeight*self.max_icon_width/icon.iconWidth,Image.SCALE_SMOOTH))


        panel = JPanel(layout = BorderLayout(),opaque = False)

        button = JButton(icon = icon,toolTipText = name.replace('\n',' '),
                       borderPainted = False,focusPainted = False,contentAreaFilled = False,margin = java.awt.Insets(0,0,0,0),
                       verticalTextPosition = AbstractButton.BOTTOM,horizontalTextPosition = AbstractButton.CENTER,
                       mousePressed = lambda e: e.source.transferHandler.exportAsDrag(e.source,e,TransferHandler.COPY))
        button.transferHandler = self
        panel.add(button)

        text = '<html><center>%s</center></html>'%name.replace('\n','<br/>')
        label = JLabel(text,horizontalAlignment = SwingConstants.CENTER,foreground = Color.WHITE)
        self.labels.append(label)
        panel.add(label,BorderLayout.SOUTH)
        self.panels.append(panel)

        panel.alignmentY = Component.CENTER_ALIGNMENT
        panel.border = BorderFactory.createEmptyBorder(2,1,2,1)
        panel.maximumSize = panel.preferredSize
        self.panel.add(panel)
        self.templates[button] = constructor
Пример #10
0
    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)
Пример #11
0
 def gui(self):
   xnode = self.xdoc.getDocumentElement()
   tnode = self.createTree(xnode)  
   # create tree and display
   jt = JTree(tnode)
   jsp = JScrollPane(jt)
   tree_box = Box(BoxLayout.Y_AXIS)
   tree_box.add(jsp)
   tree_box.add(Box.createHorizontalStrut(10))
   headerSorter = TableSorter(DefaultTableModel())
   jtb = JTable(headerSorter)
   headerSorter.addMouseListenerToHeaderInTable(jtb)
   jtb.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
   jsp2 = JScrollPane(jtb)
   table_box = Box(BoxLayout.Y_AXIS)
   table_box.add(jsp2)
   table_box.add(Box.createHorizontalStrut(500))
   mp = JPanel()
   mp.setLayout(BoxLayout(mp,BoxLayout.X_AXIS))
   mp.add(tree_box)
   mp.add(table_box)
   # add listeners
   nsl = NodeSelectionListener(jtb,xnode)
   jt.addTreeSelectionListener(nsl)
   #
   return mp
Пример #12
0
    def BuildWindow(self):
        if jython:
            contentPane = self.getContentPane()
            contentPane.setLayout(BorderLayout())
            self.fileListUpdateButton = JButton("Update file list", actionPerformed=self.OnUpdateFileList)
            self.fileNamesList = JList(DefaultListModel(), mouseClicked=self.mouseClicked)
            self.specialReloadButton = JButton("Special reload module (or double click)", actionPerformed=self.OnSpecialReloadOfModule)
            self.regularReloadButton = JButton("Regular reload module", actionPerformed=self.OnRegularReloadOfModule)
            contentPane.add("North", self.fileListUpdateButton)
            contentPane.add("Center", JScrollPane(self.fileNamesList))
            reloadButtonPanel = JPanel(BorderLayout())
            reloadButtonPanel.add("North", self.specialReloadButton)
            reloadButtonPanel.add("South", self.regularReloadButton)
            contentPane.add("South", reloadButtonPanel)
        else:
            vbox = MakeVerticalBox(self.window)
            self.fileListUpdateButton = MakeButton(vbox, "Update file list", self.OnUpdateFileList)

            self.fileNamesList = MakeList(vbox, "Python module", None)
            self.fileNamesList.connect("button-press-event", self.mouseClicked)
            
            self.specialReloadButton = MakeButton(vbox, "Special reload module (or double click)", self.OnSpecialReloadOfModule)
            self.regularReloadButton = MakeButton(vbox, "Regular reload module", self.OnRegularReloadOfModule)
           
            ShowWindow(self.window)
        self.loadFileList()
Пример #13
0
    def startGui(self):
        
#        self.gridPanel = JPanel(GridLayout(self.numRows, self.numCols))
#        self.cellButtons = self._doForAllCells(self._createCellButton)
#        self.grid = self._doForAllCells(lambda r,c: False)
#        frame.add(self.gridPanel)
#        buttonPanel = JPanel(FlowLayout())
#        stepButton = JButton("Step", actionPerformed=self._step)
#        runButton = JToggleButton("Run", actionPerformed=self._run)
#        buttonPanel.add(stepButton)
#        buttonPanel.add(runButton)
#        frame.add(buttonPanel, SOUTH)
#        frame.pack()
#        frame.locationRelativeTo = None
        self.setMenuBar()
        
        image_path = "D:\\wamp\\www\\holdem\\src\\poker\\th\\images\\As.png"
        myPicture = ImageIcon(image_path)
        myPictureLabel = JLabel("Pocket: ", myPicture, JLabel.LEFT)
        
        cardPanel = JPanel()
        cardPanel.setLayout(None)
        cardPanel.add(myPictureLabel)
        myPictureLabel.setBounds(10,10,36,52);
        
        self._frame.getContentPane().add(cardPanel)

        
        self.msg=JLabel("Hello")
        self._frame.add(self.msg, NORTH)
        self._frame.locationRelativeTo = None
        self._frame.visible = True
Пример #14
0
Файл: ashdi.py Проект: sjp38/ash
def getScreenPanel():
    global mainScreen
    global scrPanel
    if not scrPanel:
        mainScreen = JButton()
        cursorImg = BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB)
        blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, Point(0,0), "blank cursor")
        mainScreen.setCursor(blankCursor)
        mainScreen.setPreferredSize(
                Dimension(700, 700))
        image = BufferedImage(700, 700, BufferedImage.TYPE_INT_ARGB)
        g = image.createGraphics()
        g.setColor(Color.BLACK)
        g.fillRect(0, 0, 700, 700)
        g.setColor(Color.WHITE)
        g.setFont(Font("Serif", Font.BOLD, 20))
        g.drawString("Move your mouse here to controlfocused device.", 50, 30)
        mainScreenImg = image
        mainScreen.setIcon(swing.ImageIcon(image))

        mouseListener = ScrMouseListener()
        mainScreen.addMouseListener(mouseListener)
        mainScreen.addMouseMotionListener(mouseListener)
        mainScreen.addMouseWheelListener(mouseListener)

        mainScreen.setFocusable(True)
        keyListener = ScrKeyListener()
        mainScreen.addKeyListener(keyListener)


        scrPanel = JPanel()
        scrPanel.setLayout(BoxLayout(scrPanel, BoxLayout.Y_AXIS))
        scrPanel.add(mainScreen)
        scrPanel.setFocusable(True)
    return scrPanel
Пример #15
0
 def make_code_editor():
     import inspect
     panel = JPanel(BorderLayout(2,2))
     self.codeArea = JTextArea()
     self.codeArea.text = self.scoringModule and inspect.getsource(self.scoringModule) or ""
     panel.add(JScrollPane(self.codeArea), BorderLayout.CENTER)
     return panel
Пример #16
0
    def __init__(self, parent, title, modal, app):
        self.app = app
        self.setSize(400, 450)
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BorderLayout(5, 5))

        #Intro
        introLbl = JLabel("<html>%s</html>" % self.app.strings.getString("error_info_intro"))

        #Panel for displaying error info
        self.infoPanel = HtmlPanel()
        self.infoPanel.getEditorPane().addHyperlinkListener(self)
        self.scrollPane = JScrollPane(self.infoPanel)

        #OK button
        btnPanel = JPanel(FlowLayout(FlowLayout.CENTER))
        okBtn = JButton(self.app.strings.getString("OK"),
                        ImageProvider.get("ok"),
                        actionPerformed=self.on_okBtn_clicked)
        btnPanel.add(okBtn)

        #Layout
        self.add(introLbl, BorderLayout.PAGE_START)
        self.add(self.scrollPane, BorderLayout.CENTER)
        self.add(btnPanel, BorderLayout.PAGE_END)

        self.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE)
Пример #17
0
	def __init__(self,hostname):
		
		self.hostname=hostname
		
		JPanel.__init__(self,BorderLayout())
		self.cbActionListener=foo2(self)
		
		#imglist=os.listdir('./img')
		#try:imglist.remove('.svn')
		#except:pass
		imglist=['01-CircleOfFifths.gif','Fifths.png','circle-o-fifths.jpg','Circle_Of_Fifths.gif','Keywheel.gif','circle-of-fifths.gif','ColorFifths.jpg','cof.gif']
		
		self.cb=JComboBox(imglist,actionListener=self.cbActionListener)#
		#self.cb.addItemListener(self.cbCB)
		tb=JPanel()
		tb.setLayout(FlowLayout(FlowLayout.CENTER))
		tb.add(self.cb)
		self.add(tb,'Center')
		
		self.img=None
		if hostname[0:7]=='http://':
			self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+imglist[0]))
		else:
			self.img=ImageIO.read(File(self.hostname+'img/'+imglist[0]))
		
		icon=ImageIcon(self.img)
		self.label=JLabel(icon)
		self.add(self.label,'North')
Пример #18
0
    def __init__(self):
        super(AboutDialog, self).__init__()

        # Open the files and build a tab pane
        self.tabbedPane = tabs = JTabbedPane()

        for title, path in self.INFO_FILES:
            textPane = JTextPane()
            textPane.editable = False
            scrollPane = JScrollPane(textPane)
            scrollPane.preferredSize = (32767, 32767)   # just a large number

            with open(path, 'r') as fd:
                infoText = fd.read().decode('utf8')
                textPane.text = infoText

            textPane.caretPosition = 0
            tabs.addTab(title, scrollPane)

        # Load this tabbed pane into the layout
        self.add(tabs, BorderLayout.CENTER)

        # Add a label at the top
        versionLabel = JLabel(JESVersion.TITLE + " version " + JESVersion.RELEASE)
        versionLabel.alignmentX = Component.CENTER_ALIGNMENT

        versionPanel = JPanel()
        versionPanel.add(versionLabel)
        self.add(versionPanel, BorderLayout.PAGE_START)

        # Make an OK button
        self.okButton = JButton(self.ok)
        self.buttonPanel.add(self.okButton)
Пример #19
0
def get_tools(*args, **kwargs) :
    server_url = args[0]
    graphics = args[1]
    label = JLabel(server_url)
    panel = JPanel()
    panel.add(label)
    panel.add(JButton())
    return panel
Пример #20
0
 def _create_ui(self, employees, dateprovider):
     panel = JPanel(layout=FlowLayout())
     self._overview = EmployeeOverview(employees, self)
     self._details = EmployeeDetails(employees, dateprovider)
     self._welcome = Welcome()
     panel.add(self._overview)
     panel.add(self._welcome)
     return panel
Пример #21
0
 def _create_panel(self, message, widget):
     panel = JPanel()
     panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
     label = self._create_label(message)
     label.setAlignmentX(Component.LEFT_ALIGNMENT)
     panel.add(label)
     widget.setAlignmentX(Component.LEFT_ALIGNMENT)
     panel.add(widget)
     return panel
Пример #22
0
 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
Пример #23
0
 def __init__(self, message, default, hidden=False):
     self._input_field = JPasswordField() if hidden else JTextField()
     self._input_field.setText(default)
     self._input_field.selectAll()
     panel = JPanel(layout=GridLayout(2, 1))
     panel.add(JLabel(message))
     panel.add(self._input_field)
     pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION)
     pane.set_focus_listener(self._input_field)
     _SwingDialog.__init__(self, pane)
Пример #24
0
 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
Пример #25
0
 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
Пример #26
0
 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
Пример #27
0
 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
Пример #28
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)
Пример #29
0
    def buildpane(self):
        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(JButton("Send Message", actionPerformed=self.message))
        buttons.add(JButton("Add Contact", actionPerformed=self.addContact))
        #buttons.add(JButton("Quit", actionPerformed=self.quit))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.table))
        mainpane.add(buttons)
        self.update()
Пример #30
0
 def addNotice(self):
     """
     Add a panel that notifies the user about the model view not being
     ready yet.
     """
     panel = JPanel()
     panel.setBackground(Color.yellow)
     label = JLabel("Please note Nammu's model view is under "
                    "construction.")
     panel.add(label)
     return panel
Пример #31
0
# fetch displays and data from the server
d1 = ClientServer.getClientDisplay(client, 0)
d2 = ClientServer.getClientDisplay(client, 1)
refimg = client.getDataReference(0)
userline = client.getDataReference(1)

# get image in order to get its size and type schema
image = refimg.getData()
dom = getDomain(image)
LINES = dom.getY().getLength()
d = domainType(image)

# create line slider for client user
slide = VisADSlider("imgline", 0, LINES, 0, 1.0, userline, d[1])

showAxesScales(d2, 1)

# display everything...
frame = JFrame("Test T8 Client")
pane = frame.getContentPane()
pane.setLayout(BorderLayout())

# GridLayout with 1 row, 2 columns, 5 pixel horiz and vert gaps
panel = JPanel(GridLayout(1, 2, 5, 5))
panel.add(d1.getComponent())
panel.add(d2.getComponent())
pane.add("Center", panel)
pane.add("North", slide)
frame.setSize(800, 500)
frame.setVisible(1)
Пример #32
0
    def tag_3_1(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

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

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

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

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

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

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

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

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

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

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.white_list_domain_settings.add(buttonsPanel, c)
Пример #33
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):

        # properties
        self._title = "Generate Python Template"
        self._templatePath = '###### ----> PUT HERE THE ABSOLUTE PATH TO template.py <--- ####'

        # set our extension name
        callbacks.setExtensionName(self._title)

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

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

        # obtain std streams
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # main pane (top/bottom)
        self._mainpane = JPanel()
        self._mainpane.setLayout(GridLayout(2, 1))

        # configure bottom pane for buttons
        self._botPane = JPanel()
        flowLayout = FlowLayout()
        self._botPane.setLayout(flowLayout)
        self._botPane.add(
            JButton("Generate", actionPerformed=self.regeneratePy))
        self._botPane.add(JButton("Export", actionPerformed=self.exportPy))

        # Configure pyViewer (JTextArea) for python output --> top pane
        self._pyViewer = JTextArea(5, 20)
        scrollPane = JScrollPane(self._pyViewer)
        self._pyViewer.setEditable(True)
        self._pyViewer.setText("Waiting request ...")

        ### Assign top / bottom components
        self._mainpane.add(scrollPane)
        self._mainpane.add(self._botPane)

        # customize our UI components
        callbacks.customizeUiComponent(self._mainpane)

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

        # register ourselves as a ContextMenuFactory
        callbacks.registerContextMenuFactory(self)

        return

    def regeneratePy(self, event):
        pass

    def exportPy(self, event):
        chooseFile = JFileChooser()
        ret = chooseFile.showDialog(self._mainpane, "Choose file")
        filename = chooseFile.getSelectedFile().getCanonicalPath()
        self._stdout.println("Export to : " + filename)
        open(filename, 'w', 0).write(self._pyViewer.getText())

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "PyTemplate"

    def getUiComponent(self):
        return self._mainpane

    #
    # implement IContextMenuFactory
    #

    def createMenuItems(self, invocation):
        # add a new item executing our action
        item = JMenuItem(
            self._title,
            actionPerformed=lambda x, inv=invocation: self.loadRequest(inv))
        return [item]

    def loadRequest(self, invocation):
        pyCode = self.pythonHeader()
        selectedMessages = invocation.getSelectedMessages()
        self._numbMessages = len(selectedMessages)
        self._currentMessageNumber = 1
        for message in selectedMessages:
            self._currentlyDisplayedItem = message
            pyCode += self.generateRequest()
            self._currentMessageNumber += 1
        pyCode += '\n' + self.generateMain()
        self._pyViewer.setText(pyCode)

    def pythonHeader(self):
        pyCode = "# -*- coding: utf-8 -*-\n\n"
        pyCode += "import requests\n"
        pyCode += "import time\n\n"
        return pyCode

    def formatHeaders(self, httpReqInfos):
        headers = httpReqInfos.getHeaders()[
            1:]  #First header is method+path : GET/POST ..
        formatHeaders = ""

        name, content = headers[0].split(':', 1)
        formatHeaders += 'headers["' + self.sanitizeStr(
            name) + '"] = ' + '"' + self.sanitizeStr(content) + '"\n'

        for header in headers[1:]:
            name, content = header.split(':', 1)
            if "Content-Length" not in name:
                if "Cookie" in name and self._numbMessages > 1 and self._currentMessageNumber != 1:
                    continue
                else:
                    formatHeaders += '    headers["' + self.sanitizeStr(
                        name) + '"] = ' + '"' + self.sanitizeStr(
                            content) + '"\n'
        return formatHeaders

    def sanitizeStr(self, strToValid):
        valid = str(strToValid)
        valid = valid.replace('"', '\\"')
        return valid.strip()

    def generateRequest(self):
        httpInfos = self._currentlyDisplayedItem.getHttpService()
        httpReq = self._currentlyDisplayedItem.getRequest()
        requestInfos = self._helpers.analyzeRequest(httpInfos, httpReq)
        pyTemplate = open(self._templatePath, 'r').read()
        pyCode = pyTemplate.replace('$$NUM$$', str(self._currentMessageNumber))
        pyCode = pyCode.replace('$$URL$$',
                                self.sanitizeStr(requestInfos.getUrl()))
        pyCode = pyCode.replace('$$HEADERS$$',
                                self.formatHeaders(requestInfos))
        pyCode = pyCode.replace('$$METHOD$$', requestInfos.getMethod())
        if requestInfos.getMethod() == "GET":
            trigger = "req = session.get(url, headers=headers, verify=False, allow_redirects=True)"
            pyCode = pyCode.replace('$$TRIGGER$$', trigger)
            pyCode = pyCode.replace('$$POST_DATA$$', '')
        if requestInfos.getMethod() == "POST":
            trigger = "req = session.post(url, headers=headers, data=post_data, verify=False, allow_redirects=True)"
            pyCode = pyCode.replace('$$TRIGGER$$', trigger)
            rawData = httpReq[requestInfos.getBodyOffset():].tostring()
            dataPyCode = '## POST DATA\n'
            dataPyCode += '    post_data = "' + self.sanitizeStr(
                rawData) + '"\n'
            pyCode = pyCode.replace('$$POST_DATA$$', dataPyCode)
        return pyCode + '\n'

    def generateMain(self):
        pyCode = 'if __name__ == "__main__":\n'
        pyCode += '    session = requests.Session()\n'
        for i in xrange(1, self._numbMessages + 1):
            pyCode += '    code_' + str(i) + ', time_' + str(
                i) + ', response_' + str(i) + ' = performRequest_' + str(
                    i) + '(session)\n'
        return pyCode
Пример #34
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory):
    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Autorize")

        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        self._enfocementStatuses = [
            "Authorization bypass!",
            "Authorization enforced??? (please configure enforcement detector)",
            "Authorization enforced!"
        ]
        self.intercept = 0

        self.initInterceptionFilters()

        self.initEnforcementDetector()

        self.initEnforcementDetectorUnauthorized()

        self.initExport()

        self.initConfigurationTab()

        self.initTabs()

        self.initCallbacks()

        self.currentRequestNumber = 1

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

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

        exportLType = JLabel("File Type:")
        exportLType.setBounds(10, 10, 100, 30)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def initTabs(self):
        #
        ##  init autorize tabs
        #

        self.logTable = Table(self)

        self.logTable.setAutoCreateRowSorter(True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            else:
                if (enforcementStatusFilter
                        == self._log.get(i)._enfocementStatus) or (
                            enforcementStatusFilter
                            == self._log.get(i)._enfocementStatusUnauthorized):
                    csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (
                        self._log.get(i)._id, self._log.get(i)._url,
                        len(
                            self._log.get(
                                i)._originalrequestResponse.getResponse())
                        if self._log.get(i)._originalrequestResponse != None
                        else 0,
                        len(self._log.get(i)._requestResponse.getResponse())
                        if self._log.get(i)._requestResponse != None else 0,
                        len(
                            self._log.get(i)._unauthorizedRequestResponse.
                            getResponse()) if
                        self._log.get(i)._unauthorizedRequestResponse != None
                        else 0, self._log.get(i)._enfocementStatus,
                        self._log.get(i)._enfocementStatusUnauthorized)

        f = open(fileToSave.getAbsolutePath(), 'w')
        f.writelines(csvContent)
        f.close()

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

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

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

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

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

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

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

    #
    # implement ITab
    #
    def getTabCaption(self):
        return "Autorize"

    def getUiComponent(self):
        return self._splitpane

    #
    # extend AbstractTableModel
    #

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

    def getColumnCount(self):
        return 7

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

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

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

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

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

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

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

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

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

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

                        do_the_check = 1

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

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

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

        return

    def sendRequestToAutorizeWork(self, messageInfo):

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

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

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

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

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

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

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

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

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

                auth_enforced = 1

                for filter in filters:

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

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

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

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

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

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

                    if str(filter).startswith("Content-Length: "):
                        if newContentLen != filter:
                            auth_enforced = 0

                if auth_enforced:
                    impression = self._enfocementStatuses[2]
                else:
                    impression = self._enfocementStatuses[1]

        else:
            impression = self._enfocementStatuses[2]

        return impression

    def checkAuthorization(self, messageInfo, originalHeaders,
                           checkUnauthorized):
        message = self.makeMessage(messageInfo, True, True)
        requestResponse = self.makeRequest(messageInfo, message)
        analyzedResponse = self._helpers.analyzeResponse(
            requestResponse.getResponse())

        oldStatusCode = originalHeaders[0]
        newStatusCode = analyzedResponse.getHeaders()[0]
        oldContentLen = self.getContentLength(originalHeaders)
        newContentLen = self.getContentLength(analyzedResponse.getHeaders())

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

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

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

        self._lock.acquire()

        row = self._log.size()

        if checkUnauthorized:
            self._log.add(
                LogEntry(
                    self.currentRequestNumber,
                    self._callbacks.saveBuffersToTempFiles(requestResponse),
                    self._helpers.analyzeRequest(requestResponse).getUrl(),
                    messageInfo, impression,
                    self._callbacks.saveBuffersToTempFiles(
                        requestResponseUnauthorized), impressionUnauthorized)
            )  # same requests not include again.
        else:
            self._log.add(
                LogEntry(
                    self.currentRequestNumber,
                    self._callbacks.saveBuffersToTempFiles(requestResponse),
                    self._helpers.analyzeRequest(requestResponse).getUrl(),
                    messageInfo, impression, None,
                    "Disabled"))  # same requests not include again.

        self.fireTableRowsInserted(row, row)
        self.currentRequestNumber = self.currentRequestNumber + 1
        self._lock.release()

    def getContentLength(self, analyzedResponseHeaders):
        for header in analyzedResponseHeaders:
            if "Content-Length:" in header:
                return header
        return "null"

    def getCookieFromMessage(self, messageInfo):
        headers = list(
            self._helpers.analyzeRequest(
                messageInfo.getRequest()).getHeaders())
        for header in headers:
            if "Cookie:" in header:
                return header
        return None
Пример #35
0
    def getUiComponent(self):
        self.panel = JPanel()
        self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS))

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

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

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

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

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

        return self.panel
Пример #36
0
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

        ### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(
            app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(
            app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(
            self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "tool_16.png"
                ])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(
            self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "black_tool_16.png"
                ])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(
            ImageIcon(
                File.separator.join(
                    [self.app.SCRIPTDIR, "images", "icons", "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(
            ChecksTableClickListener(app, self.checkPopup, self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(
            app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(
            app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

        ### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(
            errorInfoBtnIcon,
            actionPerformed=app.on_errorInfoBtn_clicked,
            enabled=0)
        notErrorIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(
            notErrorIcon,
            actionPerformed=app.on_falsePositiveBtn_clicked,
            enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(
            correctedIcon,
            actionPerformed=app.on_correctedBtn_clicked,
            enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(
            app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(
            app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(
            app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(
            app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"), None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)
Пример #37
0
def doall(locations,
          fileobs,
          filerun1,
          filerun2,
          stime,
          etime,
          imageDir='d:/temp',
          weights=None,
          filter_type="AVE",
          normalize=False):
    obs = HecDss.open(fileobs, True)
    obs.setTimeWindow(stime, etime)
    run1 = HecDss.open(filerun1, True)
    run1.setTimeWindow(stime, etime)
    if filerun2 != None:
        run2 = HecDss.open(filerun2, True)
        run2.setTimeWindow(stime, etime)
    else:
        run2 = None
    rms1 = 0
    rms1_min, rms1_max = 0, 0
    rms2 = 0
    rms2_min, rms2_max = 0, 0
    rmsmap = {}
    #run2=None
    sumwts = 0
    average_interval = None
    for l in locations:
        data1 = get_matching(obs, 'A=%s C=%s E=15MIN' % (l, type))
        if data1 == None:
            data1 = get_matching(obs, 'A=%s C=%s E=1DAY' % (l, type))
        if data1 == None:
            data1 = get_matching(obs, 'A=%s C=%s E=IR-DAY' % (l, type))
        if data1 == None:
            data1 = get_matching(obs, 'A=%s C=%s E=1HOUR' % (l, type))
        drun1 = get_matching(run1, 'B=%s C=%s' % (l, type))
        if run2 != None:
            drun2 = get_matching(run2, 'B=%s C=%s' % (l, type))
        else:
            drun2 = None
        avg_intvl = "1DAY"
        if data1 != None:
            if average_interval != None:
                dobsd = TimeSeriesMath(data1).transformTimeSeries(
                    average_interval, None, filter_type, 0)
            else:
                dobsd = TimeSeriesMath(data1)
            if normalize:
                dobsd = dobsd.divide(TimeSeriesMath(data1).mean())
            dobsm = TimeSeriesMath(data1).transformTimeSeries(
                avg_intvl, None, filter_type, 0)
            dobsm_max = TimeSeriesMath(data1).transformTimeSeries(
                avg_intvl, None, "MAX", 0)
            dobsm_max.data.fullName = dobsm_max.data.fullName + "MAX"
            dobsm_min = TimeSeriesMath(data1).transformTimeSeries(
                avg_intvl, None, "MIN", 0)
            dobsm_min.data.fullName = dobsm_min.data.fullName + "MIN"
            if normalize:
                dobsm = dobsm.divide(TimeSeriesMath(data1).mean())
        if drun1 == None:
            continue
        else:
            if average_interval != None:
                drun1d = TimeSeriesMath(drun1).transformTimeSeries(
                    average_interval, None, filter_type, 0)
            else:
                drun1d = TimeSeriesMath(drun1)
            if normalize:
                drun1d = drun1d.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                if average_interval != None:
                    drun2d = TimeSeriesMath(drun2).transformTimeSeries(
                        average_interval, None, filter_type, 0)
                else:
                    drun2d = TimeSeriesMath(drun2)
                if normalize:
                    drun2d = drun2d.divide(TimeSeriesMath(drun2).mean())
            drun1m = TimeSeriesMath(drun1).transformTimeSeries(
                avg_intvl, None, filter_type, 0)
            drun1m_max = TimeSeriesMath(drun1).transformTimeSeries(
                avg_intvl, None, "MAX", 0)
            drun1m_min = TimeSeriesMath(drun1).transformTimeSeries(
                avg_intvl, None, "MIN", 0)
            if normalize:
                drun1m = drun1m.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                drun2m = TimeSeriesMath(drun2).transformTimeSeries(
                    avg_intvl, None, filter_type, 0)
                drun2m_max = TimeSeriesMath(drun2).transformTimeSeries(
                    avg_intvl, None, "MAX", 0)
                drun2m_min = TimeSeriesMath(drun2).transformTimeSeries(
                    avg_intvl, None, "MIN", 0)
                if normalize:
                    drun2m = drun2m.divide(TimeSeriesMath(drun2).mean())
            else:
                drun2m = None
        if weights != None:
            sumwts = sumwts + weights[l]
            lrms1 = calculate_rms(drun1m.data, dobsm.data) * weights[l]
            lrms1_min = calculate_rms(drun1m_min.data,
                                      dobsm_min.data) * weights[l]
            lrms1_max = calculate_rms(drun1m_max.data,
                                      dobsm_max.data) * weights[l]
            rms1 = rms1 + lrms1
            rms1_min = rms1_min + lrms1_min
            rms1_max = rms1_max + lrms1_max
            lrms2 = calculate_rms(drun2m.data, dobsm.data) * weights[l]
            lrms2_min = calculate_rms(drun2m_min.data,
                                      dobsm_min.data) * weights[l]
            lrms2_max = calculate_rms(drun2m_max.data,
                                      dobsm_max.data) * weights[l]
            rmsmap[
                l] = lrms1, lrms2, lrms1_min, lrms2_min, lrms1_max, lrms2_max
            rms2 = rms2 + lrms2
            rms2_min = rms2_min + lrms2_min
            rms2_max = rms2_max + lrms2_max
        plotd = newPlot("Hist vs New Geom [%s]" % l)
        if data1 != None:
            plotd.addData(dobsd.data)
        plotd.addData(drun1d.data)
        if drun2 != None:
            plotd.addData(drun2d.data)
        plotd.showPlot()
        legend_label = plotd.getLegendLabel(drun1d.data)
        legend_label.setText(legend_label.getText() + " [" +
                             str(int(lrms1 * 100) / 100.) + "," +
                             str(int(lrms1_min * 100) / 100.) + "," +
                             str(int(lrms1_max * 100) / 100.) + "]")
        legend_label = plotd.getLegendLabel(drun2d.data)
        legend_label.setText(legend_label.getText() + " [" +
                             str(int(lrms2 * 100) / 100.) + "," +
                             str(int(lrms2_min * 100) / 100.) + "," +
                             str(int(lrms2_max * 100) / 100.) + "]")
        plotd.setVisible(False)
        xaxis = plotd.getViewport(0).getAxis("x1")
        vmin = xaxis.getViewMin() + 261500.  # hardwired to around july 1, 2008
        xaxis.setViewLimits(vmin, vmin + 10000.)
        if data1 != None:
            pline = plotd.getCurve(dobsd.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
            g2dPanel = plotd.getPlotpanel()
            g2dPanel.revalidate()
            g2dPanel.paintGfx()
        plotm = newPlot("Hist vs New Geom Monthly [%s]" % l)
        plotm.setSize(1800, 1200)
        if data1 != None:
            plotm.addData(dobsm.data)
        #plotm.addData(dobsm_max.data)
        #plotm.addData(dobsm_min.data)
        plotm.addData(drun1m.data)
        #plotm.addData(drun1m_max.data)
        #plotm.addData(drun1m_min.data)
        if drun2 != None:
            plotm.addData(drun2m.data)
            #plotm.addData(drun2m_max.data)
            #plotm.addData(drun2m_min.data)
        plotm.showPlot()
        if data1 != None:
            pline = plotm.getCurve(dobsm.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
        plotm.setVisible(False)
        if data1 != None:
            plots = do_regression_plots(dobsm, drun1m, drun2m)
            if plots != None:
                spanel = plots.getPlotpanel()
                removeToolbar(spanel)
        mpanel = plotm.getPlotpanel()
        removeToolbar(mpanel)
        dpanel = plotd.getPlotpanel()
        removeToolbar(dpanel)
        from javax.swing import JPanel, JFrame
        from java.awt import GridBagLayout, GridBagConstraints
        mainPanel = JPanel()
        mainPanel.setLayout(GridBagLayout())
        c = GridBagConstraints()
        c.fill = c.BOTH
        c.weightx, c.weighty = 0.5, 1
        c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 0, 10, 4
        if data1 != None:
            if plots != None:
                pass
                #mainPanel.add(spanel,c)
        c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 0, 10, 4
        c.weightx, c.weighty = 1, 1
        mainPanel.add(mpanel, c)
        c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 4, 10, 6
        mainPanel.add(dpanel, c)
        fr = JFrame()
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        fr.getContentPane().add(mainPanel)
        fr.setSize(1100, 850)
        fr.show()
        mainPanel.setSize(1100, 850)
        mainPanel.setBackground(Color.WHITE)
        #import time; time.sleep(5)
        saveToPNG(mainPanel, imageDir + l + ".png")
    if weights != None:
        rms1 = (rms1 + rms1_min + rms1_max) / sumwts
        rms2 = (rms2 + rms2_min + rms2_max) / sumwts
        print 'RMS Run 1: %f' % rms1
        print 'RMS Run 2: %f' % rms2
        for loc in rmsmap.keys():
            print loc, rmsmap[loc]
Пример #38
0
class BurpExtender(IBurpExtender, IContextMenuFactory, JFrame):
    def registerExtenderCallbacks(self, callbacks):
        print '------------------------------Welcome to the Burp Suite Wordlist Creator----------------------------------'
        print 'Right click HTML or JSON responses in the Target tab to gather all unique words gathered from the response'
        # print '##########################################################################################################'
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        self.context = None
        self.hosts = set()

        #Define extension properties
        callbacks.setExtensionName("Custom Wordlist")
        callbacks.registerContextMenuFactory(self)

        #wordlist file
        self.wordlist = []

        #Setup space for save dialogue to sit in.
        self.panel = JPanel()
        self.panel.setLayout(BorderLayout())

        self.area = JTextArea()
        self.area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        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.setTitle("File chooser")
        self.setSize(300, 250)
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLocationRelativeTo(None)
        #this is just providing a place where the save box can sit in, no need for it to be visible on start
        self.setVisible(False)
        return

    def createMenuItems(self, context_menu):
        self.context = context_menu
        menu_list = ArrayList()
        #gather the information that is right-clicked
        menu_list.add(
            JMenuItem("Custom Wordlist", actionPerformed=self.wordlistCreate))

        return menu_list

    def wordlistCreate(self, event):
        #gathers information from the context menu, can be perused through with getResponse()
        http_traffic = self.context.getSelectedMessages()

        self.wordlist = []
        words = []
        host = ''
        #thanks BHP
        for traffic in http_traffic:
            http_service = traffic.getHttpService()
            host = http_service.getHost()
            print "Host is " + host + "\n"
            # when called from the Site Map (they only way I want to use it)
            # getSelectedMessages() returns nothing
            # we need go get all selected messages from the host the scope by calling getSiteMap() instead
            if self.context.getInvocationContext(
            ) == self.context.CONTEXT_TARGET_SITE_MAP_TREE or self.context.getInvocationContext(
            ) == self.context.CONTEXT_TARGET_SITE_MAP_TABLE:
                print "Called from the Site Map, which means we are about to process ALL the messages from it. It might take a while!\n"
                http_sitemap_traffic = self._callbacks.getSiteMap(
                    http_service.getProtocol() + "://" +
                    http_service.getHost())
                i = 0
                for straffic in http_sitemap_traffic:
                    http_response = straffic.getResponse()

                    if http_response != None:
                        words = self.handleTraffic(http_response)
                        i = i + 1
                        self.wordlist.extend(words)
                    print "Processed " + str(i) + " requests"
            else:
                http_response = traffic.getResponse()
                if http_response:
                    words = self.handleTraffic(http_response)
                    #add a list to the wordlist
                    self.wordlist.extend(words)
                #after all words have been added, write to file

        self.filewrite(host)

    def handleTraffic(self, http_response):
        print '#######################################Creating Wordlist...###############################################'
        headers, body = http_response.tostring().split('\r\n\r\n', 1)
        soup = BeautifulSoup(body, "html.parser")
        w_list = []

        #To look for more headers, add content-type

        #if the content is not JSON
        if headers.lower().find("content-type: application/json") == -1:
            w_list = self.workwithhtml(soup)
        elif headers.lower().find("content-type: application/json"):
            w_list = self.workwithjson(body)
        return w_list

    def workwithhtml(self, soup):
        #values to be added to the wordlsit
        w_list = []
        #list of numbers found larger than 4 characters
        numbers = []
        #strip tags from content (only gather text)
        [
            s.extract() for s in soup(
                ['style', 'script', '[document]', 'head', 'title', 'nav'])
        ]

        #soup output has to be encoded
        words = soup.get_text().encode('utf-8')
        #encode wordlist with ascii, replacing unknown chars with '?' which will be stripped later on. Solves issues with the ' character as a result of a failed encoding
        words = words.encode('ascii', 'replace')

        #sub all special chars with blank space
        bad_chars = re.escape(string.punctuation)
        bad_chars = bad_chars.replace("\'", "")

        #split on whitespace
        for w in words.split(" "):
            #strip new lines
            w = w.strip('\n')
            #replace all new lines
            w = w.replace("\n", "")
            numbers = self.numspresent(w, numbers)
            w_list = self.addtolist(w, w_list, bad_chars)

        #if there are no numbers greater than 4 chars
        if not numbers:
            print 'No interesting numbers found.'
        else:
            print 'Potentially interesting number for mangling:'
            #print all interesting numbers found
            for i in numbers:
                print i
        return w_list

    def workwithjson(self, body):
        #values to be added to the wordlist
        jList = []
        #list of numbers found larger than 4 characters
        numbers = []
        json_data = json.loads(body)

        #sub special chars with blank space
        bad_chars = re.escape(string.punctuation)
        bad_chars = bad_chars.replace("\'", "")

        for key, w in json_data.items():

            #check for numbers
            numbers = self.numspresent(key, numbers)
            numbers = self.numspresent(w, numbers)

            #handle the key and value for Json Data
            jList = self.addtolist(key, jList, bad_chars)
            jList = self.addtolist(w, jList, bad_chars)
        if not numbers:
            print 'No interesting numbers found.'
        else:
            print 'Potentially interesting number for mangling:'
            #print all interesting numbers found
            for i in numbers:
                print i
        return jList

    #check if there are numbers present in the value, if there are, add to list to be printed later.
    def numspresent(self, value, numbers):
        if len(value) >= 4 and value.isdigit():
            if value in numbers:
                pass
            else:
                numbers.append(value)
                w = ''
        return numbers

    def addtolist(self, value, wList, bad_chars):
        # bad_chars instantiated further up, essentially a list of special chars apart from '
        stripchars = re.sub(r'[' + bad_chars + ']', '', value)
        #strip numbers from value, nums already found.
        value = re.sub('[0-9]', '', stripchars)
        #grab strings that are of a reasonable length
        if len(value) >= 3 and len(value) < 12:
            value = self.checkforcontraction(value)
            wList.append(value.strip().lower())
        return wList

    def checkforcontraction(self, value):
        if "'" in value:
            if "'s" in value:
                pass
            elif "n't" in value:
                pass
            elif "'v" in value:
                pass
            elif "'r" in value:
                pass
            elif "'l" in value:
                pass
            elif "s'" in value:
                pass
            else:
                value = value.replace("'", "")
        return value

    def filewrite(self, hosts):
        print 'Preparing wordlist for the host: ' + hosts
        print '##########################################################################################################'
        wlist = list(set(self.wordlist))
        self.promptuser(wlist)

    def promptuser(self, wlist):
        fileChooser = JFileChooser()
        filter = FileNameExtensionFilter("Text Files", ["txt"])
        #shows only text files in the save menu prompt
        fileChooser.setFileFilter(filter)

        ret = fileChooser.showSaveDialog(self.panel)
        #if they have selected the save option
        if ret == JFileChooser.APPROVE_OPTION:
            file = fileChooser.getSelectedFile()
            #get the path that the user selected
            filepath = str(file.getCanonicalPath())

            with open(filepath, 'a+') as f:
                for word in sorted(wlist):
                    if word == '':
                        pass
                    else:
                        f.write(word + '\n')
            print 'Wordlist created at: ' + filepath
            print '##########################################################################################################\n'
Пример #39
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
Пример #40
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)

        # labels = list()
        # for i in range(0,numLineas-1):
        # 	labels.append(JLabel(''))
        # 	labels[i].setText(self.lineas[i])
        # 	area.setText(self.lineas[i])
        #panelResultados.add(labels[i])
        #panelResultados.add(JLabel('Holaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'))

        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()

    #subprocess.call("python rastreo_analisis.py", shell= True)
    def error(self):
        JOptionPane.showMessageDialog(self.panel,
                                      "Debes introducir una URL o un fichero",
                                      "Error", JOptionPane.ERROR_MESSAGE)
Пример #41
0
    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)
Пример #42
0
modulesRef = DataReferenceImpl("modules")
modulesRef.setData(modules)
display.addReference(modulesRef)

letWidget = LabeledColorWidget(maps.letmap)
# align along left side, to match VisADSlider alignment
#   (if we don't left-align, BoxLayout hoses everything
letWidget.setAlignmentX(Component.LEFT_ALIGNMENT)

eventWidget = EventWidget(file, amanda, amandaRef, maps.trackmap)

widgetPanel = JPanel()
widgetPanel.setLayout(BoxLayout(widgetPanel, BoxLayout.Y_AXIS))
widgetPanel.setMaximumSize(Dimension(400, 600))

widgetPanel.add(letWidget)
widgetPanel.add(eventWidget)
widgetPanel.add(Box.createHorizontalGlue())

displayPanel = display.getComponent()
dim = Dimension(800, 800)
displayPanel.setPreferredSize(dim)
displayPanel.setMinimumSize(dim)

# if widgetPanel alignment doesn't match
#  displayPanel alignment, BoxLayout will freak out
widgetPanel.setAlignmentX(displayPanel.getAlignmentX())
widgetPanel.setAlignmentY(displayPanel.getAlignmentY())

# create JPanel in frame
panel = JPanel()
Пример #43
0
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName(
            "Storing HTTP Requests/Responses into ElasticSearch")
        self.callbacks.registerHttpListener(self)
        self.callbacks.registerContextMenuFactory(self)
        self.out = callbacks.getStdout()

        self.lastTimestamp = None
        self.confESHost = ES_host
        self.confESIndex = self.callbacks.loadExtensionSetting(
            "elasticburp.index") or ES_index
        self.confBurpTools = Burp_Tools
        self.confBurpOnlyResp = Burp_onlyResponses

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

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

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

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

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

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

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

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

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

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

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

        return self.panel

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

        self.saveToES(msg)

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

    def genAddToES(self, msgs, component):
        def menuAddToES(e):
            progress = ProgressMonitor(component, "Feeding ElasticSearch", "",
                                       0, len(msgs))
            i = 0
            for msg in msgs:
                if not Burp_onlyResponses or msg.getResponse():
                    self.saveToES(msg, timeStampFromResponse=True)
                i += 1
                progress.setProgress(i)
            progress.close()

        return menuAddToES

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        doc.save()
Пример #44
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

        ### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(
            app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(
            app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(
            self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "tool_16.png"
                ])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(
            self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "black_tool_16.png"
                ])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(
            ImageIcon(
                File.separator.join(
                    [self.app.SCRIPTDIR, "images", "icons", "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(
            ChecksTableClickListener(app, self.checkPopup, self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(
            app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(
            app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

        ### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(
            errorInfoBtnIcon,
            actionPerformed=app.on_errorInfoBtn_clicked,
            enabled=0)
        notErrorIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(
            notErrorIcon,
            actionPerformed=app.on_falsePositiveBtn_clicked,
            enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(
            correctedIcon,
            actionPerformed=app.on_correctedBtn_clicked,
            enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(
            app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(
            app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(
            app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(
            app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"), None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = [
            "",
            self.app.strings.getString("Check"),
            self.app.strings.getString("Errors")
        ]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(
                self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {
            "white": (255, 255, 255),
            "black": (0, 0, 0),
            "green": (100, 200, 0),
            "red": (200, 0, 0)
        }
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(
            self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"), None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                errorInfo, self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)
Пример #45
0
def addCourse():
    global tfCourseName
    global tfCourseId
    global tfCourseFee
    global frame
    global btnEnter

    frame = JFrame("Add Course ")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(450, 450)
    frame.setLocation(200, 200)
    frame.setLayout(None)
    frame.setVisible(True)

    panel = JPanel()
    panel.setSize(450, 450)
    panel.setLocation(0, 0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)

    heading = JLabel("ADD COURSE")
    heading.setBounds(200, 30, 150, 40)

    lbCourseName = JLabel("Course Name ")
    lbCourseId = JLabel("Course Id")
    lbCourseFee = JLabel(" Course Fee")

    tfCourseName = JTextField()
    tfCourseId = JTextField()
    tfCourseFee = JTextField()

    lbCourseName.setBounds(70, 120, 130, 30)
    lbCourseId.setBounds(70, 170, 130, 30)
    lbCourseFee.setBounds(70, 220, 130, 30)

    tfCourseName.setBounds(220, 120, 150, 30)
    tfCourseId.setBounds(220, 170, 150, 30)
    tfCourseFee.setBounds(220, 220, 150, 30)

    btnEnter = JButton("Enter", actionPerformed=clickAddCourseFee)
    btnEnter.setBounds(300, 300, 100, 40)

    btnCancel = JButton("Cancel", actionPerformed=clickCancel)
    btnCancel.setBounds(70, 300, 100, 40)

    panel.add(heading)
    panel.add(lbCourseName)
    panel.add(lbCourseId)
    panel.add(lbCourseFee)
    panel.add(tfCourseFee)
    panel.add(tfCourseName)
    panel.add(tfCourseId)
    panel.add(tfCourseFee)
    panel.add(btnEnter)
    panel.add(btnCancel)

    frame.add(panel)
Пример #46
0
class tag(ITab):
    def __init__(self, callbacks, name):
        self._callbacks = callbacks
        self.name = name

    def getTabCaption(self):
        return self.name

    def getUiComponent(self):
        return self.tabs

    def setFontItalic(self, label):
        label.setFont(
            Font(label.getFont().getName(), Font.ITALIC,
                 label.getFont().getSize()))

    def setFontBold(self, label):
        label.setFont(Font('Serif', Font.BOLD, label.getFont().getSize()))

    # 配置界面添加
    def tagLoad(self):
        # 创建窗口 开始
        self.tabs = JTabbedPane()

        self.settings = JPanel(GridBagLayout())
        self.forward_requests_settings = JPanel(GridBagLayout())
        self.white_list_domain_settings = JPanel(GridBagLayout())
        self.white_list_http_method_settings = JPanel(GridBagLayout())

        c = GridBagConstraints()

        # 界面选项卡1-标签加载
        self.tag_1_1(c)
        self.tag_1_2(c)

        # 界面选项卡2-标签加载
        self.tag_2_1(c)
        self.tag_2_2(c)
        self.tag_2_3(c)

        # 界面选项卡3-标签加载
        self.tag_3_1(c)

        # 界面选项卡4-标签加载
        self.tag_4_1(c)
        self.tag_4_2(c)
        self.tag_4_3(c)
        self.tag_4_4(c)
        self.tag_4_5(c)
        self.tag_4_6(c)
        self.tag_4_7(c)
        self.tag_4_8(c)
        self.tag_4_9(c)
        self.tag_4_10(c)
        self.tag_4_11(c)
        self.tag_4_12(c)
        self.tag_4_13(c)
        self.tag_4_14(c)
        self.tag_4_15(c)

        # 添加选项卡
        self.tabs.addTab(u'基本设置', self.settings)
        self.tabs.addTab(u'http请求转发设置', self.forward_requests_settings)
        self.tabs.addTab(u'白名单域名设置', self.white_list_domain_settings)
        self.tabs.addTab(u'白名单http方法设置', self.white_list_http_method_settings)

        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.addSuiteTab(self)

    # 选项卡1-标签1-ui
    def tag_1_1(self, c):
        # 创建 检查框
        self.is_start_box = JCheckBox(u'是否启动插件',
                                      ForwardRequestsConfig.IS_START)
        self.setFontBold(self.is_start_box)
        self.is_start_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.is_start_box, c)

        # 在窗口添加一句话
        is_start_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_start_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(is_start_box_lbl, c)

    # 选项卡1-标签1-值
    def isStartBox(self):
        return self.is_start_box.isSelected()

    # 选项卡1-标签2-ui
    def tag_1_2(self, c):
        # 创建 检查框
        self.url_repeated_box = JCheckBox(
            u'是否启动url重复验证', ForwardRequestsConfig.URL_REPEATED_VERIFY)
        self.setFontBold(self.url_repeated_box)
        self.url_repeated_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(self.url_repeated_box, c)

        # 在窗口添加一句话
        url_repeated_box_lbl = JLabel(u'打勾-开启验证, 不打勾-关闭验证')
        self.setFontItalic(url_repeated_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.settings.add(url_repeated_box_lbl, c)

    # 选项卡1-标签2-值
    def urlRepeatedBox(self):
        return self.url_repeated_box.isSelected()

    # 选项卡2-标签1-ui
    def tag_2_1(self, c):
        # 创建 检查框
        self.is_proxy_forward_requests_box = JCheckBox(
            u'是否启动Proxy模块请求转发(推荐打勾)',
            ForwardRequestsConfig.IS_START_PROXY_FORWARD_REQUESTS)
        self.setFontBold(self.is_proxy_forward_requests_box)
        self.is_proxy_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.forward_requests_settings.add(self.is_proxy_forward_requests_box,
                                           c)

        # 在窗口添加一句话
        is_proxy_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_proxy_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.forward_requests_settings.add(is_proxy_forward_requests_box_lbl,
                                           c)

    # 选项卡2-标签2-ui
    def tag_2_2(self, c):
        # 创建 检查框
        self.is_repeater_forward_requests_box = JCheckBox(
            u'是否启动Repeater模块请求转发',
            ForwardRequestsConfig.IS_START_REPEATER_FORWARD_REQUESTS)
        self.setFontBold(self.is_repeater_forward_requests_box)
        self.is_repeater_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.forward_requests_settings.add(
            self.is_repeater_forward_requests_box, c)

        # 在窗口添加一句话
        is_repeater_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_repeater_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.forward_requests_settings.add(
            is_repeater_forward_requests_box_lbl, c)

    def tag_2_3(self, c):
        self.url_forward_xray = JCheckBox(
            u'是否将请求转发到xray', ForwardRequestsConfig.URL_FORWARD_XRAY)
        self.setFontBold(self.url_forward_xray)
        self.url_forward_xray.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 5
        self.forward_requests_settings.add(self.url_forward_xray, c)

        self.xray_listen_text_field = JTextField(u"127.0.0.1:7777")
        c.fill = GridBagConstraints.BOTH
        c.gridx = 0
        c.gridy = 6
        self.forward_requests_settings.add(self.xray_listen_text_field, c)

    def xrayAddress(self):
        return self.xray_listen_text_field.getText()

    def xrayIsSelect(self):
        return self.url_forward_xray.isSelected()

    # 获取允许转发的burp模块列表
    def getWhiteListModule(self):
        white_list_module = []

        if self.is_proxy_forward_requests_box.isSelected():
            white_list_module.append(4)
        if self.is_repeater_forward_requests_box.isSelected():
            white_list_module.append(64)

        return white_list_module

    # 选项卡3-标签1-ui
    def tag_3_1(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

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

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

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

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

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

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

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

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

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

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

    # 获取白名单域名列表
    def getWhiteList(self):
        return self.text_area_to_list(self.white_list_text_area)

    # 获取指定text数据
    def text_area_to_list(self, text_area):
        l = []
        text_list = text_area.getText().strip().split('\n')
        for data in text_list:
            if data == '':
                continue
            data = data.replace("\n", '')
            data = data.replace("\r", '')
            data = data.replace(" ", '')
            data = data.strip(' ')
            l.append(data)
        return l

    # 选项卡4-标签1-ui
    def tag_4_1(self, c):
        # 创建 检查框
        self.is_get_forward_requests_box = JCheckBox(
            u'转发GET请求', ForwardRequestsConfig.IS_GET_FORWARD_REQUESTS)
        self.setFontBold(self.is_get_forward_requests_box)
        self.is_get_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.white_list_http_method_settings.add(
            self.is_get_forward_requests_box, c)

    # 选项卡4-标签2-ui
    def tag_4_2(self, c):
        # 创建 检查框
        self.is_post_forward_requests_box = JCheckBox(
            u'转发POST请求', ForwardRequestsConfig.IS_POST_FORWARD_REQUESTS)
        self.setFontBold(self.is_post_forward_requests_box)
        self.is_post_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.white_list_http_method_settings.add(
            self.is_post_forward_requests_box, c)

    # 选项卡4-标签3-ui
    def tag_4_3(self, c):
        # 创建 检查框
        self.is_put_forward_requests_box = JCheckBox(
            u'转发PUT请求', ForwardRequestsConfig.IS_PUT_FORWARD_REQUESTS)
        self.setFontBold(self.is_put_forward_requests_box)
        self.is_put_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.white_list_http_method_settings.add(
            self.is_put_forward_requests_box, c)

    # 选项卡4-标签4-ui
    def tag_4_4(self, c):
        # 创建 检查框
        self.is_patch_forward_requests_box = JCheckBox(
            u'转发PATCH请求', ForwardRequestsConfig.IS_PATCH_FORWARD_REQUESTS)
        self.setFontBold(self.is_patch_forward_requests_box)
        self.is_patch_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.white_list_http_method_settings.add(
            self.is_patch_forward_requests_box, c)

    # 选项卡4-标签5-ui
    def tag_4_5(self, c):
        # 创建 检查框
        self.is_delete_forward_requests_box = JCheckBox(
            u'转发DELETE请求', ForwardRequestsConfig.IS_DELETE_FORWARD_REQUESTS)
        self.setFontBold(self.is_delete_forward_requests_box)
        self.is_delete_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 5
        self.white_list_http_method_settings.add(
            self.is_delete_forward_requests_box, c)

    # 选项卡4-标签6-ui
    def tag_4_6(self, c):
        # 创建 检查框
        self.is_copy_forward_requests_box = JCheckBox(
            u'转发COPY请求', ForwardRequestsConfig.IS_COPY_FORWARD_REQUESTS)
        self.setFontBold(self.is_copy_forward_requests_box)
        self.is_copy_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 6
        self.white_list_http_method_settings.add(
            self.is_copy_forward_requests_box, c)

    # 选项卡4-标签7-ui
    def tag_4_7(self, c):
        # 创建 检查框
        self.is_head_forward_requests_box = JCheckBox(
            u'转发HEAD请求', ForwardRequestsConfig.IS_HEAD_FORWARD_REQUESTS)
        self.setFontBold(self.is_head_forward_requests_box)
        self.is_head_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 7
        self.white_list_http_method_settings.add(
            self.is_head_forward_requests_box, c)

    # 选项卡4-标签8-ui
    def tag_4_8(self, c):
        # 创建 检查框
        self.is_options_forward_requests_box = JCheckBox(
            u'转发OPTIONS请求', ForwardRequestsConfig.IS_OPTIONS_FORWARD_REQUESTS)
        self.setFontBold(self.is_options_forward_requests_box)
        self.is_options_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 8
        self.white_list_http_method_settings.add(
            self.is_options_forward_requests_box, c)

    # 选项卡4-标签9-ui
    def tag_4_9(self, c):
        # 创建 检查框
        self.is_link_forward_requests_box = JCheckBox(
            u'转发LINK请求', ForwardRequestsConfig.IS_LINK_FORWARD_REQUESTS)
        self.setFontBold(self.is_link_forward_requests_box)
        self.is_link_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 9
        self.white_list_http_method_settings.add(
            self.is_link_forward_requests_box, c)

    # 选项卡4-标签10-ui
    def tag_4_10(self, c):
        # 创建 检查框
        self.is_unlink_forward_requests_box = JCheckBox(
            u'转发UNLINK请求', ForwardRequestsConfig.IS_UNLINK_FORWARD_REQUESTS)
        self.setFontBold(self.is_unlink_forward_requests_box)
        self.is_unlink_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 10
        self.white_list_http_method_settings.add(
            self.is_unlink_forward_requests_box, c)

    # 选项卡4-标签11-ui
    def tag_4_11(self, c):
        # 创建 检查框
        self.is_purge_forward_requests_box = JCheckBox(
            u'转发PURGE请求', ForwardRequestsConfig.IS_PURGE_FORWARD_REQUESTS)
        self.setFontBold(self.is_purge_forward_requests_box)
        self.is_purge_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 11
        self.white_list_http_method_settings.add(
            self.is_purge_forward_requests_box, c)

    # 选项卡4-标签12-ui
    def tag_4_12(self, c):
        # 创建 检查框
        self.is_lock_forward_requests_box = JCheckBox(
            u'转发LOCK请求', ForwardRequestsConfig.IS_LOCK_FORWARD_REQUESTS)
        self.setFontBold(self.is_lock_forward_requests_box)
        self.is_lock_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 12
        self.white_list_http_method_settings.add(
            self.is_lock_forward_requests_box, c)

    # 选项卡4-标签13-ui
    def tag_4_13(self, c):
        # 创建 检查框
        self.is_unlock_forward_requests_box = JCheckBox(
            u'转发UNLOCK请求', ForwardRequestsConfig.IS_UNLOCK_FORWARD_REQUESTS)
        self.setFontBold(self.is_unlock_forward_requests_box)
        self.is_unlock_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 13
        self.white_list_http_method_settings.add(
            self.is_unlock_forward_requests_box, c)

    # 选项卡4-标签14-ui
    def tag_4_14(self, c):
        # 创建 检查框
        self.is_propfind_forward_requests_box = JCheckBox(
            u'转发PROPFIND请求',
            ForwardRequestsConfig.IS_PROPFIND_FORWARD_REQUESTS)
        self.setFontBold(self.is_propfind_forward_requests_box)
        self.is_propfind_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 14
        self.white_list_http_method_settings.add(
            self.is_propfind_forward_requests_box, c)

    # 选项卡4-标签15-ui
    def tag_4_15(self, c):
        # 创建 检查框
        self.is_view_forward_requests_box = JCheckBox(
            u'转发VIEW请求', ForwardRequestsConfig.IS_VIEW_FORWARD_REQUESTS)
        self.setFontBold(self.is_view_forward_requests_box)
        self.is_view_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 15
        self.white_list_http_method_settings.add(
            self.is_view_forward_requests_box, c)

    # 获取白名单http方法
    def getWhiteListHttpMethod(self):
        l = []
        if self.is_get_forward_requests_box.isSelected():
            l.append('GET')
        if self.is_post_forward_requests_box.isSelected():
            l.append('POST')
        if self.is_put_forward_requests_box.isSelected():
            l.append('PUT')
        if self.is_patch_forward_requests_box.isSelected():
            l.append('PATCH')
        if self.is_delete_forward_requests_box.isSelected():
            l.append('DELETE')
        if self.is_copy_forward_requests_box.isSelected():
            l.append('COPY')
        if self.is_head_forward_requests_box.isSelected():
            l.append('HEAD')
        if self.is_options_forward_requests_box.isSelected():
            l.append('OPTIONS')
        if self.is_link_forward_requests_box.isSelected():
            l.append('LINK')
        if self.is_unlink_forward_requests_box.isSelected():
            l.append('UNLINK')
        if self.is_purge_forward_requests_box.isSelected():
            l.append('PURGE')
        if self.is_lock_forward_requests_box.isSelected():
            l.append('LOCK')
        if self.is_unlock_forward_requests_box.isSelected():
            l.append('UNLOCK')
        if self.is_propfind_forward_requests_box.isSelected():
            l.append('PROPFIND')
        if self.is_view_forward_requests_box.isSelected():
            l.append('VIEW')
        return l
Пример #47
0
class BootstrapPane():
    def __init__(self):
        self.panel = JPanel()
        self.panel.setLayout(BorderLayout())

        self.pane = JPanel()
        self.initUI()

    def initUI(self):

        layout = GroupLayout(self.pane)
        self.pane.setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)

        bc = settings.getBool("boot.use", False)
        self.useBs = JCheckBox("Use bootstrap", bc)
        binLabel = JLabel("Bootstrap file: ")
        self.binTxt = JTextField()
        self.binTxt.text = settings.getString("boot.path", "")
        self.binBtn = JButton("Load", actionPerformed=mplab_chooseBootstrap)

        entryLabel = JLabel("Bootstrap entry address (if bin): ")
        self.entryTxt = JTextField()
        self.entryTxt.text = settings.getString("boot.entry_adr", "")

        prjLabel = JLabel("Bootstrap project: ")
        self.prjTxt = JTextField()
        self.prjTxt.text = settings.getString("boot.prj", "")

        loadLabel = JLabel("Bootstrap load address (if bin): ")

        self.loadTxt = JTextField()
        self.loadTxt.text = settings.getString("boot.load_adr", "")

        layout.setHorizontalGroup(layout.createSequentialGroup().addGroup(
            layout.createParallelGroup().addComponent(
                self.useBs).addComponent(prjLabel).addComponent(binLabel).
            addComponent(entryLabel).addComponent(loadLabel)).addGroup(
                layout.createParallelGroup()
                #                .addComponent(self.useBs)
                .addComponent(self.prjTxt).addComponent(
                    self.binTxt).addComponent(self.entryTxt).addComponent(
                        self.loadTxt)).addGroup(
                            layout.createParallelGroup().addComponent(
                                self.binBtn)))

        layout.setVerticalGroup(layout.createSequentialGroup().addGroup(
            layout.createParallelGroup().addComponent(self.useBs)
        ).addGroup(
            layout.createParallelGroup().addComponent(prjLabel).addComponent(
                self.prjTxt, GroupLayout.PREFERRED_SIZE,
                GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        ).addGroup(
            layout.createParallelGroup().addComponent(binLabel).addComponent(
                self.binTxt, GroupLayout.PREFERRED_SIZE,
                GroupLayout.DEFAULT_SIZE,
                GroupLayout.PREFERRED_SIZE).addComponent(self.binBtn)
        ).addGroup(
            layout.createParallelGroup().addComponent(entryLabel).addComponent(
                self.entryTxt, GroupLayout.PREFERRED_SIZE,
                GroupLayout.DEFAULT_SIZE,
                GroupLayout.PREFERRED_SIZE)).addGroup(
                    layout.createParallelGroup().addComponent(
                        loadLabel).addComponent(self.loadTxt,
                                                GroupLayout.PREFERRED_SIZE,
                                                GroupLayout.DEFAULT_SIZE,
                                                GroupLayout.PREFERRED_SIZE)))
        self.panel.add(self.pane, BorderLayout.CENTER)

    def getPanel(self):
        return self.panel
Пример #48
0
class BurpExtender(IBurpExtender, ITab):
    socket_time_out = 3

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

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

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

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

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

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

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

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

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

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

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

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

        self.messageField = JTextArea('["action", {"add": "relay"}, [{"message": {"conversation": "WhatsApp Protocol Decryption!"}, "participant": "*****@*****.**", "messageTimestamp": "1565193325", "key": {"fromMe": false, "remoteJid": "*****@*****.**", "id": "78CECC5019E81B84B64ED2F6A57217AK"}, "status": "ERROR"}]]', 5, 90)
        self.messageField.setLineWrap(True)
        self.messageField.setToolTipText("Incoming traffic is from burp suite websocket, The outgoing traffic is the list from aesCbcEncrypt")

        self.messageTag = JLabel("Message Tag:")
        self.messageTagField = JTextField("", 80)
        self.messageTagField.setToolTipText("Copy the message tag from WebSocket it's the text until first ',' ")
        self.messageTagFieldButton = JButton("Update Tag", actionPerformed=self.performUpdateTag)

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

        self.messageTagPanel = JPanel()
        self.messageTagPanel.add(self.messageTag)
        self.messageTagPanel.add(self.messageTagField)
        self.messageTagPanel.add(self.messageTagFieldButton)

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

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

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

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

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

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

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

        c = GridBagConstraints()

        c.ipadx = 0
        c.ipady = 0

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

        c.anchor = GridBagConstraints.NORTHWEST

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

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

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

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

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

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

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

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

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

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

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

    def performUpdateTag(self, e=None):

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

        clientData = json.dumps({"action": "tagUpdate",
                                 "data": {
                                     "msg_tag": self.messageTagField.getText()
                                    }
                                 })

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

    def performAction(self, e=None):

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

        self.data = self.messageField.getText()

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

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

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

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

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

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

            except socket.timeout:
                pass

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

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

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

            except socket.timeout:
                pass

        self.client.close()


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

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

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

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

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

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

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

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

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

        self.client.close()

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

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

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

    def getUiComponent(self):
        return self.tab
Пример #49
0
    def createButtonPane(self):
        """Create AWT window panel for buttons"""
        self._button_listener = TypeDefinitionButtonListener(self)

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

        panel.add(Box.createRigidArea(Dimension(0, 5)))
        panel.add(self.createButton("Add", "new-type", "Create a new type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Edit", "edit-type", "Edit the selected type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Rename", "rename-type",
                              "Rename the selected type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Remove", "delete-type",
                              "Delete all selected types"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton(
                "Save All Types To File",
                "save-types",
                "Save all known types as JSON to a file",
            ))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Load All Types From File", "load-types",
                              "Load types from JSON file"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton(
                "Export All types As .proto",
                "export-proto",
                "Export all types as .proto",
            ))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Import .proto", "import-proto",
                              "Import types from a .proto file"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        return panel
Пример #50
0
class ConfigPanel(JFrame):

    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()
        

    def __init__(self, config=dict()):
        super(ConfigPanel, self).__init__()
        self.setTitle('SSNAKE setup')
        self.config = config.copy()
        self.param_list = ['SSNAKEPATH', 'DEFAULT']
        self.actions_list = {'SSNAKEPATH': self.set_ssnake_path}
        self.initUI(self.config)

    def update_config_from_UI(self):
        config = dict()
        for keyUI in self.config_item_dict.keys():
            key =  self.config_item_dict[keyUI]['JB'].getText()
            config[key] = dict()
            for param in self.config_item_dict[keyUI].keys():
                if param not in self.param_list:
                    continue
                if param == 'DEFAULT':
                    config[key][param] = self.config_item_dict[keyUI][param]['JRB'].isSelected()
                else:
                    config[key][param] = self.config_item_dict[keyUI][param]['JB'].getText()
        self.config = config
        print self.config

    def add_entry(self, event):
        # get key, 
        new_version = dict()
        dummyJB = JButton()
        ConfigPanel.SetKey(dummyJB)
        key = dummyJB.getText()
        del dummyJB
        if key == '':
            return

        ssnake_path = select_ssnake_path()
        if ssnake_path is None:
            return
        new_version['SSNAKEPATH'] = ssnake_path
        new_version['DEFAULT'] = False
        self.add_UI_entry(key, new_version)
        self.revalidate()
        
    def remove_entry(self,event):
        selectedRB = None
        for i in  self.select_key_rb_group.getElements():
            if i.isSelected():
                selectedRB = i
                break
        if selectedRB is None:
            return
        self.select_key_rb_group.remove(selectedRB)
        key = self.hash4keys[selectedRB]
        self.select_default_rb_group.remove(self.config_item_dict[key]['DEFAULT']['JRB'])
        self.panelEntries.remove(self.config_item_dict[key]['JP'])
        self.revalidate()
        del self.config_item_dict[key]
        self.pack()

    def save_config(self,event):
        self.update_config_from_UI()
        write_config_file(self.config)
        self.dispose()

    def set_ssnake_path(self, event):
        button = event.getSource()
        old_path = button.getText()
        path = select_ssnake_path(defaultFile=old_path)
        if path is None:
            return
        button.setText(path)

        
    def set_key(self, event):
        button = event.getSource()
        SK = ConfigPanel.SetKey(event.getSource())

    def add_UI_entry(self,key, dico=dict()):
        UI_key_dict = dict()
        UI_key_dict['JP'] = JPanel()
        UI_key_dict['JP'].setLayout(BoxLayout(UI_key_dict['JP'], BoxLayout.X_AXIS))
        UI_key_dict['JRB'] = JRadioButton()
        self.select_key_rb_group.add(UI_key_dict['JRB'])
        self.hash4keys[UI_key_dict['JRB']] = key
        UI_key_dict['JB'] = JButton(key, actionPerformed=self.set_key)
        UI_key_dict['JB'].setPreferredSize(Dimension(100,25))
        UI_key_dict['JPP'] = JPanel()

        UI_key_dict['JP'].add(UI_key_dict['JRB'])
        UI_key_dict['JP'].add(UI_key_dict['JB'])
        UI_key_dict['JP'].add(Box.createRigidArea(Dimension(15, 0)))
        UI_key_dict['JP'].add(UI_key_dict['JPP'])
        UI_key_dict['JPP'].setLayout(BoxLayout(UI_key_dict['JPP'], BoxLayout.Y_AXIS))
        self.panelEntries.add(UI_key_dict['JP'])
        for param in self.param_list:
            if param not in dico.keys(): continue
            if param == 'DEFAULT':
                UI_key_dict[param] = {'JP':JPanel(), 'JRB': JRadioButton('is Default')}
                UI_key_dict[param]['JP'].setLayout(BoxLayout(
                                    UI_key_dict[param]['JP'], BoxLayout.X_AXIS))
                UI_key_dict[param]['JP'].add(UI_key_dict[param]['JRB'])
                UI_key_dict[param]['JP'].add(Box.createHorizontalGlue())
                self.select_default_rb_group.add(UI_key_dict[param]['JRB'])
                UI_key_dict['JPP'].add(UI_key_dict[param]['JP'])
                UI_key_dict[param]['JRB'].setSelected(dico[param])
                self.hash4keys[UI_key_dict[param]['JRB']] = key
                continue
            UI_key_dict[param] = { 'JP':JPanel(), 'JL': JLabel(param+": "), 
                                 'JB': JButton(dico[param]) }
            self.hash4keys[UI_key_dict[param]['JB']] = key
            UI_key_dict[param]['JL'].setPreferredSize(Dimension(100,25)) 
            UI_key_dict[param]['JB'].actionPerformed = self.actions_list[param] 
            UI_key_dict[param]['JP'].setLayout(BoxLayout(UI_key_dict[param]['JP'], BoxLayout.X_AXIS))
            UI_key_dict[param]['JP'].add(UI_key_dict[param]['JL'])
            UI_key_dict[param]['JP'].add(UI_key_dict[param]['JB'])
            UI_key_dict[param]['JP'].add(Box.createHorizontalGlue())
            UI_key_dict['JPP'].add(UI_key_dict[param]['JP'])
        UI_key_dict['JPP'].add(Box.createRigidArea(Dimension(0, 20)))
        self.config_item_dict[key]=UI_key_dict
        self.pack()
        pass

    def initUI(self, config):
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))
        self.entries = config.keys()
        self.hash4keys = dict()

        self.panelEntries = JPanel()
        self.panelEntries.setLayout(BoxLayout(self.panelEntries,BoxLayout.Y_AXIS))
        self.add(self.panelEntries)

        #buttons
        self.panelButtons = JPanel()
        self.panelButtons.setLayout(BoxLayout(self.panelButtons,BoxLayout.X_AXIS))
        #'Configuration list:')
        self.addB = JButton('Add')
        self.addB.actionPerformed = self.add_entry
        self.removeB = JButton('Remove')
        self.removeB.actionPerformed = self.remove_entry
        self.saveB = JButton('Save')
        self.saveB.actionPerformed = self.save_config
        # pack buttons
        self.add(self.panelButtons)
        self.panelButtons.add(self.addB)
        self.panelButtons.add(self.removeB)
        self.panelButtons.add(self.saveB)

        self.config_item_dict = {}
        self.select_key_rb_group = ButtonGroup()
        self.select_default_rb_group = ButtonGroup()
        for key in self.entries:
            if key == 'default':
                continue
            self.add_UI_entry(key, config[key])
        self.pack()
        self.setLocation(150,150)

        self.setVisible(True)
Пример #51
0
class TypeDefinitionTab(burp.ITab):
    """Implements an interface for editing known message type definitions."""
    def __init__(self, extension, burp_callbacks):
        self._burp_callbacks = burp_callbacks
        self._extension = extension

        self._type_list_component = JList(extension.known_message_model)
        self._type_list_component.setSelectionMode(
            ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)

        self._component = JPanel()
        self._component.setLayout(BoxLayout(self._component, BoxLayout.Y_AXIS))

        splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        splitPane.setRightComponent(JScrollPane(self._type_list_component))
        splitPane.setLeftComponent(self.createButtonPane())
        splitPane.setResizeWeight(0.03)
        splitPane.setMaximumSize(Dimension(1000, 1000))

        self._component.add(splitPane)
        self._component.add(Box.createVerticalGlue())
        self._component.setBorder(EmptyBorder(10, 10, 10, 10))

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

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

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

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

        panel.add(Box.createRigidArea(Dimension(0, 5)))
        panel.add(self.createButton("Add", "new-type", "Create a new type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Edit", "edit-type", "Edit the selected type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Rename", "rename-type",
                              "Rename the selected type"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Remove", "delete-type",
                              "Delete all selected types"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton(
                "Save All Types To File",
                "save-types",
                "Save all known types as JSON to a file",
            ))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Load All Types From File", "load-types",
                              "Load types from JSON file"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton(
                "Export All types As .proto",
                "export-proto",
                "Export all types as .proto",
            ))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        panel.add(
            self.createButton("Import .proto", "import-proto",
                              "Import types from a .proto file"))
        panel.add(Box.createRigidArea(Dimension(0, 3)))
        return panel

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

    def create_save_callback(self, name):
        """Generate a callback for when the save button inside an opened type
        editor window is saved. Saves the type and tells the list to
        refresh.
        """
        def save_callback(typedef):
            """Save typedef and update list for a given message name"""
            if name not in default_config.known_types:
                self._extension.known_message_model.addElement(name)

            default_config.known_types[name] = typedef

        return save_callback

    def add_typedef(self):
        type_name = JOptionPane.showInputDialog("Enter new name")

        # Error out if already defined
        if type_name in default_config.known_types:
            JOptionPane.showMessageDialog(
                self._component,
                'Message type "%s" already exists' % type_name,
            )
            return

        self._extension.open_typedef_editor(
            {}, self.create_save_callback(type_name))

    def edit_typedef(self):
        list_component = self._type_list_component
        if list_component.isSelectionEmpty():
            return

        type_name = list_component.getSelectedValue()
        message_type = default_config.known_types[type_name]

        self._extension.open_typedef_editor(
            sort_typedef(message_type), self.create_save_callback(type_name))
Пример #52
0
class ScriptTabbedPane(JTabbedPane):

    EMPTY_SCRIPT_TEXT = '''<html><body>
<div style="font-size: 16pt;text-align:center">
You have no Python scripts created.<br/> Please use the add tab (+) button to create a new Python script.
</div></body></html>'''

    def __init__(self, extender, callbacks, helpers, scripts):
        super(ScriptTabbedPane, self).__init__()
        self.scripts = scripts
        self.extender = extender
        self.callbacks = callbacks
        self.helpers = helpers

        self.addChangeListener(ScriptTabbedPane.TabsStateChanged())
        self.scripts.add_listener(self)
        self.create_add_tab()

    def create_add_tab(self):
        self.add_tab = JButton("+", actionPerformed=self.add_clicked)
        self.add_tab.font = Font('Monospaced', Font.PLAIN, 18)
        self.add_tab.contentAreaFilled = False
        self.add_tab.border = None

        self.emptyTab = JPanel(BorderLayout())
        emptyScriptLabel = JLabel(ScriptTabbedPane.EMPTY_SCRIPT_TEXT,
                                  SwingConstants.CENTER)
        emptyScriptLabel.putClientProperty("html.disable", None)
        self.emptyTab.add(emptyScriptLabel, BorderLayout.CENTER)

        self.addTab(None, self.emptyTab)
        self.setTabComponentAt(0, self.add_tab)

    def add_clicked(self, event):
        idx = self.tabCount - 1
        title = 'New Script {}'.format(idx + 1)
        script = Script(self.extender, self.callbacks, self.helpers, title)
        self.scripts.add(script)

    def create_script_tab(self, script, idx):
        new_tab = ScriptTabComponent(script)
        new_tab.tabbed_pane = self
        new_tab.addCloseListener(
            ScriptTabbedPane.ScriptTabCloseListener(self, self.scripts,
                                                    script))
        new_tab.addTitleChangedListener(
            ScriptTabbedPane.ScriptTabTabTitleChangedListener(script))
        new_panel = ScriptPanel(script, self.callbacks)
        self.add(new_panel, idx)
        self.setTabComponentAt(idx, new_tab)
        self.selectedIndex = idx

    def collection_changed(self, collection, type, script):
        if type == ObservableCollection.ITEM_ADDED:
            idx = self.tabCount - 1
            self.create_script_tab(script, idx)

    class ScriptTabCloseListener(TabComponentCloseListener):
        def __init__(self, tabbedpane, scripts, script):
            self.tabbed_pane = tabbedpane
            self.scripts = scripts
            self.script = script

        def tabClose(self, event):
            result = JOptionPane.showConfirmDialog(
                None, 'Are you sure you want to close \'{}\' ?'.format(
                    event.source.text), "Close Tab", JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE)
            if result == JOptionPane.YES_OPTION:
                idx = self.tabbed_pane.indexOfTabComponent(event.source)
                self.tabbed_pane.remove(idx)
                self.scripts.remove(self.script)

    class ScriptTabTabTitleChangedListener(TabComponentTitleChangedListener):
        def __init__(self, script):
            self.script = script

        def titleChanged(self, event):
            self.script.title = event.getTitle()

    class TabsStateChanged(ChangeListener):
        def stateChanged(self, event):
            # prevents the add tab from being selected apart from when there are no other tabs created (i.e. starting from fresh)
            # instead the tab next the add tab is selected
            tabbed_pane = event.source
            if tabbed_pane.tabCount > 1 and tabbed_pane.selectedIndex == tabbed_pane.tabCount - 1:
                tabbed_pane.selectedIndex = tabbed_pane.tabCount - 2