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)
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
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
def __init__(self): # Panel for Measurements self.setLayout(BorderLayout()) # PAGE_START ''' show group/dataset names in the list (component/variable) names ''' self.cbfilemeasOut = JComboBox([]) bfilemeasOut= JButton('Measurements', actionPerformed= self.loadMeasOut) p3= JPanel() p3.setLayout(GridLayout(1,2)) p3.add(self.cbfilemeasOut) p3.add(bfilemeasOut) self.add(p3, BorderLayout.PAGE_START) # LINE_START root = DefaultMutableTreeNode('VarMeasurements') self.tree = JTree(root) scrollPane = JScrollPane() # add a scrollbar to the viewport scrollPane.setPreferredSize(Dimension(230,320)) scrollPane.getViewport().setView((self.tree)) p4 = JPanel() p4.add(scrollPane) self.add(p4, BorderLayout.LINE_START) # CENTER ''' represent a signal with matplot lib in textarea places ''' graficMeas= JTextArea() self.add(graficMeas, BorderLayout.CENTER)
def __init__(self, label=None): JPanel.__init__(self) self.addMouseListener(self) self.addMouseWheelListener(self) self.addMouseMotionListener(self) self.hover = False self.min_width = 20 self.min_height = 20 self.resize_border = 20 self.max_show_dim = 30 # The maximum number of display dimensions to show in the popup menu self.setSize(100, 50) self.border = self.default_border self.popup = JPopupMenu() self.popup.add(JMenuItem('hide', actionPerformed=self.hideme)) self.show_label = False self.label = label self.label_offset = 0 if self.label is not None: self.show_label = True self.popup.add(JPopupMenu.Separator()) self.popup_label = JCheckBoxMenuItem('label', self.show_label, actionPerformed=self.toggle_label) self.popup.add(self.popup_label) self.label_height = 15 self.update_label() else: self.label_height = 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
def init(self): global exampleList self.thinFont = Font("Dialog", 0, 10) self.pane = self.getContentPane() self.examples = exampleList.keys() self.examples.sort() self.exampleSelector = JList(self.examples, valueChanged=self.valueChanged) self.exampleSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) self.exampleSelector.setLayoutOrientation(JList.VERTICAL) self.exampleSelector.setPreferredSize(Dimension(150,500)) self.exampleSelector.setBackground(Color(0.95, 0.95, 0.98)) self.exampleSelector.setFont(self.thinFont) self.centerPanel = JPanel(BorderLayout()) self.canvas = GraphCanvas() self.canvas.setApplet(self) self.buttonRow = JPanel(FlowLayout()) self.backButton = JButton("<", actionPerformed = self.backAction) self.backButton.setFont(self.thinFont) self.continueButton = JButton("continue >", actionPerformed=self.continueAction) self.continueButton.setFont(self.thinFont) self.scaleGroup = ButtonGroup() self.linearButton = JRadioButton("linear scale", actionPerformed=self.linearAction) self.linearButton.setSelected(True) self.linearButton.setFont(self.thinFont) self.logarithmicButton = JRadioButton("logarithmic scale", actionPerformed=self.logarithmicAction) self.logarithmicButton.setFont(self.thinFont) self.aboutButton = JButton("About...", actionPerformed=self.aboutAction) self.aboutButton.setFont(self.thinFont) self.scaleGroup.add(self.linearButton) self.scaleGroup.add(self.logarithmicButton) self.buttonRow.add(self.backButton) self.buttonRow.add(self.continueButton) self.buttonRow.add(JLabel(" "*5)) self.buttonRow.add(self.linearButton) self.buttonRow.add(self.logarithmicButton) self.buttonRow.add(JLabel(" "*20)); self.buttonRow.add(self.aboutButton) self.centerPanel.add(self.canvas, BorderLayout.CENTER) self.centerPanel.add(self.buttonRow, BorderLayout.PAGE_END) self.helpText = JTextPane() self.helpText.setBackground(Color(1.0, 1.0, 0.5)) self.helpText.setPreferredSize(Dimension(800,80)) self.helpText.setText(re_sub("[ \\n]+", " ", """ Please select one of the examples in the list on the left! """)) self.pane.add(self.exampleSelector, BorderLayout.LINE_START) self.pane.add(self.centerPanel, BorderLayout.CENTER) self.pane.add(self.helpText, BorderLayout.PAGE_END) self.graph = None self.simulation = None self.touched = "" self.selected = "" self.gfxDriver = None
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()
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)
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
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)
def p_build_ui(self, event): """ Adds a list of checkboxes, one for each loaded plugin to the Selct plugins window """ if not self.loaded_p_list: self.update_scroll("[!!] No plugins loaded!") return scroll_pane = JScrollPane() scroll_pane.setPreferredSize(Dimension(200, 250)) check_frame = JPanel(GridBagLayout()) constraints = GridBagConstraints() constraints.fill = GridBagConstraints.HORIZONTAL constraints.gridy = 0 constraints.anchor = GridBagConstraints.FIRST_LINE_START for plug in self.loaded_p_list: check_frame.add(JCheckBox(plug.get_name(), plug.enabled, actionPerformed=self.update_box), constraints) constraints.gridy += 1 vport = JViewport() vport.setView(check_frame) scroll_pane.setViewport(vport) self.window.contentPane.add(scroll_pane) self.window.pack() self.window.setVisible(True)
def __init__(self, employees, overview_listener): JPanel.__init__(self, layout=BorderLayout()) self._listener = overview_listener self._employee_list = self._create_employee_list(employees) new_emp_btn = self._create_new_employee_button() self.add(self._employee_list.widget, BorderLayout.PAGE_START) self.add(new_emp_btn, BorderLayout.PAGE_END)
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
def __init__(self): JPanel.__init__(self) self.myGL = GL() self.myGLU = GLU(self.myGL) self.myAUX = GLAUX(self.myGL) self.myGLUT = GLUT(self.myGL) self.myAUX.auxInitPosition(0, 0, 208, 227) self.myAUX.auxInitWindow(self) myGL = self.myGL myGL.glClearColor(0.0, 0.0, 0.0, 0.0) myGL.glEnable(GL.GL_DEPTH_TEST) myGL.glShadeModel(GL.GL_SMOOTH) myGL.glEnable(GL.GL_TEXTURE_GEN_S) #myGL.glEnable(GL.GL_TEXTURE_1D) myGL.glEnable(GL.GL_CULL_FACE) myGL.glEnable(GL.GL_LIGHTING) myGL.glEnable(GL.GL_LIGHT0) myGL.glEnable(GL.GL_AUTO_NORMAL) myGL.glEnable(GL.GL_NORMALIZE) myGL.glFrontFace(GL.GL_CW) myGL.glCullFace(GL.GL_BACK) myGL.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, 64.0) self.componentResized = self.OnComponentResized
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
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
def build_buttons_panel(self): ''' Builds the buttons panel to save or cancel changes. TODO: Reset button to reset to defaults? ''' panel = JPanel(FlowLayout()) panel.add(JButton('Cancel', actionPerformed=self.cancel)) panel.add(JButton('Save', actionPerformed=self.save)) return panel
def addObject(self, objectID): """ Creates new empty JPanel that'll contain the model for one object in the ATF file. """ objectPanel = JPanel() objectPanel.setLayout(BoxLayout(objectPanel, BoxLayout.PAGE_AXIS)) self.objectTabs[objectID] = objectPanel
def build_keystrokes_panel(self): ''' Create the panel that'll go in the Keystrokes tab. This should contain options for choosing which keystrokes are to be assigned to which actions. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel
def build_languages_panel(self): ''' Create the panel that'll go in the Languages tab. This should contain options for choosing which is the list of languages that can be included from the new ATF window and their abbrv. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel
def paint(self, g): # due to bug, cannot call super() JPanel.paint(self, g) if self.inGame: self.drawObjects(g) else: self.gameOver(g)
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)
def __init__(self, browser, valueType): JPanel.__init__(self) self.browser = browser self.valueType = valueType self.internalValueChanging = True self.basicInitialization() self.makeComponents() self.originalValueBytes = "" self.valueType = valueType self.internalValueChanging = False
def build_projects_panel(self): ''' Create the panel that'll go in the Projects tab. This should contain the list of preferred projects and a means to select which is the preferred default. ''' panel = JPanel() label = JLabel("Coming soon...") panel.add(label, BorderLayout.CENTER) return panel
def build_buttons_row(self): ''' Add OK/Cancel/Blank buttons. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. create_button = JButton('Create template', actionPerformed=self.create_template) leave_button = JButton('Leave blank', actionPerformed=self.blank) cancel_button = JButton('Cancel', actionPerformed=self.cancel) panel.add(create_button) panel.add(leave_button) panel.add(cancel_button) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, create_button, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, create_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, leave_button, 5, SpringLayout.EAST, create_button) layout.putConstraint(SpringLayout.NORTH, leave_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, cancel_button, 5, SpringLayout.EAST, leave_button) layout.putConstraint(SpringLayout.NORTH, cancel_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, cancel_button) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, cancel_button) # Add this to NewAtf JFrame return panel
def 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)
def __init__(self, cattrs): #JDialog.__init__(self,"Curve Attribute Editor") #("Curve Attribute Editor") if cattrs == None or len(cattrs) == 0: raise "No curve attributes specified" self.attrs = cattrs self.cpanel = EditCurveAttr(cattrs[0]) pane = self.getContentPane() pane.setLayout(BorderLayout()) x = map(lambda x: x+1,range(len(self.attrs))) self.curveBox = JComboBox(x) self.curveBox.setBorder(BorderFactory.createTitledBorder("Curve #")) self.curveBox.setSelectedItem(0) class CListener(ItemListener): def __init__(self,cbox,cpanel,cattrs): self.cbox = cbox self.cpanel = cpanel self.attrs = cattrs def itemStateChanged(self, evt): crvNo = self.cbox.getSelectedItem() self.cpanel.update() self.cpanel.setAttribute(self.attrs[crvNo-1]) self.curveBox.addItemListener(CListener(self.curveBox, self.cpanel,self.attrs)) okBtn = JButton("OK",actionPerformed=self.ok_action) cancelBtn = JButton("Cancel",actionPerformed=self.cancel_action) btnPanel = JPanel() btnPanel.setLayout(GridLayout(1,3)) btnPanel.add(self.curveBox) btnPanel.add(okBtn) btnPanel.add(cancelBtn) pane.add(self.cpanel,BorderLayout.CENTER) pane.add(btnPanel, BorderLayout.SOUTH) self.setLocation(100,100) self.pack() self.setVisible(1)
def __init__(self, employees): JPanel.__init__(self, preferredSize=(400, 200)) layout = BoxLayout(self, BoxLayout.Y_AXIS) self.setLayout(layout) self._employees = employees employees.add_change_listener(self) self._create_status_label() self._create_name_editor() self._create_start_date_editor() self._create_save_button() self._adding_employee = False
def build_replace_row(self): ''' Builds the replace row. ''' panel = JPanel(FlowLayout()) label = JLabel("Replace: ") panel.add(label) self.replace_field = JTextField(20, actionPerformed=self.find_next) label.setLabelFor(self.replace_field) panel.add(self.replace_field) return panel
def __init__(self): # Setup controls - buttons first self.playButton.preferredSize = self.refreshButton.preferredSize self.playButton.actionCommand = self.PLAY self.playButton.actionPerformed = self.whenButtonClicked self.pauseButton.preferredSize = self.refreshButton.preferredSize self.pauseButton.actionCommand = self.PAUSE self.pauseButton.actionPerformed = self.whenButtonClicked self.stopButton.preferredSize = self.refreshButton.preferredSize self.stopButton.actionCommand = self.STOP self.stopButton.actionPerformed = self.whenButtonClicked self.refreshButton.actionCommand = self.REFRESH self.refreshButton.actionPerformed = self.whenButtonClicked # Now combobox and text field self.sourceCombo.itemStateChanged = self.whenSourceChanged self.updateSourcesList() self.rangeSpinner.stateChanged = self.whenRangeChanged # Now sliders ticksMajor = int(self.posMinMax / 4) ticksMinor = int(ticksMajor / 5) labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Left")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("Right")) self.positionXSlider.labelTable = labels self.positionXSlider.minimum = -self.posMinMax self.positionXSlider.maximum = self.posMinMax self.positionXSlider.majorTickSpacing = ticksMajor self.positionXSlider.minorTickSpacing = ticksMinor self.positionXSlider.paintTicks = True self.positionXSlider.paintLabels = True self.positionXSlider.snapToTicks = True self.positionXSlider.value = 0 self.positionXSlider.stateChanged = self.whenSliderXChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Behind")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("In-front")) self.positionYSlider.labelTable = labels self.positionYSlider.minimum = -self.posMinMax self.positionYSlider.maximum = self.posMinMax self.positionYSlider.majorTickSpacing = ticksMajor self.positionYSlider.minorTickSpacing = ticksMinor self.positionYSlider.paintTicks = True self.positionYSlider.paintLabels = True self.positionYSlider.snapToTicks = True self.positionYSlider.value = 0 self.positionYSlider.orientation = JSlider.VERTICAL self.positionYSlider.stateChanged = self.whenSliderYChanged labels = Hashtable(3) labels.put(-self.posMinMax, JLabel("Below")) labels.put(0, JLabel("Centre")) labels.put(self.posMinMax, JLabel("Above")) self.positionZSlider.labelTable = labels self.positionZSlider.minimum = -self.posMinMax self.positionZSlider.maximum = self.posMinMax self.positionZSlider.majorTickSpacing = ticksMajor self.positionZSlider.minorTickSpacing = ticksMinor self.positionZSlider.paintTicks = True self.positionZSlider.paintLabels = True self.positionZSlider.snapToTicks = True self.positionZSlider.value = 0 self.positionZSlider.orientation = JSlider.VERTICAL self.positionZSlider.stateChanged = self.whenSliderZChanged # Setup frame self.title = "Simple JMRI Audio Player" self.contentPane.layout = BoxLayout(self.contentPane, BoxLayout.Y_AXIS) # Add controls to frame - combo & buttons first p = JPanel(FlowLayout(FlowLayout.LEADING)) p.add(self.sourceCombo) p.add(self.refreshButton) p.add(self.playButton) p.add(self.pauseButton) p.add(self.stopButton) #p.add(JLabel("Range")) #p.add(self.rangeSpinner) self.add(p) self.add(Box.createVerticalGlue()) # Now sliders p = JPanel(FlowLayout(FlowLayout.LEADING)) label = JLabel("Y Position") label.UI = VerticalLabelUI() # Default behaviour is anti-clockwise p.add(label) p.add(self.positionYSlider) p2 = JPanel() p2.layout = BoxLayout(p2, BoxLayout.Y_AXIS) p3 = JPanel() p3.add(JLabel("Range")) p3.add(self.rangeSpinner) p2.add(p3) #p2.add(Box.createVerticalGlue()) p3 = JPanel() p3.layout = BoxLayout(p3, BoxLayout.Y_AXIS) label = JLabel("X Position") label.alignmentX = JLabel.CENTER_ALIGNMENT p3.add(label) p3.add(self.positionXSlider) p2.add(p3) p.add(p2) label = JLabel("Z Position") label.UI = VerticalLabelUI() p.add(label) p.add(self.positionZSlider) self.add(p) # Finally pack and show self.pack() self.show()
def __init__(self): self.panel = JPanel() self.panel.setLayout(BorderLayout()) self.pane = JPanel() self.initUI()
def createButtonPane(self): """Create a new button pane with the type editor window""" self._button_listener = TypeEditorButtonListener(self) panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) panel.add(Box.createRigidArea(Dimension(0, 5))) panel.add( self.createButton("Validate", "validate", "Check if typedef is valid")) panel.add(Box.createRigidArea(Dimension(0, 3))) panel.add(self.createButton("Save", "save", "Save the typedef")) panel.add(Box.createRigidArea(Dimension(0, 3))) panel.add(self.createButton("Reset", "reset", "Reset to original")) panel.add(Box.createRigidArea(Dimension(0, 3))) panel.add(self.createButton("Exit", "exit", "Close window and reset")) panel.add(Box.createRigidArea(Dimension(0, 3))) return panel
class BobGui(JFrame): def __init__(self): super(BobGui, self).__init__('BobPy') # IJ.log('okay?') # print('okay??') self.setLayout(BorderLayout()) self.main_panel = JPanel() # self.main_panel.setLayout(MigLayout('insets 1 10 1 1')) self.main_panel.setLayout(MigLayout()) dir_panel = JPanel() dir_panel.setLayout(BoxLayout(dir_panel, BoxLayout.X_AXIS)) dir_label = JLabel('Experiment Folder:') dir_panel.add(dir_label) self.dir_text_field = JTextField(10) self.dir_text_field.addActionListener( ActionListenerFactory(self, self.text_field_al)) dir_panel.add(self.dir_text_field) dir_button = JButton('open') dir_button.addActionListener( ActionListenerFactory(self, self.choose_dir_al)) dir_panel.add(dir_button) self.main_panel.add(dir_panel, 'wrap, growx, spanx, pushx') add_key_args(self.main_panel, 'close_w', ActionListenerFactory(self, self.close_al), KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) self.add(self.main_panel, BorderLayout.CENTER) self.setPreferredSize(Dimension(650, 600)) self.pack() self.setLocationRelativeTo(None) self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setVisible(True) def show_exper_info(self): chf_panel = self.make_chf_panel() hseg_tree_panel = self.make_hseg_tree_panel() self.split_pane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.split_pane.setOneTouchExpandable(True) self.split_pane.setContinuousLayout(True) self.split_pane.setResizeWeight(0.5) self.split_pane.add(chf_panel) self.split_pane.add(hseg_tree_panel) self.main_panel.add(self.split_pane, 'grow, wrap') # self.log_text = JTextArea() self.main_panel.add(self.log_text, 'grow, wrap') self.log_text.setLineWrap(True) self.log_text.setWrapStyleWord(True) self.revalidate() def make_chf_panel(self): """ chf --> common hseg files """ chf_panel = JPanel() chf_panel.setLayout(MigLayout('insets 0')) chf_files_label = JLabel('Hemisegment cells') chf_files_text = JTextArea( BobGui.archetype_to_str( self.exper.hseg_cell_files_cab().archetype)) chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(chf_files_text, 'grow, wrap') chf_files_label = JLabel('Hemisegment binary image files') chf_files_text = JTextArea( BobGui.archetype_to_str(self.exper.hseg_bin_files_cab().archetype)) chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(chf_files_text, 'grow, wrap') chf_files_label = JLabel('Intensity Image Files') # chf_files_text = JTextArea(BobGui.archetype_to_str(self.exper.hseg_intens_im_files_cab().archetype)) # print(self.exper.hseg_intens_im_files_cab().archetype) # chf_panel.add(chf_files_label, 'growx, wrap') # chf_panel.add(chf_files_text, 'grow, wrap') self.intens_im_boxes = [] intens_im_panel = JPanel() intens_im_panel.setLayout(MigLayout('insets 0')) for poss_im_file in self.exper.hseg_intens_im_files_cab().archetype: self.intens_im_boxes.append(JCheckBox(poss_im_file)) intens_im_panel.add(self.intens_im_boxes[-1], 'wrap') chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(intens_im_panel, 'grow, wrap') mdf_create_button = JButton( 'Create meta_data file from default outline') # mdf_create_button = JButton('<html>Create meta_data file<br>from default outline</html>') mdf_create_button.addActionListener( ActionListenerFactory(self, self.mdf_create_al)) mdf_open_button = JButton('Open existing meta_data file') mdf_open_button.addActionListener( ActionListenerFactory(self, self.mdf_open_al)) # meta_data_file_buttton = JButton('Open/Create meta_data file') # meta_data_file_buttton.addActionListener(ActionListenerFactory(self, self.meta_data_al)) # chf_panel.add(meta_data_file_buttton) chf_panel.add(mdf_create_button, 'wrap') chf_panel.add(mdf_open_button, 'wrap') chf_scroll_pane = JScrollPane() chf_scroll_pane.getViewport().setView(chf_panel) return chf_scroll_pane @staticmethod def archetype_to_str(archetype): at_str = '' for val in archetype: at_str += str(val) + '\n' return at_str def make_hseg_tree_panel(self): root = DefaultMutableTreeNode(self.exper.name) for hseg in self.exper.hsegs(): hseg_node = DefaultMutableTreeNode(hseg.name) root.add(hseg_node) hseg_at_deviations = self.exper.hseg_files_cab( ).archetype_deviations if len(hseg_at_deviations[hseg.name]) > 0: for definer, file_names in hseg_at_deviations[ hseg.name].items(): for file_name in file_names: node_str = definer + ': ' + file_name temp = DefaultMutableTreeNode(node_str) hseg_node.add(temp) hseg_tree = JTree(root) hseg_tree.setCellRenderer(BobPyTreeCellRenderer()) hseg_scroll_pane = JScrollPane() hseg_scroll_pane.getViewport().setView((hseg_tree)) hseg_panel = JPanel(MigLayout('insets 0')) hseg_panel.add(hseg_scroll_pane, 'grow, span, push, wrap') run_button = JButton('Run') run_button.addActionListener(ActionListenerFactory(self, self.run_al)) rerun_button = JButton('Rerun') rerun_button.addActionListener( ActionListenerFactory(self, self.rerun_al)) hseg_panel.add(run_button) hseg_panel.add(rerun_button) return hseg_panel def log(self, text): self.log_text.append(str(text) + '\n') def text_field_al(self, e): # self.dir_path = self.got_exper(self.dir_text_field.getText()) def choose_dir_al(self, e): dc = DirectoryChooser('Choose a bob_py experiment folder') # self.dir_path = dc.getDirectory() # self.dir_text_field.setText(self.dir_path) # self.dir_text_field.setText('blerg') # IJ.log('blerg') # print('boop') self.got_exper(dc.getDirectory()) def close_al(self, e): self.dispatchEvent(WindowEvent(self, WindowEvent.WINDOW_CLOSING)) def run_al(self, e): # dt = br.dtic('Processed experiment {}'.format(self.exper.name)) t = br.tic() self.exper.make_data() self.exper.output_cell_cols_def() self.exper.output_nuc_cols_def() self.exper.output_new_hdings() self.exper.log('Processed experiment {} in {:.3f} seconds'.format( self.exper.name, br.toc(t))) # br.dtoc(dt) def rerun_al(self, e): # dt = br.dtic('Processed experiment {}'.format(self.exper.name)) # t = br.tic() self.exper = None self.got_exper(self.dir_path) self.run_al(None) # self.exper = # self.exper.make_data() # self.exper.output_cell_cols_def() # self.exper.output_nuc_cols_def() # self.exper.output_new_hdings() # # self.exper.log('Created and processed experiment {} in {:.3f} seconds'.format(self.exper.name, br.toc(t))) # br.dtoc(dt) # def meta_data_al(self, e) : # meta_data_path = self.exper.meta_data_path() # if not os.path.exists(meta_data_path) : # txt = make_meta_data_str(self.exper) # with open(meta_data_path, 'w') as f : # f.write(txt) # # IJ.open(meta_data_path) def mdf_create_al(self, e): meta_data_path = self.exper.meta_data_path() # if not os.path.exists(meta_data_path) : intens_im_list = [] for check_box in self.intens_im_boxes: if check_box.isSelected(): intens_im_list.append(check_box.getLabel()) txt = make_meta_data_str2(self.exper, intens_im_list) with open(meta_data_path, 'w') as f: f.write(txt) # IJ.open(meta_data_path) def mdf_open_al(self, e): meta_data_path = self.exper.meta_data_path() IJ.open(meta_data_path) def got_exper(self, dir_path): # IJ.log('exper') self.dir_path = dir_path self.dir_text_field.setText(self.dir_path) self.log_text = JTextArea() self.exper = bob_py.Exper(dir_path, gui=self) self.show_exper_info()
def make_chf_panel(self): """ chf --> common hseg files """ chf_panel = JPanel() chf_panel.setLayout(MigLayout('insets 0')) chf_files_label = JLabel('Hemisegment cells') chf_files_text = JTextArea( BobGui.archetype_to_str( self.exper.hseg_cell_files_cab().archetype)) chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(chf_files_text, 'grow, wrap') chf_files_label = JLabel('Hemisegment binary image files') chf_files_text = JTextArea( BobGui.archetype_to_str(self.exper.hseg_bin_files_cab().archetype)) chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(chf_files_text, 'grow, wrap') chf_files_label = JLabel('Intensity Image Files') # chf_files_text = JTextArea(BobGui.archetype_to_str(self.exper.hseg_intens_im_files_cab().archetype)) # print(self.exper.hseg_intens_im_files_cab().archetype) # chf_panel.add(chf_files_label, 'growx, wrap') # chf_panel.add(chf_files_text, 'grow, wrap') self.intens_im_boxes = [] intens_im_panel = JPanel() intens_im_panel.setLayout(MigLayout('insets 0')) for poss_im_file in self.exper.hseg_intens_im_files_cab().archetype: self.intens_im_boxes.append(JCheckBox(poss_im_file)) intens_im_panel.add(self.intens_im_boxes[-1], 'wrap') chf_panel.add(chf_files_label, 'growx, wrap') chf_panel.add(intens_im_panel, 'grow, wrap') mdf_create_button = JButton( 'Create meta_data file from default outline') # mdf_create_button = JButton('<html>Create meta_data file<br>from default outline</html>') mdf_create_button.addActionListener( ActionListenerFactory(self, self.mdf_create_al)) mdf_open_button = JButton('Open existing meta_data file') mdf_open_button.addActionListener( ActionListenerFactory(self, self.mdf_open_al)) # meta_data_file_buttton = JButton('Open/Create meta_data file') # meta_data_file_buttton.addActionListener(ActionListenerFactory(self, self.meta_data_al)) # chf_panel.add(meta_data_file_buttton) chf_panel.add(mdf_create_button, 'wrap') chf_panel.add(mdf_open_button, 'wrap') chf_scroll_pane = JScrollPane() chf_scroll_pane.getViewport().setView(chf_panel) return chf_scroll_pane
class Plaso_ImportSettingsWithUISettingsPanel( IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # Check the checkboxs to see what actions need to be taken def checkBoxEvent(self, event): if self.Exclude_File_Sources_CB.isSelected(): self.local_settings.setExclude_File_Sources(True) else: self.local_settings.setExclude_File_Sources(False) # Check to see if there are any entries that need to be populated from the database. def check_Database_entries(self): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = head + "\\GUI_Settings.db3" try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings DB!") try: stmt = dbConn.createStatement() SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' resultSet = stmt.executeQuery(SQL_Statement) while resultSet.next(): if resultSet.getString( "Setting_Name") == "Plaso_Executable_Directory": self.Program_Executable_TF.setText( resultSet.getString("Setting_Value")) self.local_settings.setPlaso_Directory( resultSet.getString("Setting_Value")) self.local_settings.setPlaso_Dir_Found(True) self.Error_Message.setText("Settings Read successfully!") except SQLException as e: self.Error_Message.setText("Error Reading Settings Database") stmt.close() dbConn.close() # Save entries from the GUI to the database. def SaveSettings(self, e): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = head + "\\GUI_Settings.db3" try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings") try: stmt = dbConn.createStatement() SQL_Statement = "" if (self.local_settings.getPlaso_Dir_Found()): SQL_Statement = 'Update settings set Setting_Value = "' + self.Program_Executable_TF.getText() + '"' + \ ' where setting_name = "Plaso_Executable_Directory";' else: SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' + \ self.Program_Executable_TF.getText() + '");' stmt.execute(SQL_Statement) self.Error_Message.setText("Plaso Executable Directory Saved") self.local_settings.setPlaso_Directory( self.Program_Executable_TF.getText()) except SQLException as e: self.Error_Message.setText(e.getMessage()) stmt.close() dbConn.close() # When button to find file is clicked then open dialog to find the file and return it. def Find_Plaso_Dir(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("All", ["*.*"]) chooseFile.addChoosableFileFilter(filter) chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = chooseFile.showDialog(self.panel0, "Find Plaso Directory") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setPlaso_Directory(Canonical_file) self.Program_Executable_TF.setText(Canonical_file) def Find_Plaso_File(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("All", ["*.*"]) chooseFile.addChoosableFileFilter(filter) ret = chooseFile.showDialog(self.panel0, "Find Plaso Storage File") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setPlaso_Storage_File(Canonical_file) self.Plaso_Storage_File_TF.setText(Canonical_file) # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout(self.gbPanel0) self.Label_1 = JLabel("Plaso Executable Directory") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0) self.panel0.add(self.Label_1) self.Program_Executable_TF = JTextField(20) self.Program_Executable_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Program_Executable_TF, self.gbcPanel0) self.panel0.add(self.Program_Executable_TF) self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Plaso_Dir) self.Find_Program_Exec_BTN.setEnabled(True) self.rbgPanel0.add(self.Find_Program_Exec_BTN) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN, self.gbcPanel0) self.panel0.add(self.Find_Program_Exec_BTN) self.Blank_1 = JLabel(" ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0) self.panel0.add(self.Blank_1) self.Save_Settings_BTN = JButton("Save Plaso Exec Dir", actionPerformed=self.SaveSettings) self.Save_Settings_BTN.setEnabled(True) self.rbgPanel0.add(self.Save_Settings_BTN) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0) self.panel0.add(self.Save_Settings_BTN) self.Blank_2 = JLabel(" ") self.Blank_2.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0) self.panel0.add(self.Blank_2) self.Label_1 = JLabel("Plaso Storage File") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0) self.panel0.add(self.Label_1) self.Plaso_Storage_File_TF = JTextField(20) self.Plaso_Storage_File_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Plaso_Storage_File_TF, self.gbcPanel0) self.panel0.add(self.Plaso_Storage_File_TF) self.Find_Storage_BTN = JButton("Find Storage File", actionPerformed=self.Find_Plaso_File) self.Find_Storage_BTN.setEnabled(True) self.rbgPanel0.add(self.Find_Storage_BTN) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Find_Storage_BTN, self.gbcPanel0) self.panel0.add(self.Find_Storage_BTN) self.Blank_3 = JLabel(" ") self.Blank_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 15 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_3, self.gbcPanel0) self.panel0.add(self.Blank_3) self.Exclude_File_Sources_CB = JCheckBox( "Exclude File Source", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 17 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Exclude_File_Sources_CB, self.gbcPanel0) self.panel0.add(self.Exclude_File_Sources_CB) self.Blank_4 = JLabel(" ") self.Blank_4.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 19 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_4, self.gbcPanel0) self.panel0.add(self.Blank_4) self.Label_3 = JLabel("Message:") self.Label_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 21 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_3, self.gbcPanel0) self.panel0.add(self.Label_3) self.Error_Message = JLabel("") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 23 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0) self.panel0.add(self.Error_Message) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.Exclude_File_Sources_CB.setSelected( self.local_settings.getExclude_File_Sources()) self.check_Database_entries() #self.Error_Message.setText(Case.getCurrentCase().getTempDirectory()) # Return the settings used def getSettings(self): return self.local_settings
def addTabs(self, container): head = 'Row,Col,Cell'.split(',') junk = 'False,True'.split(',') data = [[0, 1], [0, 1]] info = JTable( # Used to get default attributes data, head, selectionMode=LSM.SINGLE_SELECTION) bTable = JTable(booleanTM(self.settings(info), head)) bTable.setDefaultRenderer(Boolean, boolRenderer()) tab1 = JPanel() tab1.add(JScrollPane(bTable)) info = JTable(data, head, selectionMode=LSM.SINGLE_INTERVAL_SELECTION) bTable = JTable(booleanTM(self.settings(info), head)) bTable.setDefaultRenderer(Boolean, boolRenderer()) tab2 = JPanel() tab2.add(JScrollPane(bTable)) info = JTable(data, head, selectionMode=LSM.MULTIPLE_INTERVAL_SELECTION) bTable = JTable(booleanTM(self.settings(info), head)) bTable.setDefaultRenderer(Boolean, boolRenderer()) tab3 = JPanel() tab3.add(JScrollPane(bTable)) tabs = JTabbedPane() tabs.addTab('Single', tab1) tabs.addTab('One Group', tab2) tabs.addTab('Multi-Group', tab3) container.add(tabs)
def addMetadata(self, objectID, project, language): """ Add a JTable at the top of the object tab containing the metadata of the object presented in that tab. """ metadataPanel = JPanel() # TODO: Need to count protocols to set up Grid dimension metadataPanel.setLayout(GridLayout(3, 2)) projectLabel = JLabel("Project: ") projectValue = JLabel(project) languageLabel = JLabel("Language: ") languageValue = JLabel(language) # If language code is in the settings, then display name instead # of code for lang, code in self.languages.iteritems(): if code == language: languageValue.setText(lang) # TODO Protocols not yet in parsed object protocolsLabel = JLabel("ATF Protocols: ") protocolsBox = JComboBox(self.protocols) metadataPanel.add(projectLabel) metadataPanel.add(projectValue) metadataPanel.add(languageLabel) metadataPanel.add(languageValue) metadataPanel.add(protocolsLabel) metadataPanel.add(protocolsBox) # Add metadataPanel to object tab in main panel self.objectTabs[objectID].add(metadataPanel)
def addLine(self, objectID, category, text): """ Add a new panel containing the text corresponding to one line in the ATF file. This panel will show the line type (ruling, comment, text, translation...), followed by the line content and a group of icons to add, edit or remove the line. """ linePanel = JPanel() linePanel.setLayout(BorderLayout()) label = JLabel(category) combo = JComboBox(text) combo.setEditable(True) combo.setPreferredSize(Dimension(500, 20)) combo.setSize(combo.getPreferredSize()) combo.setMinimumSize(combo.getPreferredSize()) combo.setMaximumSize(combo.getPreferredSize()) buttonsPanel = JPanel() addButton = JButton("Add") editButton = JButton("Edit") deleteButton = JButton("Delete") buttonsPanel.add(addButton) buttonsPanel.add(editButton) buttonsPanel.add(deleteButton) linePanel.add(label, BorderLayout.WEST) linePanel.add(combo, BorderLayout.CENTER) linePanel.add(buttonsPanel, BorderLayout.EAST) # Add metadataPanel to object tab in main panel self.objectTabs[objectID].add(linePanel)
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() #empty the list so concurrent lists don't get mixed up self.wordlist = [] hosts = '' #thanks BHP for traffic in http_traffic: http_service = traffic.getHttpService() hosts = http_service.getHost() #gathers all responses from the traffic http_response = traffic.getResponse() if http_response: words = self.handleTraffic(http_response) #add a list to the wordlist self.wordlist.extend(words) else: continue #after all words have been added, write to file self.filewrite(hosts) 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'
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory, IHttpRequestResponseWithMarkers, ITextEditor): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks #Initialize callbacks to be used later self._helpers = callbacks.getHelpers() callbacks.setExtensionName("Trishul") self._log = ArrayList() #_log used to store our outputs for a URL, which is retrieved later by the tool self._lock = Lock() #Lock is used for locking threads while updating logs in order such that no multiple updates happen at once self.intercept = 0 self.FOUND = "Found" self.CHECK = "Possible! Check Manually" self.NOT_FOUND = "Not Found" #Static Values for output #Initialize GUI self.issuesTab() self.advisoryReqResp() self.configTab() self.tabsInit() self.definecallbacks() print("Thank You for Installing Trishul") return # #Initialize Issues Tab displaying the JTree # def issuesTab(self): self.root = DefaultMutableTreeNode('Issues') frame = JFrame("Issues Tree") self.tree = JTree(self.root) self.rowSelected = '' self.tree.addMouseListener(mouseclick(self)) self.issuepanel = JScrollPane() self.issuepanel.setPreferredSize(Dimension(300,450)) self.issuepanel.getViewport().setView((self.tree)) frame.add(self.issuepanel,BorderLayout.CENTER) # #Adding Issues to Issues TreePath # def addIssues(self, branch, branchData=None): if branchData == None: branch.add(DefaultMutableTreeNode('No valid data')) else: for item in branchData: branch.add(DefaultMutableTreeNode(item)) # #Initialize the Config Tab to modify tool settings # def configTab(self): Config = JLabel("Config") self.startButton = JToggleButton("Intercept Off", actionPerformed=self.startOrStop) self.startButton.setBounds(40, 30, 200, 30) self.autoScroll = JCheckBox("Auto Scroll") self.autoScroll.setBounds(40, 80, 200, 30) self.xsscheck = JCheckBox("Detect XSS") self.xsscheck.setSelected(True) self.xsscheck.setBounds(40, 110, 200, 30) self.sqlicheck = JCheckBox("Detect SQLi") self.sqlicheck.setSelected(True) self.sqlicheck.setBounds(40, 140, 200, 30) self.ssticheck = JCheckBox("Detect SSTI") self.ssticheck.setSelected(True) self.ssticheck.setBounds(40, 170, 200, 30) self.blindxss = JCheckBox("Blind XSS") self.blindxss.setBounds(40, 200, 200, 30) self.BlindXSSText = JTextArea("", 5, 30) scrollbxssText = JScrollPane(self.BlindXSSText) scrollbxssText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollbxssText.setBounds(40, 250, 400, 110) self.configtab = JPanel() self.configtab.setLayout(None) self.configtab.setBounds(0, 0, 300, 300) self.configtab.add(Config) self.configtab.add(self.startButton) self.configtab.add(self.autoScroll) self.configtab.add(self.xsscheck) self.configtab.add(self.sqlicheck) self.configtab.add(self.ssticheck) self.configtab.add(self.blindxss) self.configtab.add(scrollbxssText) # #Turn Intercept from Proxy on or off # def startOrStop(self, event): if self.startButton.getText() == "Intercept Off": self.startButton.setText("Intercept On") self.startButton.setSelected(True) self.intercept = 1 else: self.startButton.setText("Intercept Off") self.startButton.setSelected(False) self.intercept = 0 # #Intialize the Advisory, Request and Response Tabs # def advisoryReqResp(self): self.textfield = JEditorPane("text/html", "") self.kit = HTMLEditorKit() self.textfield.setEditorKit(self.kit) self.doc = self.textfield.getDocument() self.textfield.setEditable(0) self.advisorypanel = JScrollPane() self.advisorypanel.getVerticalScrollBar() self.advisorypanel.setPreferredSize(Dimension(300,450)) self.advisorypanel.getViewport().setView((self.textfield)) self.selectedreq = [] self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._texteditor = self._callbacks.createTextEditor() self._texteditor.setEditable(False) # #Initialize Trishul Tabs # def tabsInit(self): self.logTable = Table(self) tableWidth = self.logTable.getPreferredSize().width self.logTable.getColumn("#").setPreferredWidth(Math.round(tableWidth / 50 * 0.1)) self.logTable.getColumn("Method").setPreferredWidth(Math.round(tableWidth / 50 * 3)) self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 40)) self.logTable.getColumn("Parameters").setPreferredWidth(Math.round(tableWidth / 50 * 1)) self.logTable.getColumn("XSS").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("SQLi").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("SSTI").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Request Time").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.tableSorter = TableRowSorter(self) self.logTable.setRowSorter(self.tableSorter) self._bottomsplit = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._bottomsplit.setDividerLocation(500) self.issuetab = JTabbedPane() self.issuetab.addTab("Config",self.configtab) self.issuetab.addTab("Issues",self.issuepanel) self._bottomsplit.setLeftComponent(self.issuetab) self.tabs = JTabbedPane() self.tabs.addTab("Advisory",self.advisorypanel) self.tabs.addTab("Request", self._requestViewer.getComponent()) self.tabs.addTab("Response", self._responseViewer.getComponent()) self.tabs.addTab("Highlighted Response", self._texteditor.getComponent()) self._bottomsplit.setRightComponent(self.tabs) self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._splitpane.setDividerLocation(450) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self)) self._splitpane.setRightComponent(self._bottomsplit) # #Initialize burp callbacks # def definecallbacks(self): self._callbacks.registerHttpListener(self) self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self._bottomsplit) self._callbacks.registerContextMenuFactory(self) self._callbacks.addSuiteTab(self) # #Menu Item to send Request to Trishul # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Trishul") for response in responses: requestMenuItem.addActionListener(handleMenuItems(self,response, "request")) ret.add(requestMenuItem) return ret return None # #Highlighting Response # def markHttpMessage( self, requestResponse, responseMarkString ): responseMarkers = None if responseMarkString: response = requestResponse.getResponse() responseMarkBytes = self._helpers.stringToBytes( responseMarkString ) start = self._helpers.indexOf( response, responseMarkBytes, False, 0, len( response ) ) if -1 < start: responseMarkers = [ array( 'i',[ start, start + len( responseMarkBytes ) ] ) ] requestHighlights = [array( 'i',[ 0, 5 ] )] return self._callbacks.applyMarkers( requestResponse, requestHighlights, responseMarkers ) def getTabCaption(self): return "Trishul" def getUiComponent(self): return self._splitpane # #Table Model to display URL's and results based on the log size # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 8 def getColumnName(self, columnIndex): data = ['#','Method', 'URL', 'Parameters', 'XSS', 'SQLi', "SSTI", "Request Time"] try: return data[columnIndex] except IndexError: return "" def getColumnClass(self, columnIndex): data = [Integer, String, String, Integer, String, String, String, String] try: return data[columnIndex] except IndexError: return "" #Get Data stored in log and display in the respective columns def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return rowIndex+1 if columnIndex == 1: return logEntry._method if columnIndex == 2: return logEntry._url.toString() if columnIndex == 3: return len(logEntry._parameter) if columnIndex == 4: return logEntry._XSSStatus if columnIndex == 5: return logEntry._SQLiStatus if columnIndex == 6: return logEntry._SSTIStatus if columnIndex == 7: return logEntry._req_time return "" def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() #For Intercepted requests perform tests in scope def processHttpMessage(self, toolFlag, messageIsRequest, messageInf): if self.intercept == 1: if toolFlag == self._callbacks.TOOL_PROXY: if not messageIsRequest: requestInfo = self._helpers.analyzeRequest(messageInf) requeststr = requestInfo.getUrl() parameters = requestInfo.getParameters() param_new = [p for p in parameters if p.getType() != 2] if len(param_new) != 0: if self._callbacks.isInScope(URL(str(requeststr))): start_new_thread(self.sendRequestToTrishul,(messageInf,)) return # #Main processing of Trishul # def sendRequestToTrishul(self,messageInfo): request = messageInfo.getRequest() req_time = datetime.datetime.today() requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() messageInfo = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), request) resp_time = datetime.datetime.today() time_taken = (resp_time - req_time).total_seconds() response = messageInfo.getResponse() #initialozations of default value SQLiimp = self.NOT_FOUND SSTIimp = self.NOT_FOUND XSSimp = self.NOT_FOUND Comp_req = messageInfo requestInfo = self._helpers.analyzeRequest(messageInfo) self.content_resp = self._helpers.analyzeResponse(response) requestURL = requestInfo.getUrl() parameters = requestInfo.getParameters() requeststring = self._helpers.bytesToString(request) headers = requestInfo.getHeaders() #Used to obtain GET, POST and JSON parameters from burp api param_new = [p for p in parameters if p.getType() == 0 or p.getType() == 1 or p.getType() == 6] i = 0 xssflag=0 sqliflag=0 sstiflag=0 resultxss = [] resultsqli = [] resultssti = [] xssreqresp = [] sqlireqresp = [] sstireqresp = [] ssti_description = [] sqli_description = [] xss_description = [] for i in range(len(param_new)): name = param_new[i].getName() ptype = param_new[i].getType() param_value = param_new[i].getValue() #check XSS if ticked if self.xsscheck.isSelected(): score = 0 flag1 = 0 XSSimp = self.NOT_FOUND payload_array = ["<", ">", "\\\\'asd", "\\\\\"asd", "\\", "'\""] json_payload_array = ["<", ">", "\\\\'asd", "\\\"asd", "\\", "\'\\\""] payload_all = "" json_payload = "" rand_str = "testtest" for payload in payload_array: payload_all = payload_all+rand_str+payload payload_all = URLEncoder.encode(payload_all, "UTF-8") for payload in json_payload_array: json_payload = json_payload+rand_str+payload json_payload = URLEncoder.encode(json_payload, "UTF-8") if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) response = attack.getResponse() response_str = self._helpers.bytesToString(response) xssreqresp.append(attack) if_found_payload = "" non_encoded_symbols = "" for check_payload in payload_array: if_found_payload = rand_str+check_payload if if_found_payload in response_str: non_encoded_symbols = non_encoded_symbols+"<br>"+check_payload.replace('<', '<') score = score+1 flag1 = 1 if score > 2: XSSimp = self.CHECK if score > 3: XSSimp = self.FOUND xssflag = self.checkBetterScore(score,xssflag) if non_encoded_symbols == " \\\\'asd": XSSimp = self.NOT_FOUND if non_encoded_symbols != '': xss_description.append("The Payload <b>" + payload_all.replace('<', '<') + "</b> was passed in the request for the paramater <b>" + self._helpers.urlDecode(name) + "</b>. Some Tags were observed in the output unfiltered. A payload can be generated with the observed tags.<br>Symbols not encoded for parameter <b>" + name + "</b>: " + non_encoded_symbols) else: xss_description.append("") else: XSSimp = "Disabled" resultxss.append(XSSimp) if self.sqlicheck.isSelected(): SQLiimp = self.NOT_FOUND score = 0 value = "%27and%28select%2afrom%28select%28sleep%285%29%29%29a%29--" orig_time = datetime.datetime.today() if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, value, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+value) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+value+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack1 = self.makeRequest(Comp_req, updated_request) response1 = attack1.getResponse() new_time = datetime.datetime.today() response_str1 = self._helpers.bytesToString(response1) sqlireqresp.append(attack1) diff = (new_time - orig_time).total_seconds() if (diff - time_taken) > 3: score = 4 self.error_array = ["check the manual that corresponds to your", "You have an error", "syntax error", "SQL syntax", "SQL statement", "ERROR:", "Error:", "MySQL","Warning:","mysql_fetch_array()"] found_text = "" for error in self.error_array: if error in response_str1: found_text = found_text + error score = score + 1 if score > 1: SQLiimp = self.CHECK if score > 2: SQLiimp = self.FOUND sqliflag = self.checkBetterScore(score,sqliflag) if found_text != '': sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. Some errors were generated in the response which confirms that there is an Error based SQLi. Please check the request and response for this parameter") elif (diff - time_taken) > 3: sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. The response was in a delay of <b>"+str(diff)+"</b> seconds as compared to original <b>"+str(time_taken)+"</b> seconds. This indicates that there is a time based SQLi. Please check the request and response for this parameter") else: sqli_description.append("") else: SQLiimp = "Disabled" resultsqli.append(SQLiimp) if self.ssticheck.isSelected(): score = 0 SSTIimp = self.NOT_FOUND payload_array = ["${123*456}", "<%=123*567%>", "{{123*678}}"] json_payload_array = ["$\{123*456\}", "<%=123*567%>", "\{\{123*678\}\}"] payload_all = "" rand_str = "jjjjjjj" json_payload = "" for payload in payload_array: payload_all = payload_all+rand_str+payload for payload in json_payload_array: json_payload = json_payload+rand_str+payload payload_all = URLEncoder.encode(payload_all, "UTF-8") json_payload = URLEncoder.encode(json_payload, "UTF-8") if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) response = attack.getResponse() response_str = self._helpers.bytesToString(response) self.expected_output = ["56088","69741","83394","3885","777777777777777"] for output in self.expected_output: if_found_payload = rand_str+output if if_found_payload in response_str: if output == self.expected_output[0]: sstireqresp.append(attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Java</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>56088</b>") score = 2 if output == self.expected_output[1]: sstireqresp.append(attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Ruby</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>69741</b>") score = 2 if output == self.expected_output[2]: payload_new = "{{5*'777'}}" json_payload_ssti = "\{\{5*'777'\}\}" payload = URLEncoder.encode("{{5*'777'}}", "UTF-8") json_ssti = URLEncoder.encode("\{\{5*'777'\}\}", "UTF-8") if ptype == 0 or ptype == 1: new_paramters = self._helpers.buildParameter(name, payload, ptype) ssti_updated_request = self._helpers.updateParameter(request, new_paramters) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_ssti) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_ssti+"\"") ssti_updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) self.ssti_attack = self.makeRequest(Comp_req, ssti_updated_request) ssti_response = self.ssti_attack.getResponse() ssti_response_str = self._helpers.bytesToString(ssti_response) if self.expected_output[3] in ssti_response_str: sstireqresp.append(self.ssti_attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Twig</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>3885</b>") score = 2 elif self.expected_output[4] in ssti_response_str: sstireqresp.append(self.ssti_attack) self.responseMarkString = "777777777777777" ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Jinja2</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>777777777777777</b>") score = 2 if score > 0: SSTIimp = self.CHECK if score > 1: SSTIimp = self.FOUND sstiflag = self.checkBetterScore(score,sstiflag) else: SSTIimp = "Disabled" resultssti.append(SSTIimp) if self.blindxss.isSelected(): blindxss_value = self.BlindXSSText.getText() if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, blindxss_value, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+blindxss_value) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+blindxss_value+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) if XSSimp != "Disabled": if xssflag > 3: XSSimp = self.FOUND elif xssflag > 2: XSSimp = self.CHECK else: XSSimp = self.NOT_FOUND if SSTIimp != "Disabled": if sstiflag > 1: SSTIimp = self.FOUND elif sstiflag > 0: SSTIimp = self.CHECK else: SSTIimp = self.NOT_FOUND if SQLiimp != "Disabled": if sqliflag > 3: SQLiimp = self.FOUND elif sqliflag > 2: SQLiimp = self.CHECK else: SQLiimp = self.NOT_FOUND self.addToLog(messageInfo, XSSimp, SQLiimp, SSTIimp, param_new, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp , xss_description, sqli_description, ssti_description, req_time.strftime('%H:%M:%S %m/%d/%y')) # #Function used to check if the score originally and mentioned is better # def checkBetterScore(self, score, ogscore): if score > ogscore: ogscore = score return ogscore def makeRequest(self, messageInfo, message): request = messageInfo.getRequest() requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() return self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message) def addToLog(self, messageInfo, XSSimp, SQLiimp, SSTIimp, parameters, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description, req_time): requestInfo = self._helpers.analyzeRequest(messageInfo) method = requestInfo.getMethod() self._lock.acquire() row = self._log.size() self._log.add(LogEntry(self._callbacks.saveBuffersToTempFiles(messageInfo), requestInfo.getUrl(),method,XSSimp,SQLiimp,SSTIimp,req_time, parameters,resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description)) # same requests not include again. SwingUtilities.invokeLater(UpdateTableEDT(self,"insert",row,row)) self._lock.release()
def _add_label(self, label): panel = JPanel() panel.add(JLabel('<html><h2>%s</h2></html>' % label)) self._add_panel(panel)
class GUI_PSQLiteUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setFlag(True) self.local_settings.setArea(self.area.getText()); else: self.local_settings.setFlag(False) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Check to activate/deactivate TextArea", actionPerformed=self.checkBoxEvent) self.label0 = JLabel(" ") self.label1 = JLabel("Input in SQLite DB's in area below,") self.label2 = JLabel("seperate values by commas.") self.label3 = JLabel("then check the box above.") self.label4 = JLabel(" ") self.panel1.add(self.checkbox) self.panel1.add(self.label0) self.panel1.add(self.label1) self.panel1.add(self.label2) self.panel1.add(self.label3) self.panel1.add(self.label4) self.add(self.panel1) self.area = JTextArea(5,25) #self.area.getDocument().addDocumentListener(self.area) #self.area.addKeyListener(listener) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self.area) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getFlag()) # Return the settings used def getSettings(self): return self.local_settings
def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout(self.gbPanel0) self.Label_1 = JLabel("Plaso Executable Directory") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0) self.panel0.add(self.Label_1) self.Program_Executable_TF = JTextField(20) self.Program_Executable_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Program_Executable_TF, self.gbcPanel0) self.panel0.add(self.Program_Executable_TF) self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Plaso_Dir) self.Find_Program_Exec_BTN.setEnabled(True) self.rbgPanel0.add(self.Find_Program_Exec_BTN) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN, self.gbcPanel0) self.panel0.add(self.Find_Program_Exec_BTN) self.Blank_1 = JLabel(" ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0) self.panel0.add(self.Blank_1) self.Save_Settings_BTN = JButton("Save Plaso Exec Dir", actionPerformed=self.SaveSettings) self.Save_Settings_BTN.setEnabled(True) self.rbgPanel0.add(self.Save_Settings_BTN) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0) self.panel0.add(self.Save_Settings_BTN) self.Blank_2 = JLabel(" ") self.Blank_2.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0) self.panel0.add(self.Blank_2) self.Label_1 = JLabel("Plaso Storage File") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0) self.panel0.add(self.Label_1) self.Plaso_Storage_File_TF = JTextField(20) self.Plaso_Storage_File_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Plaso_Storage_File_TF, self.gbcPanel0) self.panel0.add(self.Plaso_Storage_File_TF) self.Find_Storage_BTN = JButton("Find Storage File", actionPerformed=self.Find_Plaso_File) self.Find_Storage_BTN.setEnabled(True) self.rbgPanel0.add(self.Find_Storage_BTN) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Find_Storage_BTN, self.gbcPanel0) self.panel0.add(self.Find_Storage_BTN) self.Blank_3 = JLabel(" ") self.Blank_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 15 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_3, self.gbcPanel0) self.panel0.add(self.Blank_3) self.Exclude_File_Sources_CB = JCheckBox( "Exclude File Source", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 17 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Exclude_File_Sources_CB, self.gbcPanel0) self.panel0.add(self.Exclude_File_Sources_CB) self.Blank_4 = JLabel(" ") self.Blank_4.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 19 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_4, self.gbcPanel0) self.panel0.add(self.Blank_4) self.Label_3 = JLabel("Message:") self.Label_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 21 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_3, self.gbcPanel0) self.panel0.add(self.Label_3) self.Error_Message = JLabel("") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 23 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0) self.panel0.add(self.Error_Message) self.add(self.panel0)
def build_gui(self): """Construct GUI elements.""" panel = JPanel(BorderLayout(3, 3)) panel.setBorder(EmptyBorder(160, 160, 160, 160)) self.aws_access_key_inpt = JTextField(10) self.aws_secret_key_inpt = JTextField(10) self.aws_session_token_inpt = JTextField(10) self.gs_access_key_inpt = JTextField(10) self.gs_secret_key_inpt = JTextField(10) self.wordlist_path_inpt = JTextField(10) self.checkbox_inpt = JCheckBox('Enabled') save_btn = JButton('Save', actionPerformed=self.save_config) labels = JPanel(GridLayout(0, 1)) inputs = JPanel(GridLayout(0, 1)) panel.add(labels, BorderLayout.WEST) panel.add(inputs, BorderLayout.CENTER) top_label = JLabel('<html><b>Settings</b><br><br></html>') top_label.setHorizontalAlignment(JLabel.CENTER) panel.add(top_label, BorderLayout.NORTH) labels.add(JLabel('AWS Access Key:')) inputs.add(self.aws_access_key_inpt) labels.add(JLabel('AWS Secret Key:')) inputs.add(self.aws_secret_key_inpt) labels.add(JLabel('AWS Session Key (optional):')) inputs.add(self.aws_session_token_inpt) labels.add(JLabel('GS Access Key:')) inputs.add(self.gs_access_key_inpt) labels.add(JLabel('GS Secret Key:')) inputs.add(self.gs_secret_key_inpt) labels.add(JLabel('Wordlist Filepath (optional):')) inputs.add(self.wordlist_path_inpt) labels.add(JLabel('Passive Mode:')) inputs.add(self.checkbox_inpt) panel.add(save_btn, BorderLayout.SOUTH) return panel
def makeBorder(el): p = JPanel() p.setLayout(BorderLayout()) p.add("Center", el) return p
def makeFlow(*elts): p = JPanel() p.setLayout(FlowLayout()) for b in elts: p.add(b) return p
def makeGrid(i, j, *elts): p = JPanel() p.setLayout(GridLayout(i, j)) for b in elts: p.add(b) return p
def __init__(self): super(BobGui, self).__init__('BobPy') # IJ.log('okay?') # print('okay??') self.setLayout(BorderLayout()) self.main_panel = JPanel() # self.main_panel.setLayout(MigLayout('insets 1 10 1 1')) self.main_panel.setLayout(MigLayout()) dir_panel = JPanel() dir_panel.setLayout(BoxLayout(dir_panel, BoxLayout.X_AXIS)) dir_label = JLabel('Experiment Folder:') dir_panel.add(dir_label) self.dir_text_field = JTextField(10) self.dir_text_field.addActionListener( ActionListenerFactory(self, self.text_field_al)) dir_panel.add(self.dir_text_field) dir_button = JButton('open') dir_button.addActionListener( ActionListenerFactory(self, self.choose_dir_al)) dir_panel.add(dir_button) self.main_panel.add(dir_panel, 'wrap, growx, spanx, pushx') add_key_args(self.main_panel, 'close_w', ActionListenerFactory(self, self.close_al), KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) self.add(self.main_panel, BorderLayout.CENTER) self.setPreferredSize(Dimension(650, 600)) self.pack() self.setLocationRelativeTo(None) self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setVisible(True)
def registerExtenderCallbacks(self, callbacks): print "Loading..." self._callbacks = callbacks self._callbacks.setExtensionName('Burp SSL Scanner') # self._callbacks.registerScannerCheck(self) # self._callbacks.registerExtensionStateListener(self) self._helpers = callbacks.getHelpers() # initialize the main scanning event and thread self.scanningEvent = Event() self.scannerThread = None self.targetURL = None # main split pane self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20)) # sub split pane (top) self._topPanel = JPanel(BorderLayout(10, 10)) self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0)) # Setup Panel : [Target: ] [______________________] [START BUTTON] self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.setupPanel.add( JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START) self.hostField = JTextField('', 50) self.setupPanel.add(self.hostField) self.toggleButton = JButton( 'Start scanning', actionPerformed=self.startScan) self.setupPanel.add(self.toggleButton) if 'Professional' in callbacks.getBurpVersion()[0] : self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True) else : self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False) self.addToSitemapCheckbox.setEnabled(False) self.setupPanel.add(self.addToSitemapCheckbox) self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True) self.setupPanel.add(self.scanSiteMapHostCheckbox) self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START) # Status bar self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT)) self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT) self.scanStatusPanel.add(self.scanStatusLabel) self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START) self._splitpane.setTopComponent(self._topPanel) # bottom panel self._bottomPanel = JPanel(BorderLayout(10, 10)) self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0)) self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />' 'Please note that TLS1.3 is still not supported by this extension.</h1>') self.currentText = self.initialText self.textPane = JTextPane() self.textScrollPane = JScrollPane(self.textPane) self.textPane.setContentType("text/html") self.textPane.setText(self.currentText) self.textPane.setEditable(False) self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER) self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile) self.saveButton.setEnabled(False) self.savePanel.add(self.saveButton) self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost) self.savePanel.add(self.clearScannedHostButton) self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT)) self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END) self._splitpane.setBottomComponent(self._bottomPanel) callbacks.customizeUiComponent(self._splitpane) callbacks.addSuiteTab(self) print "SSL Scanner tab loaded" self.scannerMenu = ScannerMenu(self) callbacks.registerContextMenuFactory(self.scannerMenu) print "SSL Scanner custom menu loaded" self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected) callbacks.registerScannerCheck(self.scannerCheck) print "SSL Scanner check registered" projectConfig = json.loads(self._callbacks.saveConfigAsJson()) scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy'] scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed'] print(scanAccuracy, scanSpeed) self.scannedHost = [] print 'SSL Scanner loaded'
def draw(self): """ init autorize tabs """ self._extender.logTable = Table(self._extender) tableWidth = self._extender.logTable.getPreferredSize().width self._extender.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2)) self._extender.logTable.getColumn("Method").setPreferredWidth(Math.round(tableWidth / 50 * 3)) self._extender.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 25)) self._extender.logTable.getColumn("Orig. Len").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Modif. Len").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Unauth. Len").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Authz. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._extender.logTable.getColumn("Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._extender.tableSorter = TableRowSorter(self._extender.tableModel) rowFilter = TableRowFilter(self._extender) self._extender.tableSorter.setRowFilter(rowFilter) self._extender.logTable.setRowSorter(self._extender.tableSorter) self._extender._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._extender._splitpane.setResizeWeight(1) self._extender.scrollPane = JScrollPane(self._extender.logTable) self._extender._splitpane.setLeftComponent(self._extender.scrollPane) self._extender.scrollPane.getVerticalScrollBar().addAdjustmentListener(AutoScrollListener(self._extender)) copyURLitem = JMenuItem("Copy URL") copyURLitem.addActionListener(CopySelectedURL(self._extender)) sendRequestMenu = JMenuItem("Send Original Request to Repeater") sendRequestMenu.addActionListener(SendRequestRepeater(self._extender, self._extender._callbacks, True)) sendRequestMenu2 = JMenuItem("Send Modified Request to Repeater") sendRequestMenu2.addActionListener(SendRequestRepeater(self._extender, self._extender._callbacks, False)) sendResponseMenu = JMenuItem("Send Responses to Comparer") sendResponseMenu.addActionListener(SendResponseComparer(self._extender, self._extender._callbacks)) retestSelecteditem = JMenuItem("Retest selected request") retestSelecteditem.addActionListener(RetestSelectedRequest(self._extender)) deleteSelectedItem = JMenuItem("Delete") deleteSelectedItem.addActionListener(DeleteSelectedRequest(self._extender)) self._extender.menu = JPopupMenu("Popup") self._extender.menu.add(sendRequestMenu) self._extender.menu.add(sendRequestMenu2) self._extender.menu.add(sendResponseMenu) self._extender.menu.add(copyURLitem) self._extender.menu.add(retestSelecteditem) # self.menu.add(deleteSelectedItem) disabling this feature until bug will be fixed. message_editor = MessageEditor(self._extender) self._extender.tabs = JTabbedPane() self._extender._requestViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender._responseViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender._originalrequestViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender._originalresponseViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender._unauthorizedrequestViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender._unauthorizedresponseViewer = self._extender._callbacks.createMessageEditor(message_editor, False) self._extender.original_requests_tabs = JTabbedPane() self._extender.original_requests_tabs.addMouseListener(Mouseclick(self._extender)) self._extender.original_requests_tabs.addTab("Original Request", self._extender._originalrequestViewer.getComponent()) self._extender.original_requests_tabs.addTab("Original Response", self._extender._originalresponseViewer.getComponent()) self._extender.original_requests_tabs.addTab("Expand", None) self._extender.original_requests_tabs.setSelectedIndex(0) self._extender.unauthenticated_requests_tabs = JTabbedPane() self._extender.unauthenticated_requests_tabs.addMouseListener(Mouseclick(self._extender)) self._extender.unauthenticated_requests_tabs.addTab("Unauthenticated Request", self._extender._unauthorizedrequestViewer.getComponent()) self._extender.unauthenticated_requests_tabs.addTab("Unauthenticated Response", self._extender._unauthorizedresponseViewer.getComponent()) self._extender.unauthenticated_requests_tabs.addTab("Expand", None) self._extender.unauthenticated_requests_tabs.setSelectedIndex(0) self._extender.modified_requests_tabs = JTabbedPane() self._extender.modified_requests_tabs.addMouseListener(Mouseclick(self._extender)) self._extender.modified_requests_tabs.addTab("Modified Request", self._extender._requestViewer.getComponent()) self._extender.modified_requests_tabs.addTab("Modified Response", self._extender._responseViewer.getComponent()) self._extender.modified_requests_tabs.addTab("Expand", None) self._extender.modified_requests_tabs.setSelectedIndex(0) self._extender.requests_panel = JPanel(GridLayout(3,0)) self._extender.requests_panel.add(self._extender.modified_requests_tabs) self._extender.requests_panel.add(self._extender.original_requests_tabs) self._extender.requests_panel.add(self._extender.unauthenticated_requests_tabs) self._extender.tabs.addTab("Request/Response Viewers", self._extender.requests_panel) self._extender.tabs.addTab("Configuration", self._extender._cfg_splitpane) self._extender.tabs.setSelectedIndex(1) self._extender._splitpane.setRightComponent(self._extender.tabs)
def draw(self): """ init configuration tab """ self._extender.startButton = JToggleButton("Autorize is off", actionPerformed=self.startOrStop) self._extender.startButton.setBounds(10, 20, 230, 30) self._extender.clearButton = JButton("Clear List", actionPerformed=self.clearList) self._extender.clearButton.setBounds(10, 80, 100, 30) self._extender.autoScroll = JCheckBox("Auto Scroll") self._extender.autoScroll.setBounds(145, 80, 130, 30) self._extender.ignore304 = JCheckBox("Ignore 304/204 status code responses") self._extender.ignore304.setBounds(280, 5, 300, 30) self._extender.ignore304.setSelected(True) self._extender.prevent304 = JCheckBox("Prevent 304 Not Modified status code") self._extender.prevent304.setBounds(280, 25, 300, 30) self._extender.interceptRequestsfromRepeater = JCheckBox("Intercept requests from Repeater") self._extender.interceptRequestsfromRepeater.setBounds(280, 45, 300, 30) self._extender.doUnauthorizedRequest = JCheckBox("Check unauthenticated") self._extender.doUnauthorizedRequest.setBounds(280, 65, 300, 30) self._extender.doUnauthorizedRequest.setSelected(True) self._extender.saveHeadersButton = JButton("Save headers", actionPerformed=self.saveHeaders) self._extender.saveHeadersButton.setBounds(360, 115, 120, 30) savedHeadersTitles = self.getSavedHeadersTitles() self._extender.savedHeadersTitlesCombo = JComboBox(savedHeadersTitles) self._extender.savedHeadersTitlesCombo.addActionListener(SavedHeaderChange(self._extender)) self._extender.savedHeadersTitlesCombo.setBounds(10, 115, 300, 30) self._extender.replaceString = JTextArea("Cookie: Insert=injected; cookie=or;\nHeader: here", 5, 30) self._extender.replaceString.setWrapStyleWord(True) self._extender.replaceString.setLineWrap(True) scrollReplaceString = JScrollPane(self._extender.replaceString) scrollReplaceString.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollReplaceString.setBounds(10, 150, 470, 150) self._extender.fetchButton = JButton("Fetch cookies from last request", actionPerformed=self.fetchCookies) self._extender.fetchButton.setEnabled(False) self._extender.fetchButton.setBounds(10, 305, 250, 30) self._extender.filtersTabs = JTabbedPane() self._extender.filtersTabs = self._extender.filtersTabs self._extender.filtersTabs.addTab("Enforcement Detector", self._extender.EDPnl) self._extender.filtersTabs.addTab("Detector Unauthenticated", self._extender.EDPnlUnauth) self._extender.filtersTabs.addTab("Interception Filters", self._extender.filtersPnl) self._extender.filtersTabs.addTab("Match/Replace", self._extender.MRPnl) self._extender.filtersTabs.addTab("Table Filter", self._extender.filterPnl) self._extender.filtersTabs.addTab("Save/Restore", self._extender.exportPnl) self._extender.filtersTabs.setSelectedIndex(2) self._extender.filtersTabs.setBounds(0, 350, 2000, 700) self._extender.pnl = JPanel() self.pnl = self._extender.pnl self.pnl.setBounds(0, 0, 1000, 1000) self.pnl.setLayout(None) self.pnl.add(self._extender.startButton) self.pnl.add(self._extender.clearButton) self.pnl.add(scrollReplaceString) self.pnl.add(self._extender.saveHeadersButton) self.pnl.add(self._extender.savedHeadersTitlesCombo) self.pnl.add(self._extender.fetchButton) self.pnl.add(self._extender.autoScroll) self.pnl.add(self._extender.interceptRequestsfromRepeater) self.pnl.add(self._extender.ignore304) self.pnl.add(self._extender.prevent304) self.pnl.add(self._extender.doUnauthorizedRequest) self.pnl.add(self._extender.filtersTabs)
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
def draw(self): """ init show tab """ filterLModified = JLabel("Modified:") filterLModified.setBounds(10, 10, 100, 30) filterLUnauthenticated = JLabel("Unauthenticated:") filterLUnauthenticated.setBounds(250, 10, 100, 30) self._extender.showAuthBypassModified = JCheckBox( self._extender.BYPASSSED_STR) self._extender.showAuthBypassModified.setBounds(10, 35, 200, 30) self._extender.showAuthBypassModified.setSelected(True) self._extender.showAuthBypassModified.addItemListener( TabTableFilter(self._extender)) self._extender.showAuthPotentiallyEnforcedModified = JCheckBox( "Is enforced???") self._extender.showAuthPotentiallyEnforcedModified.setBounds( 10, 60, 200, 30) self._extender.showAuthPotentiallyEnforcedModified.setSelected(True) self._extender.showAuthPotentiallyEnforcedModified.addItemListener( TabTableFilter(self._extender)) self._extender.showAuthEnforcedModified = JCheckBox( self._extender.ENFORCED_STR) self._extender.showAuthEnforcedModified.setBounds(10, 85, 200, 30) self._extender.showAuthEnforcedModified.setSelected(True) self._extender.showAuthEnforcedModified.addItemListener( TabTableFilter(self._extender)) self._extender.showAuthBypassUnauthenticated = JCheckBox( self._extender.BYPASSSED_STR) self._extender.showAuthBypassUnauthenticated.setBounds( 250, 35, 200, 30) self._extender.showAuthBypassUnauthenticated.setSelected(True) self._extender.showAuthBypassUnauthenticated.addItemListener( TabTableFilter(self._extender)) self._extender.showAuthPotentiallyEnforcedUnauthenticated = JCheckBox( "Is enforced???") self._extender.showAuthPotentiallyEnforcedUnauthenticated.setBounds( 250, 60, 200, 30) self._extender.showAuthPotentiallyEnforcedUnauthenticated.setSelected( True) self._extender.showAuthPotentiallyEnforcedUnauthenticated.addItemListener( TabTableFilter(self._extender)) self._extender.showAuthEnforcedUnauthenticated = JCheckBox( self._extender.ENFORCED_STR) self._extender.showAuthEnforcedUnauthenticated.setBounds( 250, 85, 200, 30) self._extender.showAuthEnforcedUnauthenticated.setSelected(True) self._extender.showAuthEnforcedUnauthenticated.addItemListener( TabTableFilter(self._extender)) self._extender.showDisabledUnauthenticated = JCheckBox("Disabled") self._extender.showDisabledUnauthenticated.setBounds(250, 110, 200, 30) self._extender.showDisabledUnauthenticated.setSelected(True) self._extender.showDisabledUnauthenticated.addItemListener( TabTableFilter(self._extender)) self._extender.filterPnl = JPanel() self._extender.filterPnl.setLayout(None) self._extender.filterPnl.setBounds(0, 0, 1000, 1000) self._extender.filterPnl.add(filterLModified) self._extender.filterPnl.add(filterLUnauthenticated) self._extender.filterPnl.add(self._extender.showAuthBypassModified) self._extender.filterPnl.add( self._extender.showAuthPotentiallyEnforcedModified) self._extender.filterPnl.add(self._extender.showAuthEnforcedModified) self._extender.filterPnl.add( self._extender.showAuthBypassUnauthenticated) self._extender.filterPnl.add( self._extender.showAuthPotentiallyEnforcedUnauthenticated) self._extender.filterPnl.add( self._extender.showAuthEnforcedUnauthenticated) self._extender.filterPnl.add( self._extender.showDisabledUnauthenticated)
def __init__(self, size): JPanel.__init__(self) self.setPreferredSize(Dimension(size[0], size[1])) self.surface = pyj2d.surface.Surface(size, BufferedImage.TYPE_INT_RGB) self.setBackground(Color.BLACK)
def __init__(self, menuHandles, manager, isDominant, systemPanel, isTemporal=False): self.systemPanel = systemPanel self.knownPops = 0 self.ignoreChanges = True JPanel() self.menuHandles = menuHandles self.isDominant = isDominant self.isTemporal = isTemporal if isDominant: self.setLayout(GridLayout(8, 2)) else: self.setLayout(GridLayout(5, 2)) if isTemporal: self.add(JLabel('Ne')) ne = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US)) ne.addPropertyChangeListener(self) self.ne = ne self.add(ne) self.add(JLabel('Expected total samples')) else: self.add(JLabel('Attempted Fst')) fst = JFormattedTextField(NumberFormat.getNumberInstance( Locale.US)) fst.addPropertyChangeListener(self) self.fst = fst self.add(fst) self.add(JLabel('Expected total pops')) pops = JFormattedTextField(NumberFormat.getIntegerInstance(Locale.US)) pops.addPropertyChangeListener(self) # self.pops = JComboBox(['1', '2', '4', '8', '12', '16']) self.pops = pops self.add(self.pops) if not isDominant and not isTemporal: self.add(JLabel('Mutation model')) self.mut = JComboBox(['Infinite Alleles', 'Stepwise']) self.mut.addItemListener(self) self.add(self.mut) else: self.mut = None self.add(JLabel('Subsample size')) sampleSize = JFormattedTextField( NumberFormat.getIntegerInstance(Locale.US)) sampleSize.addPropertyChangeListener(self) self.sampleSize = sampleSize self.add(self.sampleSize) if isDominant: self.add(JLabel('Theta')) theta = JFormattedTextField( NumberFormat.getNumberInstance(Locale.US)) theta.addPropertyChangeListener(self) self.theta = theta self.add(theta) theta.setValue(0.1) self.add(JLabel('Beta-a')) beta1 = JFormattedTextField( NumberFormat.getNumberInstance(Locale.US)) beta1.addPropertyChangeListener(self) self.beta1 = beta1 self.add(beta1) beta1.setValue(0.25) self.add(JLabel('Beta-b')) beta2 = JFormattedTextField( NumberFormat.getNumberInstance(Locale.US)) beta2.addPropertyChangeListener(self) self.beta2 = beta2 self.add(beta2) beta2.setValue(0.25) self.add(JLabel('Critical frequency')) crit = JFormattedTextField( NumberFormat.getNumberInstance(Locale.US)) crit.addPropertyChangeListener(self) self.crit = crit self.add(crit) crit.setValue(0.99) run = JButton('Run!') run.addActionListener(manager) run.setActionCommand('RunFDist') self.run = run self.add(run)
class Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('All', 'true') else: self.local_settings.setSetting('All', 'false') if self.checkbox1.isSelected(): self.local_settings.setSetting('Application', 'true') else: self.local_settings.setSetting('Application', 'false') if self.checkbox2.isSelected(): self.local_settings.setSetting('Security', 'true') else: self.local_settings.setSetting('Security', 'false') if self.checkbox3.isSelected(): self.local_settings.setSetting('System', 'true') else: self.local_settings.setSetting('System', 'false') if self.checkbox4.isSelected(): self.local_settings.setSetting('Other', 'true') self.local_settings.setSetting('EventLogs', self.area.getText()) else: self.local_settings.setSetting('Other', 'false') def keyPressed(self, event): self.local_settings.setSetting('EventLogs', self.area.getText()) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("All Logs", actionPerformed=self.checkBoxEvent) self.checkbox1 = JCheckBox("Application.Evtx", actionPerformed=self.checkBoxEvent) self.checkbox2 = JCheckBox("Security.EVTX", actionPerformed=self.checkBoxEvent) self.checkbox3 = JCheckBox("System.EVTX", actionPerformed=self.checkBoxEvent) self.checkbox4 = JCheckBox( "Other - Input in text area below then check this box", actionPerformed=self.checkBoxEvent) self.panel1.add(self.checkbox) self.panel1.add(self.checkbox1) self.panel1.add(self.checkbox2) self.panel1.add(self.checkbox3) self.panel1.add(self.checkbox4) self.add(self.panel1) self.area = JTextArea(5, 25) #self.area.addKeyListener(self) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected( self.local_settings.getSetting('All') == 'true') self.checkbox1.setSelected( self.local_settings.getSetting('Application') == 'true') self.checkbox2.setSelected( self.local_settings.getSetting('Security') == 'true') self.checkbox3.setSelected( self.local_settings.getSetting('System') == 'true') self.checkbox4.setSelected( self.local_settings.getSetting('Other') == 'true') self.area.setText(self.local_settings.getSetting('EventLogs')) # Return the settings used def getSettings(self): return self.local_settings
class View: def __init__(self): self.data = Data() self.checklist = self.data.get_checklist() self.issues = self.data.get_issues() self.set_checklist_tree() self.set_tree() self.set_pane() self.set_tabbed_panes() self.set_settings() self.set_tsl() def set_callbacks(self, callbacks): self.callbacks = callbacks def set_checklist(self, file_name): self.data.set_checklist(file_name) self.checklist = self.data.get_checklist() def get_checklist(self): return self.checklist def get_issues(self): return self.issues # TODO: Create the checklist dynamically for all nodes based on JSON structure # Creates a DefaultMutableTreeNode using the JSON file data def set_checklist_tree(self): self.checklist_tree = DefaultMutableTreeNode("HUNT - Methodology") for item in self.checklist: node = DefaultMutableTreeNode(item) self.checklist_tree.add(node) is_functionality = node.toString() == "Functionality" if is_functionality: functionality_node = node functionality = self.checklist["Functionality"] # Sorts the functionality by name and by test name functionality_list = [] for functionality_name in functionality: functionality_list.append(functionality_name) for functionality_name in sorted(functionality_list): tests = functionality[functionality_name]["tests"] node = DefaultMutableTreeNode(functionality_name) tests_list = [] for test_name in tests: tests_list.append(test_name) for test_name in sorted(tests_list): node.add(DefaultMutableTreeNode(test_name)) functionality_node.add(node) def get_checklist_tree(self): return self.checklist_tree # Creates a JTree object from the checklist def set_tree(self): self.tree = JTree(self.checklist_tree) self.tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION) def get_tree(self): return self.tree # TODO: Change to briefcase icon for brief, P1-P5 icons for vulns, # bullseye icon for Targets, etc # Create a JSplitPlane with a JTree to the left and JTabbedPane to right def set_pane(self): status = JTextArea() status.setLineWrap(True) status.setText("Nothing selected") self.status = status self.pane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JScrollPane(self.tree), JTabbedPane()) self.pane.setDividerLocation(310) self.pane.getLeftComponent().setMinimumSize(Dimension(310, 300)) def get_pane(self): return self.pane # Creates the tabs dynamically using data from the JSON file def set_tabbed_panes(self): functionality = self.checklist["Functionality"] self.tabbed_panes = {} for functionality_name in functionality: tests = functionality[functionality_name]["tests"] for test_name in tests: key = functionality_name + "." + test_name tabbed_pane = self.set_tabbed_pane(functionality_name, test_name) self.tabbed_panes[key] = self.tabbed_pane def get_tabbed_panes(self): return self.tabbed_panes # Creates a JTabbedPane for each vulnerability per functionality def set_tabbed_pane(self, functionality_name, test_name): description_tab = self.set_description_tab(functionality_name, test_name) bugs_tab = self.set_bugs_tab() resources_tab = self.set_resource_tab(functionality_name, test_name) notes_tab = self.set_notes_tab() self.tabbed_pane = JTabbedPane() self.tabbed_pane.add("Description", description_tab) self.tabbed_pane.add("Bugs", bugs_tab) self.tabbed_pane.add("Resources", resources_tab) self.tabbed_pane.add("Notes", notes_tab) # Creates the description panel def set_description_tab(self, fn, vn): description_text = str( self.checklist["Functionality"][fn]["tests"][vn]["description"]) description_textarea = JTextArea() description_textarea.setLineWrap(True) description_textarea.setText(description_text) description_panel = JScrollPane(description_textarea) return description_panel # TODO: Add functionality to remove tabs # Creates the bugs panel def set_bugs_tab(self): bugs_tab = JTabbedPane() return bugs_tab # Creates the resources panel def set_resource_tab(self, fn, vn): resource_urls = self.checklist["Functionality"][fn]["tests"][vn][ "resources"] resource_text = "" for url in resource_urls: resource_text = resource_text + str(url) + "\n" resource_textarea = JTextArea() resource_textarea.setLineWrap(True) resource_textarea.setWrapStyleWord(True) resource_textarea.setText(resource_text) resources_panel = JScrollPane(resource_textarea) return resources_panel def set_notes_tab(self): notes_textarea = JTextArea() return notes_textarea def set_tsl(self): self.tsl = TSL(self) self.tree.addTreeSelectionListener(self.tsl) return def get_tsl(self): return self.tsl def set_settings(self): self.settings = JPanel() layout = GroupLayout(self.settings) self.settings.setLayout(layout) layout.setAutoCreateGaps(True) load_file_button = JButton("Load JSON File") load_file_button.setActionCommand("load") load_file_button.addActionListener( SettingsAction(self, load_file_button, None)) save_file_button = JButton("Save JSON File") save_file_button.setActionCommand("save") save_file_button.addActionListener( SettingsAction(None, save_file_button, self.tabbed_panes)) horizontal_group1 = layout.createParallelGroup( GroupLayout.Alignment.LEADING) horizontal_group1.addComponent(load_file_button) horizontal_group1.addComponent(save_file_button) horizontal_group = layout.createSequentialGroup() horizontal_group.addGroup(horizontal_group1) layout.setHorizontalGroup(horizontal_group) vertical_group1 = layout.createParallelGroup( GroupLayout.Alignment.BASELINE) vertical_group1.addComponent(load_file_button) vertical_group2 = layout.createParallelGroup( GroupLayout.Alignment.BASELINE) vertical_group2.addComponent(save_file_button) vertical_group = layout.createSequentialGroup() vertical_group.addGroup(vertical_group1) vertical_group.addGroup(vertical_group2) layout.setVerticalGroup(vertical_group) def get_settings(self): return self.settings def set_request_tab_pane(self, request_response): raw_request = request_response.getRequest() request_body = StringUtil.fromBytes(raw_request) request_body = request_body.encode("utf-8") request_tab_textarea = self.callbacks.createTextEditor() component = request_tab_textarea.getComponent() request_tab_textarea.setText(request_body) request_tab_textarea.setEditable(False) return component def set_response_tab_pane(self, request_response): raw_response = request_response.getResponse() response_body = StringUtil.fromBytes(raw_response) response_body = response_body.encode("utf-8") response_tab_textarea = self.callbacks.createTextEditor() component = response_tab_textarea.getComponent() response_tab_textarea.setText(response_body) response_tab_textarea.setEditable(False) return component def set_bugs_tabbed_pane(self, request_tab, response_tab): bugs_tabbed_pane = JTabbedPane() bugs_tabbed_pane.add("Request", request_tab) bugs_tabbed_pane.add("Response", response_tab) return bugs_tabbed_pane
def getUiComponent(self): panel = JPanel(BorderLayout()) panel.setLocation(100, 100) panel.setLayout(None) lbl1 = JLabel("Insert URL") lbl1.setBounds(60, 20, 100, 40) txt1 = JTextField(100) txt1.setBounds(140, 20, 600, 40) def btn1Click(event): import requests from bs4 import BeautifulSoup url = requests.get("http://" + str(txt1.text)) # a=requests.get(str(txt1.text)) req = url.text links = [] soup = BeautifulSoup(url.text, 'html.parser') for link in soup.find_all('a'): links.append(link.get('href')) links = ((str(links).replace("[", "")).replace("]", "")).replace("u'", "'") txt2.text = links #set info por table2 txt2.editable = False txt2.wrapStyleWord = True txt2.lineWrap = True text2.aligmentx = Component.LEFT_ALIGMENT txt2.size(300, 1) return btn = JButton("Click", actionPerformed=btn1Click) btn.setBounds(400, 80, 60, 30) panel.add(lbl1, BorderLayout.CENTER) panel.add(txt1, BorderLayout.CENTER) panel.add(btn, BorderLayout.CENTER) lbl2 = JLabel("Output URLs") lbl2.setBounds(60, 80, 150, 40) txt2 = JTextArea() txt2.setBounds(140, 120, 600, 600) txt2.setBackground(Color.WHITE) # set table color, if you want panel.add(lbl2, BorderLayout.CENTER) panel.add(txt2, BorderLayout.CENTER) return panel
class BurpExtender(IBurpExtender, ITab): def registerExtenderCallbacks(self, callbacks): print "Loading..." self._callbacks = callbacks self._callbacks.setExtensionName('Burp SSL Scanner') # self._callbacks.registerScannerCheck(self) # self._callbacks.registerExtensionStateListener(self) self._helpers = callbacks.getHelpers() # initialize the main scanning event and thread self.scanningEvent = Event() self.scannerThread = None self.targetURL = None # main split pane self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20)) # sub split pane (top) self._topPanel = JPanel(BorderLayout(10, 10)) self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0)) # Setup Panel : [Target: ] [______________________] [START BUTTON] self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.setupPanel.add( JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START) self.hostField = JTextField('', 50) self.setupPanel.add(self.hostField) self.toggleButton = JButton( 'Start scanning', actionPerformed=self.startScan) self.setupPanel.add(self.toggleButton) if 'Professional' in callbacks.getBurpVersion()[0] : self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True) else : self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False) self.addToSitemapCheckbox.setEnabled(False) self.setupPanel.add(self.addToSitemapCheckbox) self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True) self.setupPanel.add(self.scanSiteMapHostCheckbox) self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START) # Status bar self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT)) self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT) self.scanStatusPanel.add(self.scanStatusLabel) self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START) self._splitpane.setTopComponent(self._topPanel) # bottom panel self._bottomPanel = JPanel(BorderLayout(10, 10)) self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0)) self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />' 'Please note that TLS1.3 is still not supported by this extension.</h1>') self.currentText = self.initialText self.textPane = JTextPane() self.textScrollPane = JScrollPane(self.textPane) self.textPane.setContentType("text/html") self.textPane.setText(self.currentText) self.textPane.setEditable(False) self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER) self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10)) self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile) self.saveButton.setEnabled(False) self.savePanel.add(self.saveButton) self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost) self.savePanel.add(self.clearScannedHostButton) self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT)) self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END) self._splitpane.setBottomComponent(self._bottomPanel) callbacks.customizeUiComponent(self._splitpane) callbacks.addSuiteTab(self) print "SSL Scanner tab loaded" self.scannerMenu = ScannerMenu(self) callbacks.registerContextMenuFactory(self.scannerMenu) print "SSL Scanner custom menu loaded" self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected) callbacks.registerScannerCheck(self.scannerCheck) print "SSL Scanner check registered" projectConfig = json.loads(self._callbacks.saveConfigAsJson()) scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy'] scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed'] print(scanAccuracy, scanSpeed) self.scannedHost = [] print 'SSL Scanner loaded' def startScan(self, ev) : host = self.hostField.text self.scanningEvent.set() if(len(host) == 0): return if host.find("://") == -1: host = "https://" + host try: self.targetURL = URL(host) if(self.targetURL.getPort() == -1): self.targetURL = URL("https", self.targetURL.getHost(), 443, "/") self.hostField.setEnabled(False) self.toggleButton.setEnabled(False) self.saveButton.setEnabled(False) self.addToSitemapCheckbox.setEnabled(False) self.currentText = self.initialText self.textPane.setText(self.currentText) self.updateText("<h2>Scanning %s:%d</h2>" % (self.targetURL.getHost(), self.targetURL.getPort())) print("Scanning %s:%d" % (self.targetURL.getHost(), self.targetURL.getPort())) self.scannerThread = Thread(target=self.scan, args=(self.targetURL, )) self.scannerThread.start() except BaseException as e: self.saveButton.setEnabled(False) print(e) return def scan(self, url, usingBurpScanner=False): def setScanStatusLabel(text) : if not usingBurpScanner : SwingUtilities.invokeLater( ScannerRunnable(self.scanStatusLabel.setText, (text,))) def updateResultText(text) : if not usingBurpScanner : SwingUtilities.invokeLater( ScannerRunnable(self.updateText, (text, ))) if usingBurpScanner : res = result.Result(url, self._callbacks, self._helpers, False) else : res = result.Result(url, self._callbacks, self._helpers, self.addToSitemapCheckbox.isSelected()) host, port = url.getHost(), url.getPort() ### Get project configuration projectConfig = json.loads(self._callbacks.saveConfigAsJson()) if 'scanner' in projectConfig: # scanAccuracy: minimise_false_negatives, normal, minimise_false_positives scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy'] # scanSpeed: fast, normal, thorough scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed'] else: scanAccuracy = 'normal' scanSpeed = 'normal' updateResultText('<h2>Scanning speed: %s</h2> %s' % (scanSpeed, test_details.SCANNING_SPEED_INFO[scanSpeed])) updateResultText('<h2>Scanning accuracy: %s</h2> %s' % (scanAccuracy, test_details.SCANNING_ACCURACY_INFO[scanAccuracy])) try : setScanStatusLabel("Checking for supported SSL/TLS versions") con = connection_test.ConnectionTest(res, host, port, scanSpeed, scanAccuracy) con.start() conResultText = '<hr /><br /><h3>' + res.printResult('connectable') + '</h3>' + \ '<ul><li>' + res.printResult('offer_ssl2') + '</li>' + \ '<li>' + res.printResult('offer_ssl3') + '</li>' + \ '<li>' + res.printResult('offer_tls10') + '</li>' + \ '<li>' + res.printResult('offer_tls11') + '</li>' + \ '<li>' + res.printResult('offer_tls12') + '</li></ul>' updateResultText(conResultText) if not res.getResult('connectable') : updateResultText("<h2>Scan terminated (Connection failed)</h2>") raise BaseException('Connection failed') setScanStatusLabel("Checking for supported cipher suites (This can take a long time)") supportedCipher = supportedCipher_test.SupportedCipherTest(res, host, port, scanSpeed, scanAccuracy) supportedCipher.start() setScanStatusLabel("Checking for Cipherlist") cipher = cipher_test.CipherTest(res, host, port, scanSpeed, scanAccuracy) cipher.start() cipherResultText = '<h3>Available ciphers:</h3>' + \ '<ul><li>' + res.printResult('cipher_NULL') + '</li>' + \ '<li>' + res.printResult('cipher_ANON') + '</li>' + \ '<li>' + res.printResult('cipher_EXP') + '</li>' + \ '<li>' + res.printResult('cipher_LOW') + '</li>' + \ '<li>' + res.printResult('cipher_WEAK') + '</li>' + \ '<li>' + res.printResult('cipher_3DES') + '</li>' + \ '<li>' + res.printResult('cipher_HIGH') + '</li>' + \ '<li>' + res.printResult('cipher_STRONG') + '</li></ul>' updateResultText(cipherResultText) setScanStatusLabel("Checking for Heartbleed") heartbleed = heartbleed_test.HeartbleedTest(res, host, port, scanSpeed, scanAccuracy) heartbleed.start() heartbleedResultText = res.printResult('heartbleed') updateResultText(heartbleedResultText) setScanStatusLabel("Checking for CCS Injection") ccs = ccs_test.CCSTest(res, host, port, scanSpeed, scanAccuracy) ccs.start() ccsResultText = res.printResult('ccs_injection') updateResultText(ccsResultText) setScanStatusLabel("Checking for TLS_FALLBACK_SCSV") fallback = fallback_test.FallbackTest(res, host, port, scanSpeed, scanAccuracy) fallback.start() fallbackResultText = res.printResult('fallback_support') updateResultText(fallbackResultText) setScanStatusLabel("Checking for POODLE (SSLv3)") poodle = poodle_test.PoodleTest(res, host, port, scanSpeed, scanAccuracy) poodle.start() poodleResultText = res.printResult('poodle_ssl3') updateResultText(poodleResultText) setScanStatusLabel("Checking for SWEET32") sweet32 = sweet32_test.Sweet32Test(res, host, port, scanSpeed, scanAccuracy) sweet32.start() sweet32ResultText = res.printResult('sweet32') updateResultText(sweet32ResultText) setScanStatusLabel("Checking for DROWN") drown = drown_test.DrownTest(res, host, port, scanSpeed, scanAccuracy) drown.start() drownResultText = res.printResult('drown') updateResultText(drownResultText) setScanStatusLabel("Checking for FREAK") freak = freak_test.FreakTest(res, host, port, scanSpeed, scanAccuracy) freak.start() freakResultText = res.printResult('freak') updateResultText(freakResultText) setScanStatusLabel("Checking for LUCKY13") lucky13 = lucky13_test.Lucky13Test(res, host, port, scanSpeed, scanAccuracy) lucky13.start() lucky13ResultText = res.printResult('lucky13') updateResultText(lucky13ResultText) setScanStatusLabel("Checking for CRIME") crime = crime_test.CrimeTest(res, host, port, scanSpeed, scanAccuracy) crime.start() crimeResultText = res.printResult('crime_tls') updateResultText(crimeResultText) setScanStatusLabel("Checking for BREACH") breach = breach_test.BreachTest(res, host, port, scanSpeed, scanAccuracy) breach.start(self._callbacks, self._helpers) breachResultText = res.printResult('breach') updateResultText(breachResultText) setScanStatusLabel("Checking for BEAST") beast = beast_test.BeastTest(res, host, port, scanSpeed, scanAccuracy) beast.start() beastResultText = res.printResult('beast') updateResultText(beastResultText) setScanStatusLabel("Checking for LOGJAM") logjam = logjam_test.LogjamTest(res, host, port, scanSpeed, scanAccuracy) logjam.start() logjamResultText = res.printResult('logjam_export') + '<br />' + res.printResult('logjam_common') updateResultText(logjamResultText) updateResultText('<h2>Finished scanning</h2><br /><hr /><br /><h2>Summary</h2>') updateResultText('<h2>Supported ciphers (by Protocol)</h2>') updateResultText(res.printCipherList()) updateResultText('<h2>Supported ciphers (by Vulnerability)</h2>') updateResultText(res.printCipherListByVulns()) updateResultText('<h2>Issues found</h2>') updateResultText(res.printAllIssue()) except BaseException as e : print(e) setScanStatusLabel("An error occurred. Please refer to the output/errors tab for more information.") time.sleep(2) if usingBurpScanner : return res.getAllIssue() else : self.scanningEvent.clear() SwingUtilities.invokeLater( ScannerRunnable(self.toggleButton.setEnabled, (True, )) ) SwingUtilities.invokeLater( ScannerRunnable(self.hostField.setEnabled, (True, )) ) SwingUtilities.invokeLater( ScannerRunnable(self.saveButton.setEnabled, (True, )) ) if 'Professional' in self._callbacks.getBurpVersion()[0] : SwingUtilities.invokeLater( ScannerRunnable(self.addToSitemapCheckbox.setEnabled, (True, )) ) setScanStatusLabel("Ready to scan") print("Finished scanning") def updateText(self, stringToAppend): self.currentText += ('<br />' + stringToAppend) self.textPane.setText(self.currentText) def saveToFile(self, event): fileChooser = JFileChooser() if not (self.targetURL is None): fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result_%s.html" \ % (self.targetURL.getHost()))) else: fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result.html")) if (fileChooser.showSaveDialog(self.getUiComponent()) == JFileChooser.APPROVE_OPTION): fw = FileWriter(fileChooser.getSelectedFile()) fw.write(self.textPane.getText()) fw.flush() fw.close() print "Saved results to disk" def clearScannedHost(self, event) : self.scannedHost = [] def addHostToScannedList(self, host, port) : self.scannedHost.append([host, port]) def getTabCaption(self): return "SSL Scanner" def getUiComponent(self): return self._splitpane