def __initDropDownBox(self, table): smells = [ x[0].label for x in groupBy((entity == 'smell'), label)] smells.sort() smells.remove('ForTestersOnly') dropdown = JComboBox(jarray.array(smells, String)) dropdown.addActionListener(DropDownListener(table)) self.add(dropdown, self.__createDropDownConstraints())
def get_loss_type_combo(self): combo_box = JComboBox() combo_model = DefaultComboBoxModel() combo_model.addElement("random") combo_model.addElement("state") combo_model.addElement("gemodel") combo_box.setModel(combo_model) combo_box.setMaximumSize(Dimension(120, 20)) combo_box.addActionListener( self.ComboListener(self.loss_random_items, self.loss_state_items, self.loss_gemodel_items)) return combo_box
class GlobalPanel(JPanel, ActionListener): def __init__(self,options): self.options=options self.layout=BoxLayout(self,BoxLayout.Y_AXIS) self.opt_color=JCheckBox('Colour',True,actionPerformed=self.options.changed) self.add(self.opt_color) self.dpi=JTextField('80',actionPerformed=self.options.changed) self.add(make_option('dpi',self.dpi)) self.metrics=JComboBox(['mean','median','sd','var'],editable=False) self.metrics.selectedIndex=0 self.metrics.addActionListener(self) self.add(make_option('metric',self.metrics)) def actionPerformed(self,event): self.options.changed(event)
class LineTab(JPanel,ActionListener): def __init__(self,options): self.options=options self.layout=BoxLayout(self,BoxLayout.Y_AXIS) self.area=JCheckBox('CI area',False,actionPerformed=self.options.changed) self.add(self.area) self.x_axis=JComboBox(['equal','linear','log'],editable=False) self.x_axis.selectedIndex=0 self.x_axis.addActionListener(self) self.y_axis=JComboBox(['linear','log'],editable=False) self.y_axis.selectedIndex=0 self.y_axis.addActionListener(self) axis=JPanel(border=BorderFactory.createTitledBorder('axis')) axis.layout=BoxLayout(axis,BoxLayout.X_AXIS) axis.add(JLabel('x:')) axis.add(self.x_axis) axis.add(JLabel('y:')) axis.add(self.y_axis) axis.maximumSize=axis.minimumSize self.add(axis) def actionPerformed(self,event): self.options.changed(event)
def initProfilesTable(self): profile_table = JTable() self.profile_table_model = self.ProfileTableModel() profile_table.setModel(self.profile_table_model) cm = profile_table.getColumnModel() # Set column widths for i in range(0, 4): width = self.profile_table_model.column_widths.get(i) if width is not None: column = cm.getColumn(i) column.setPreferredWidth(width) column.setMaxWidth(width) profile_table.setFillsViewportHeight(True) def doAction(event): print event # Add the actions dropdown actionCol = cm.getColumn(3) actions = JComboBox() actions.addItem("Activate") actions.addItem("Unactivate") actions.addItem("Edit") actions.addItem("Export to Script") actions.addItem("Delete") actionCol.setCellEditor(DefaultCellEditor(actions)) self.profile_table_model.actions_combo = actions renderer = self.ComboBoxTableCellRenderer() actionCol.setCellRenderer(renderer) actions.addActionListener(self.ComboActionListener(self)) return profile_table
class EventsPane(WindowPane, ActionListener, DocumentListener): def __init__(self, window, api): self.api = api self.component = JPanel(BorderLayout()) # Create editor pane scrollpane = JScrollPane() self.script_area = InputPane(window) self.script_area.undo = UndoManager() 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) # Create Selection pane select_pane = JPanel() self.objects_box = JComboBox([], actionCommand="object") select_pane.add(self.objects_box) self.events_box = JComboBox( ["update", "click"], actionCommand="event" ) self.event_types = [EventType.UPDATE, EventType.CLICK] select_pane.add(self.events_box) self.languages = list(ScriptType.values()) self.language_box = JComboBox( [l.getName() for l in self.languages], actionCommand="language" ) select_pane.add(self.language_box) self.save_btn = JButton("Save") select_pane.add(self.save_btn) self.component.add(select_pane, BorderLayout.PAGE_START) self.events_box.addActionListener(self) self.objects_box.addActionListener(self) self.language_box.addActionListener(self) self.save_btn.addActionListener(self) self.current = None self.update_geos() interface.addEventListener("add", self.event_listener) interface.addEventListener("remove", self.event_listener) interface.addEventListener("rename", self.event_listener) # Listen to script_area changes in order to know when the save # button can be activated self.script_area.doc.addDocumentListener(self) # Hack to be able to change the objects_box self.building_objects_box = False self.active = False def activate(self): self.active = True if self.must_update_geos: self.update_geos() def deactivate(self): self.active = False def indent_selection(self): return self.script_area.indent_selection() def dedent_selection(self): return self.script_area.dedent_selection() def update_geos(self): self.must_update_geos = False try: self.building_objects_box = True self.objects_box.removeAllItems() self.geos = self.api.getAllGeos() for geo in self.geos: tp = API.Geo.getTypeString(geo) label = API.Geo.getLabel(geo) self.objects_box.addItem(tp + " " + label) finally: self.building_objects_box = False if not self.geos: self.current = None self.objects_box.enabled = False self.events_box.enabled = False self.language_box.enabled = False self.script_area.input = "" self.script_area.component.enabled = False else: changed = False if self.current is None: index, event = 0, 1 changed = True else: geo, event = self.current try: index = self.geos.index(geo) except ValueError: index, event = 0, 1 changed = True self.events_box.selectedIndex = event self.objects_box.selectedIndex = index self.events_box.enabled = True self.objects_box.enabled = True self.language_box.enabled = True self.script_area.component.enabled = True if changed: self.update_script_area() self.objects_box.repaint() self.events_box.repaint() def event_listener(self, evt, target): if self.active: self.update_geos() else: self.must_update_geos = True def current_script_changed(self): self.save_btn.enabled = True def set_save_btn(self, state): self.save_btn.enabled = state def save_current_script(self): if self.current is not None: geo, evt = self.current lang = self.language_box.selectedIndex evt, lang = self.event_types[evt], self.languages[lang] script = self.script_area.input self.api.setScript(geo, script, evt, lang) def update_script_area(self): self.save_current_script() geo_index = self.objects_box.selectedIndex if geo_index == -1: self.current = None else: geo = self.geos[geo_index] evt = self.events_box.selectedIndex self.current = geo, evt script = API.Geo.getScript(geo, self.event_types[evt]) if script is None: self.script_area.input = "" else: self.script_area.input = API.getScriptText(script) self.language_box.selectedIndex = API.getScriptType(script).ordinal() self.script_area.reset_undo() later(self.set_save_btn, False) def reset(self): self.current = None self.update_geos() # Implementation of ActionListener def actionPerformed(self, evt): if self.building_objects_box: return if evt.actionCommand == "language": self.save_btn.enabled = True else: self.update_script_area() # Implementation of DocumentListener def changedUpdate(self, evt): self.current_script_changed() def removeUpdate(self, evt): self.current_script_changed() def insertUpdate(self, evt): self.current_script_changed()
def __init__(self): self.setLayout(GridBagLayout()) self.setBorder(make_title_border("API")) self.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.status = StatusText(25) self.add(JLabel("Status :"), gridx=0) self.add(self.status, gridx=1) self.version = StatusText(25) self.version.set(context.version, bg=Color.GRAY) self.add(JLabel("Version :"), gridx=0) self.add(self.version, gridx=1) settings = context.settings txt_url = JTextField(25) txt_url.setText(settings.load("apiurl", "https://api.yeswehack.com/")) self.add(JLabel("API URL :"), gridx=0) self.add(txt_url, gridx=1) combo_auth = JComboBox((AuthMethod.anonymous, AuthMethod.email_pass)) combo_auth.setSelectedItem( settings.load("auth_method", AuthMethod.anonymous)) combo_auth.addActionListener( CallbackActionListener(self.auth_method_changed)) self.add(JLabel("Authentication :"), gridx=0) self.add(combo_auth, gridx=1) txt_mail = JTextField(25) txt_mail.setText(settings.load("email")) self.add(JLabel("Email :"), gridx=0) self.add(txt_mail, gridx=1) txt_pass = JPasswordField(25) txt_pass.setText(settings.load("password")) self.add(JLabel("Password :"******"remember", True)) self.add(JLabel("Remember password :"******"Connect") btn_connect.addActionListener(CallbackActionListener(self.submit)) self.add(btn_connect, gridx=1, anchor=EAST) self.inputs = { "apiurl": txt_url, "auth_method": combo_auth, "email": txt_mail, "password": txt_pass, "remember": check_remember, "connect": btn_connect, } self.setMaximumSize(self.getPreferredSize()) self.auth_method_changed() async_call(self.update_status)
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener): """ generated source for class ConfigurableConfigPanel """ serialVersionUID = 1L associatedFile = File() associatedFileField = JTextField() params = JSONObject() savedParams = str() loadButton = JButton() saveAsButton = JButton() saveButton = JButton() name = JTextField() strategy = JComboBox() metagameStrategy = JComboBox() stateMachine = JComboBox() cacheStateMachine = JCheckBox() maxPlys = JSpinner() heuristicFocus = JSpinner() heuristicMobility = JSpinner() heuristicOpponentFocus = JSpinner() heuristicOpponentMobility = JSpinner() mcDecayRate = JSpinner() rightPanel = JPanel() def __init__(self): """ generated source for method __init__ """ super(ConfigurableConfigPanel, self).__init__(GridBagLayout()) leftPanel = JPanel(GridBagLayout()) leftPanel.setBorder(TitledBorder("Major Parameters")) self.rightPanel = JPanel(GridBagLayout()) self.rightPanel.setBorder(TitledBorder("Minor Parameters")) self.strategy = JComboBox([None]*) self.metagameStrategy = JComboBox([None]*) self.stateMachine = JComboBox([None]*) self.cacheStateMachine = JCheckBox() self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1)) self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1)) self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1)) self.name = JTextField() self.name.setColumns(20) self.name.setText("Player #" + Random().nextInt(100000)) self.loadButton = JButton(loadButtonMethod()) self.saveButton = JButton(saveButtonMethod()) self.saveAsButton = JButton(saveAsButtonMethod()) self.associatedFileField = JTextField() self.associatedFileField.setEnabled(False) buttons = JPanel() buttons.add(self.loadButton) buttons.add(self.saveButton) buttons.add(self.saveAsButton) nRow = 0 leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_0 = nRow nRow += 1 leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_1 = nRow nRow += 1 leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_2 = nRow nRow += 1 leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_3 = nRow nRow += 1 leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5)) __nRow_4 = nRow nRow += 1 leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0)) leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0)) layoutRightPanel() add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5)) self.params = JSONObject() syncJSONtoUI() self.strategy.addActionListener(self) self.metagameStrategy.addActionListener(self) self.stateMachine.addActionListener(self) self.cacheStateMachine.addActionListener(self) self.maxPlys.addChangeListener(self) self.heuristicFocus.addChangeListener(self) self.heuristicMobility.addChangeListener(self) self.heuristicOpponentFocus.addChangeListener(self) self.heuristicOpponentMobility.addChangeListener(self) self.mcDecayRate.addChangeListener(self) self.name.getDocument().addDocumentListener(self) def layoutRightPanel(self): """ generated source for method layoutRightPanel """ nRow = 0 self.rightPanel.removeAll() self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_5 = nRow nRow += 1 self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) if self.strategy.getSelectedItem().__str__() == "Heuristic": __nRow_6 = nRow nRow += 1 __nRow_7 = nRow nRow += 1 __nRow_8 = nRow nRow += 1 __nRow_9 = nRow nRow += 1 __nRow_10 = nRow nRow += 1 self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) if self.strategy.getSelectedItem().__str__() == "Monte Carlo": __nRow_11 = nRow nRow += 1 self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) __nRow_12 = nRow nRow += 1 self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5)) self.rightPanel.repaint() @SuppressWarnings("unchecked") def getParameter(self, name, defaultValue): """ generated source for method getParameter """ try: if self.params.has(name): return self.params.get(name) else: return defaultValue except JSONException as je: return defaultValue def actionPerformed(self, arg0): """ generated source for method actionPerformed """ if arg0.getSource() == self.strategy: self.layoutRightPanel() syncJSONtoUI() def changedUpdate(self, e): """ generated source for method changedUpdate """ syncJSONtoUI() def insertUpdate(self, e): """ generated source for method insertUpdate """ syncJSONtoUI() def removeUpdate(self, e): """ generated source for method removeUpdate """ syncJSONtoUI() def stateChanged(self, arg0): """ generated source for method stateChanged """ syncJSONtoUI() def syncJSONtoUI(self): """ generated source for method syncJSONtoUI """ if settingUI: return self.params = getJSONfromUI() self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams) def getJSONfromUI(self): """ generated source for method getJSONfromUI """ newParams = JSONObject() try: if not self.name.getText().isEmpty(): newParams.put("name", self.name.getText()) newParams.put("strategy", self.strategy.getSelectedItem().__str__()) newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__()) newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__()) newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected()) newParams.put("maxPlys", self.maxPlys.getModel().getValue()) newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue()) newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue()) newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue()) newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue()) newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue()) except JSONException as je: je.printStackTrace() return newParams settingUI = False def setUIfromJSON(self): """ generated source for method setUIfromJSON """ self.settingUI = True try: if self.params.has("name"): self.name.setText(self.params.getString("name")) if self.params.has("strategy"): self.strategy.setSelectedItem(self.params.getString("strategy")) if self.params.has("metagameStrategy"): self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy")) if self.params.has("stateMachine"): self.stateMachine.setSelectedItem(self.params.getString("stateMachine")) if self.params.has("cacheStateMachine"): self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine")) if self.params.has("maxPlys"): self.maxPlys.getModel().setValue(self.params.getInt("maxPlys")) if self.params.has("heuristicFocus"): self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus")) if self.params.has("heuristicMobility"): self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility")) if self.params.has("heuristicOpponentFocus"): self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus")) if self.params.has("heuristicOpponentMobility"): self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility")) if self.params.has("mcDecayRate"): self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate")) except JSONException as je: je.printStackTrace() finally: self.settingUI = False def loadParamsJSON(self, fromFile): """ generated source for method loadParamsJSON """ if not fromFile.exists(): return self.associatedFile = fromFile self.associatedFileField.setText(self.associatedFile.getPath()) self.params = JSONObject() try: try: while (line = br.readLine()) != None: pdata.append(line) finally: br.close() self.params = JSONObject(pdata.__str__()) self.savedParams = self.params.__str__() self.setUIfromJSON() self.syncJSONtoUI() except Exception as e: e.printStackTrace() def saveParamsJSON(self, saveAs): """ generated source for method saveParamsJSON """ try: if saveAs or self.associatedFile == None: fc.setFileFilter(PlayerFilter()) if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None: if toFile.__name__.contains("."): self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player") else: self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player") self.associatedFileField.setText(self.associatedFile.getPath()) else: return bw.write(self.params.__str__()) bw.close() self.savedParams = self.params.__str__() self.syncJSONtoUI() except IOException as ie: ie.printStackTrace() def saveButtonMethod(self): """ generated source for method saveButtonMethod """ return AbstractAction("Save") def saveAsButtonMethod(self): """ generated source for method saveAsButtonMethod """ return AbstractAction("Save As") def loadButtonMethod(self): """ generated source for method loadButtonMethod """ return AbstractAction("Load") class PlayerFilter(FileFilter): """ generated source for class PlayerFilter """ def accept(self, f): """ generated source for method accept """ if f.isDirectory(): return True return f.__name__.endsWith(".player") def getDescription(self): """ generated source for method getDescription """ return "GGP Players (*.player)"
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener): # Define the global variables for the burp plugin EXTENSION_NAME = "UPnP BHunter" ipv4_selected = True services_dict = {} ip_service_dict = {} STOP_THREAD = False #Some SSDP m-search parameters are based upon "UPnP Device Architecture v2.0" SSDP_MULTICAST_IPv4 = ["239.255.255.250"] SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"] SSDP_MULTICAST_PORT = 1900 ST_ALL = "ssdp:all" ST_ROOTDEV = "upnp:rootdevice" PLACEHOLDER = "FUZZ_HERE" SSDP_TIMEOUT = 2 def registerExtenderCallbacks(self, callbacks): # Get a reference to callbacks object self.callbacks = callbacks # Get the useful extension helpers object self.helpers = callbacks.getHelpers() # Set the extension name self.callbacks.setExtensionName(self.EXTENSION_NAME) self.callbacks.registerExtensionStateListener(self) # Draw plugin user interface self.drawPluginUI() self.callbacks.addSuiteTab(self) # Plugin loading message print("[+] Burp plugin UPnP BHunter loaded successfully") return def drawPluginUI(self): # Create the plugin user interface self.pluginTab = JPanel() self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console') self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14)) self.uiTitle.setForeground(Color(250, 100, 0)) self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelA.setMaximumSize(Dimension(2500, 1000)) self.uiPanelA.setDividerSize(2) self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelB.setDividerSize(2) self.uiPanelA.setBottomComponent(self.uiPanelB) self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray)) # Create and configure labels and text fields self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations") self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step2 = JLabel( "[2nd STEP] Select a UPnP Service and Action") self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it") self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14)) self.labelsubtitle_step1 = JLabel( "Specify the IP version address in scope and start UPnP discovery") self.labelsubtitle_step2 = JLabel( "Select which of the found UPnP services will be probed") self.labelsubtitle_step3 = JLabel( "Review and modify the request, then send it to one of the attack tools" ) self.label_step1 = JLabel("Target IP") self.label_step2 = JLabel("Found UPnp Services") self.labelstatus = JLabel(" Status") self.labelempty_step1 = JLabel(" ") self.labelempty_step2 = JLabel(" ") self.labelupnp = JLabel("UPnP list") self.labelip = JLabel("IP list") self.labelactions = JLabel("Actions") self.labelNoneServiceFound = JLabel(" ") self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12)) self.labelNoneServiceFound.setForeground(Color.red) # Create combobox for IP version selection self.ip_versions = ["IPv4", "IPv6"] self.combo_ipversion = JComboBox(self.ip_versions) self.combo_ipversion.setSelectedIndex(0) self.combo_ipversion.setEnabled(True) # Create and configure progress bar self.progressbar = JProgressBar(0, 100) self.progressbar.setString("Ready") self.progressbar.setStringPainted(True) # Create and configure buttons self.startbutton = JButton("Start Discovery", actionPerformed=self.startHunting) self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll) self.intruderbutton = JButton("Send to Intruder", actionPerformed=self.sendToIntruder) self.repeaterbutton = JButton("Send to Repeater", actionPerformed=self.sendToRepeater) #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater) self.textarea_request = JTextArea(18, 90) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Class neeeded to handle the target combobox in second step panel class TargetComboboxListener(ActionListener): def __init__(self, upnpcombo_targets, upnpcombo_services, ip_service_dict): self.upnpcombo_targets = upnpcombo_targets self.upnpcombo_services = upnpcombo_services self.ip_service_dict = ip_service_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_target = self.upnpcombo_targets.getSelectedItem() if self.ip_service_dict and selected_target: self.upnpcombo_services.removeAllItems() for service_url in self.ip_service_dict[ selected_target]: self.upnpcombo_services.addItem(service_url) self.upnpcombo_services.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the service combobox in second step panel class ServiceComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_service: self.upnpcombo_actions.removeAllItems() actions = self.services[selected_service] for action in actions: self.upnpcombo_actions.addItem(action) self.upnpcombo_actions.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the action combobox in second step panel class ActionComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, textarea_request, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.textarea_request = textarea_request self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_action = self.upnpcombo_actions.getSelectedItem() selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_action: self.textarea_request.setText( self.services[selected_service][selected_action]) except BaseException as e: print("[!] Exception selecting action: \"%s\" ") % e self.upnpactions = [" "] self.upnpcombo_actions = JComboBox(self.upnpactions) self.upnpcombo_actions.setSelectedIndex(0) self.upnpcombo_actions.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnpservices = [" "] self.upnpcombo_services = JComboBox(self.upnpservices) self.upnpcombo_services.setSelectedIndex(0) self.upnpcombo_services.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnptargets = [" "] self.upnpcombo_targets = JComboBox(self.upnptargets) self.upnpcombo_targets.setSelectedIndex(0) self.upnpcombo_targets.setEnabled(False) # Set the action listeners for all the comboboxes self.upnpcombo_targets.addActionListener( TargetComboboxListener(self.upnpcombo_targets, self.upnpcombo_services, self.ip_service_dict)) self.upnpcombo_services.addActionListener( ServiceComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.services_dict)) self.upnpcombo_actions.addActionListener( ActionComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.textarea_request, self.services_dict)) # Configuring first step panel self.panel_step1 = JPanel() self.panel_step1.setPreferredSize(Dimension(2250, 100)) self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step1.setLayout(BorderLayout(15, 15)) self.titlepanel_step1 = JPanel() self.titlepanel_step1.setLayout(BorderLayout()) self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH) self.titlepanel_step1.add(self.labelsubtitle_step1) self.targetpanel_step1 = JPanel() self.targetpanel_step1.add(self.label_step1) self.targetpanel_step1.add(self.combo_ipversion) self.targetpanel_step1.add(self.startbutton) self.targetpanel_step1.add(self.clearbutton) self.targetpanel_step1.add(self.labelstatus) self.targetpanel_step1.add(self.progressbar) self.emptypanel_step1 = JPanel() self.emptypanel_step1.setLayout(BorderLayout()) self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST) # Assembling first step panel components self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH) self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST) self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH) self.uiPanelA.setTopComponent(self.panel_step1) # Configure second step panel self.panel_step2 = JPanel() self.panel_step2.setPreferredSize(Dimension(2250, 100)) self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step2.setLayout(BorderLayout(15, 15)) self.titlepanel_step2 = JPanel() self.titlepanel_step2.setLayout(BorderLayout()) self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH) self.titlepanel_step2.add(self.labelsubtitle_step2) self.selectpanel_step2 = JPanel() self.selectpanel_step2.add(self.labelip) self.selectpanel_step2.add(self.upnpcombo_targets) self.selectpanel_step2.add(self.labelupnp) self.selectpanel_step2.add(self.upnpcombo_services) self.selectpanel_step2.add(self.labelactions) self.selectpanel_step2.add(self.upnpcombo_actions) self.emptypanel_step2 = JPanel() self.emptypanel_step2.setLayout(BorderLayout()) self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST) self.emptypanel_step2.add(self.labelNoneServiceFound) # Assembling second step panel components self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH) self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST) self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH) self.uiPanelB.setTopComponent(self.panel_step2) # Configuring third step panel self.panel_step3 = JPanel() self.panel_step3.setPreferredSize(Dimension(2250, 100)) self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step3.setLayout(BorderLayout(15, 15)) self.titlepanel_step3 = JPanel() self.titlepanel_step3.setLayout(BorderLayout()) self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH) self.titlepanel_step3.add(self.labelsubtitle_step3) self.underpanel_step3 = JPanel() self.underpanel_step3.setLayout(BorderLayout()) self.underpanel_step3.add((JScrollPane(self.textarea_request)), BorderLayout.NORTH) self.actionpanel_step3 = JPanel() self.actionpanel_step3.add(self.intruderbutton) self.actionpanel_step3.add(self.repeaterbutton) self.extrapanel_step3 = JPanel() self.extrapanel_step3.setLayout(BorderLayout()) self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST) # Assembling thirdd step panel components self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH) self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST) self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH) self.uiPanelB.setBottomComponent(self.panel_step3) # Assembling the group of all panels layout = GroupLayout(self.pluginTab) self.pluginTab.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(10, 10, 10).addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA)).addContainerGap( 26, Short.MAX_VALUE))) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(15, 15, 15).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20))) def extensionUnloaded(self): # Unload the plugin, and if running stop the background thread if self.upnpcombo_services.isEnabled(): if self.th.isAlive(): print("[+] Stopping thread %s") % self.th.getName() self.STOP_THREAD = True self.th.join() else: print("Thread %s already dead") % self.th.getName() print("[+] Burp plugin UPnP BHunter successfully unloaded") return def getTabCaption(self): return self.EXTENSION_NAME def getUiComponent(self): return self.pluginTab def clearAll(self, e=None): # Reset all data of the plugin self.services_dict.clear() self.progressbar.setString("Ready") self.progressbar.setValue(0) self.upnpcombo_targets.removeAllItems() self.upnpcombo_targets.setEnabled(False) self.upnpcombo_services.removeAllItems() self.upnpcombo_services.setEnabled(False) self.upnpcombo_actions.removeAllItems() self.upnpcombo_actions.setEnabled(False) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) self.labelNoneServiceFound.setText(" ") self.textarea_request.setText(" ") print("[+] Clearing all data") return def startHunting(self, e=None): # Starting the UPnP hunt def startHunting_run(): # Initialize the internal parameters every time the start-discovery button is clicked self.services_dict.clear() found_loc = [] discovery_files = [] self.labelNoneServiceFound.setText(" ") self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Then determine if targerting IPv4 or IPv6 adresses if self.combo_ipversion.getSelectedItem() == "IPv4": self.ipv4_selected = True print("[+] Selected IPv4 address scope") else: self.ipv4_selected = False print("[+] Selected IPv6 address scope") # And here finally the hunt could start self.progressbar.setString("Running...") self.progressbar.setValue(20) found_loc = self.discoverUpnpLocations() self.progressbar.setValue(40) discovery_files = self.downloadXMLfiles(found_loc) self.progressbar.setValue(60) self.buildSOAPs(discovery_files) self.progressbar.setValue(80) self.progressbar.setString("Done") self.progressbar.setValue(100) self.updateComboboxList(self.services_dict) # Update the comboboxes list with the discovered UPnPs if (self.services_dict): self.upnpcombo_targets.setEnabled(True) self.upnpcombo_services.setEnabled(True) self.upnpcombo_actions.setEnabled(True) self.intruderbutton.setEnabled(True) self.repeaterbutton.setEnabled(True) if self.STOP_THREAD: return # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI self.th = threading.Thread(target=startHunting_run) #self.th.daemon = True # This does not seem to be useful self.th.setName("th-BHunter") self.th.start() def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port): # Builder of the two ssdp msearch request types msearch_req = "M-SEARCH * HTTP/1.1\r\n" \ "HOST: {0}:{1}\r\n" \ "MAN: \"ssdp:discover\"\r\n" \ "MX: {2}\r\n" \ "ST: {3}\r\n" \ "\r\n" \ .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type) return msearch_req def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port): # Send the ssdp request and retrieve response buf_resp = set() if self.ipv4_selected: print("[+] Creating IPv4 SSDP multicast request") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: print("[+] Creating IPv6 SSDP multicast request") sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setblocking(0) # Sending ssdp requests while len(ssdp_req): # Blocking socket client until the request is completely sent try: sent = sock.sendto(ssdp_req.encode("ASCII"), (ssdp_ip, ssdp_port)) ssdp_req = ssdp_req[sent:] except socket.error, exc: if exc.errno != errno.EAGAIN: print("[E] Got error %s with socket when sending") % exc sock.close() raise exc print("[!] Blocking socket until ", len(ssdp_req), " is sent.") select.select([], [sock], []) continue # Retrieving ssdp responses num_resp = 0 while sock: # Blocking socket until there are ssdp responses to be read or timeout is reached readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT) if not readable: # Timeout reached without receiving any ssdp response if num_resp == 0: print( "[!] Got timeout without receiving any ssdp response.") break else: num_resp = num_resp + 1 # Almost an ssdp response was received if readable[0]: try: data = sock.recv(1024) if data: buf_resp.add(data.decode('ASCII')) except socket.error, exc: print("[E] Got error %s with socket when receiving" ) % exc sock.close() raise exc
class DDTabUi(): def __init__(self, ext): self._panel = JPanel() layout = GroupLayout(self._panel) innerPanel = JPanel() innerPanelLayout = GroupLayout(innerPanel) self._panel.setLayout(layout) innerPanel.setLayout(innerPanelLayout) self.labelDojoURL = JLabel("DefectDojo :") self.defectDojoURL = JTextField("") self.searchConnectButton = JButton('Connect', actionPerformed=ext.getProducts) self.labelApiKey = JLabel("API Key :") self.apiKey = JTextField("") self.labelUsername = JLabel("Username :"******"admin") self.labelProductID = JLabel("Product :") self.productID = JTextField(focusLost=ext.getEngagements) self.labelProductName = JLabel("Product Name :") self.productName = JComboBox() self.prodMan = ProdListener(ext) self.prodMouse = ProdMouseListener(ext) self.productName.addMouseListener(self.prodMouse) self.productName.addActionListener(self.prodMan) self.labelEngagementID = JLabel("Engagement (In Progress) :") self.engagementID = JTextField(focusLost=ext.getTests) self.engagementName = JComboBox() self.engMan = EngListener(ext) self.engagementName.addActionListener(self.engMan) self.labelTestID = JLabel("Test :") self.testID = JTextField() self.testName = JComboBox() self.testMan = TestListener(ext) self.testName.addActionListener(self.testMan) self.search = JTextField() self.searchProductButton = JButton('Product Search', actionPerformed=ext.getProducts) innerPanelLayout.setHorizontalGroup( innerPanelLayout.createParallelGroup().addGroup( GroupLayout.Alignment.TRAILING, innerPanelLayout.createSequentialGroup().addContainerGap(). addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING). addGroup(innerPanelLayout.createParallelGroup().addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING).addGroup( innerPanelLayout.createSequentialGroup( ).addComponent( self.labelUsername, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE).addGap( 105, 105, 105)). addComponent(self.labelProductName, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)). addGroup( GroupLayout.Alignment.LEADING, innerPanelLayout.createSequentialGroup().addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING). addComponent( self.labelEngagementID, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE).addComponent( self.labelDojoURL, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)). addPreferredGap( LayoutStyle.ComponentPlacement.RELATED)) ).addGroup(innerPanelLayout.createSequentialGroup( ).addGroup( innerPanelLayout.createParallelGroup().addComponent( self.labelTestID, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE).addComponent( self.searchProductButton, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE)).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED))). addGroup( GroupLayout.Alignment.LEADING, innerPanelLayout.createSequentialGroup().addComponent( self.labelApiKey, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED))). addGroup(innerPanelLayout.createParallelGroup().addGroup( innerPanelLayout.createSequentialGroup().addComponent( self.engagementID, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE).addGap( 18, 18, 18).addComponent(self.engagementName, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE) ).addGroup(innerPanelLayout.createSequentialGroup().addGap( 54, 54, 54).addGroup( innerPanelLayout.createParallelGroup().addComponent( self.defectDojoURL, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE).addComponent( self.apiKey, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE).addComponent( self.user, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE).addComponent( self.productName, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE) )).addGroup( innerPanelLayout.createSequentialGroup().addComponent( self.testID, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18). addGroup(innerPanelLayout.createParallelGroup( ).addComponent( self.search, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE).addComponent( self.testName, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE)))).addGap( 348, 348, 348))) innerPanelLayout.setVerticalGroup(innerPanelLayout.createParallelGroup( ).addGroup(innerPanelLayout.createSequentialGroup().addContainerGap( ).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING, False).addComponent(self.defectDojoURL).addComponent( self.labelDojoURL, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, sys.maxint) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.apiKey, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelApiKey, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.user, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelUsername, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.productName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelProductName, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.engagementName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.engagementID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelEngagementID, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.testName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.testID, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent( self.labelTestID, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE) ).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup( innerPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING, False).addComponent( self.search, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, sys.maxint).addComponent( self.searchProductButton)).addContainerGap( 131, sys.maxint))) layout.setHorizontalGroup(layout.createParallelGroup().addGroup( layout.createSequentialGroup().addComponent( innerPanel, GroupLayout.PREFERRED_SIZE, 633, GroupLayout.PREFERRED_SIZE).addGap(0, 312, sys.maxint))) layout.setVerticalGroup(layout.createParallelGroup().addGroup( layout.createSequentialGroup().addComponent( innerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addGap(0, 199, sys.maxint)))
class GUI(ITab, ActionListener, KeyAdapter): def __init__(self): return def getTabCaption(self): return "BurpExtension" def getUiComponent(self): return self.UI() def UI(self): self.val="" self.tabbedPane = JTabbedPane(JTabbedPane.TOP) self.panel = JPanel() self.tabbedPane.addTab("App Details", None, self.panel, None) # Details of app currently under pentest would be pulled into here through API self.panel_1 = JPanel() self.tabbedPane.addTab("Results", None, self.panel_1, None) # passed results would go inside this and connected to reporting system via API self.panel_2 = JPanel() self.tabbedPane.addTab("Failed Cases", None, self.panel_2, None) #list of failed tests would go inside this self.textField = JTextField() self.textField.setBounds(12, 13, 207, 39) self.panel.add(self.textField) self.textField.setColumns(10) self.comboBox = JComboBox() self.comboBox.setEditable(True) self.comboBox.addItem("Default") self.comboBox.addItem("High") self.comboBox.addItem("Low") self.comboBox.setBounds(46, 65, 130, 28) self.comboBox.addActionListener(self) self.panel.add(self.comboBox) self.btnNewButton = JButton("Submit") self.btnNewButton.setBounds(60, 125, 97, 25) self.panel.add(self.btnNewButton) editorPane = JEditorPane(); editorPane.setBounds(12, 35, 1000, 800); self.panel_2.add(editorPane); self.panel_2.setLayout(BorderLayout()) return self.tabbedPane def getAppRating(self): sys.stdout.write(str(self.val)) return str(self.val) def actionPerformed(self, e): if(e.getSource()==self.comboBox): self.val = self.comboBox.getSelectedItem() else: self.addDetails() def addDetails(self): jf0 = JFrame() jf0.setTitle("Add Issue"); jf0.setLayout(None); txtEnterIssue = JTextField(); txtEnterIssue.setName("Enter Issue Name"); txtEnterIssue.setToolTipText("Enter Issue Name Here"); txtEnterIssue.setBounds(182, 58, 473, 40); jf0.add(txtEnterIssue); txtEnterIssue.setColumns(10); btnNewButton = JButton("Add"); btnNewButton.setBounds(322, 178, 139, 41); jf0.add(btnNewButton); comboBox = JComboBox(); comboBox.setMaximumRowCount(20); comboBox.setEditable(True); comboBox.setToolTipText("Objective Name"); comboBox.setBounds(182, 125, 473, 40); jf0.add(comboBox); lblNewLabel = JLabel("Issue Name Here"); lblNewLabel.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel.setBounds(25, 58, 130, 40); jf0.add(lblNewLabel); lblNewLabel_1 = JLabel("Objective Name"); lblNewLabel_1.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel_1.setBounds(25, 125, 130, 40); jf0.add(lblNewLabel_1); jf0.setVisible(True) jf0.setBounds(400, 300, 700, 300) jf0.EXIT_ON_CLOSE txtEnterIssue.addKeyListener(self) def keyPressed(self, e): self.search_string.__add__(self.search_string) self.jtf1.setText(self.search_string) sys.stdout.write(self.search_string)
class Panel_Extension(JPanel): def get_combo_items(self, combo): itemcount = combo.getItemCount() items = [] for i in range(itemcount): items.append(combo.getItemAt(i)) return items def load_profiles(self): loaded_profiles = cb.callbacks.loadExtensionSetting("Profiles") if loaded_profiles is not None: self.profiles = loaded_profiles.splitlines() items = self.get_combo_items(self._profiles_combo) for profile in self.profiles: if profile not in items: self._profiles_combo.addItem(profile) if len(self.profiles) > 0: self.load_fields( "bao7uo WAF bypass" if "bao7uo WAF bypass" in self.profiles else self.profiles[0] ) else: self.save_fields("bao7uo WAF bypass") def save_profiles(self): cb.callbacks.saveExtensionSetting( "Profiles", "\n".join(self.profiles) if len(self.profiles) > 0 else None ) def load_fields(self, profile): self.parent.panel_update_cookies._update_values() values = self.parent.panel_update_cookies.values for key in values.keys(): if key is None: break loaded = cb.callbacks.loadExtensionSetting(profile + "_" + key) if loaded is None: break self.parent.panel_update_cookies.values[key] = loaded self.parent.panel_extension._profile_textfield.setText(profile) self.parent.panel_update_cookies._load_values() Update_cookies = cb.callbacks.loadExtensionSetting( profile + "_" + "Update_cookies" ) if Update_cookies is not None: self.parent.panel_update_cookies._rowpanel2.removeAllElements() if len(Update_cookies) > 0: self.parent.panel_update_cookies._rowpanel2.addelements( Update_cookies, True ) Remove_cookies = cb.callbacks.loadExtensionSetting( profile + "_" + "Remove_cookies" ) if Remove_cookies is not None: self.parent.panel_remove_cookies._rowpanel1.removeAllElements() if len(Remove_cookies) > 0: self.parent.panel_remove_cookies._rowpanel1.addelements( Remove_cookies, True ) def save_fields(self, profile, delete=False): items = self.get_combo_items(self._profiles_combo) if delete: if len(items) == 0: return items_profile_index = items.index(profile) if profile in self.profiles: self.profiles.remove(profile) self.save_profiles() if profile in items: self._profiles_combo.removeItem(profile) else: if profile not in self.profiles: self.profiles.append(profile) self.save_profiles() if profile not in items: self._profiles_combo.addItem(profile) items = self.get_combo_items(self._profiles_combo) items_profile_index = items.index(profile) self.parent.panel_update_cookies._update_values() values = self.parent.panel_update_cookies.values if delete: values = dict.fromkeys(values.iterkeys(), None) for key in values.keys(): cb.callbacks.saveExtensionSetting( profile + "_" + key, values[key] ) if delete: Update_cookies = None Remove_cookies = None else: Update_cookies = \ self.parent.panel_update_cookies._rowpanel2.getAllElements( True ) Remove_cookies = \ self.parent.panel_remove_cookies._rowpanel1.getAllElements( True ) cb.callbacks.saveExtensionSetting( profile + "_" + "Update_cookies", Update_cookies ) cb.callbacks.saveExtensionSetting( profile + "_" + "Remove_cookies", Remove_cookies ) if self._profiles_combo.getItemCount() > 0: if delete: select_index = items_profile_index - 1 \ if items_profile_index > 0 else 0 else: select_index = items_profile_index self._profiles_combo.setSelectedIndex(select_index) def _button_delete_profile_pressed(self, msg): self.save_fields(self._profiles_combo.getSelectedItem(), True) def _button_save_fields_pressed(self, msg): self.save_fields(self._profile_textfield.getText()) def _button_demo_pressed(self, msg): if JOptionPane.showConfirmDialog( msg.getSource().getParent().getParent(), "This will clear all session handling rules in Burp's \n" + "\"Project options -> Sessions\"\n" + "tab, even rules not produced by this extension. They\n" + "will be replaced with a sample/demo rule containing an\n" + "invoke extension session handler action.\n\n" + "A request which can be used for the demo will be sent\n" + "to the Repeater tab.\n\n" + "The demo URL will be placed in the settings, and the\n" + "contents of the \"Cookies to obtain\" list will be\n"+ "replaced with a single demo cookie named\n" + "\"ClientSideCookie\"\n\n" + "Please check the PhantomJS settings, then click on\n" + "\'Add a new \"Get Cookies\" session handler\'.\n\n" + "Are you sure you want to remove any existing session\n" + "handling rules?", "Burp Suite / WAF Cookie Fetcher", JOptionPane.YES_NO_OPTION ) == JOptionPane.YES_OPTION: panel_update_cookies = self.getParent().panel_update_cookies for field in \ panel_update_cookies.fields: if "getText" in dir(field) and "getName" in dir(field): field_name = field.getName() if field_name == "url": field.setText(cb.demo_url) if field_name == "domain": field.setText(cb.demo_domain) panel_update_cookies._rowpanel2.removeAllElements() panel_update_cookies._rowpanel2.addelement(cb.demo_cookie) cb.callbacks.loadConfigFromJson(cb.demo_json) cb.send_url_to_repeater(cb.demo_url) def _button_quit_pressed(self, msg): cb.callbacks.unloadExtension() def __init__(self): self.profiles = [] self.setBorder( BorderFactory.createTitledBorder("Profiles") ) self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self._rowpanel1 = JPanel() self._rowpanel1.setLayout(BoxLayout(self._rowpanel1, BoxLayout.X_AXIS)) self._profiles_combo = \ JComboBox( self.profiles ) self._profiles_combo.addItem("0"*40) self._profiles_combo.setMaximumSize( self._profiles_combo.getPreferredSize() ) self._profiles_combo.removeItem("0" * 40) self._profiles_combo_panel = border_X_panel() self._demo_panel = button_panel( "Demo", self._button_demo_pressed ) self._quit_panel = button_panel( "Unload WAF Cookie Fetcher", self._button_quit_pressed ) self._profile_textfield = \ PTTextField( "profile", "Profile name: ", "bao7uo WAF bypass", None, JButton( "Save profile", actionPerformed=self._button_save_fields_pressed ) ) self._profiles_combo_panel.add(self._profiles_combo) self._button_delete_profile = \ JButton( "Delete profile", actionPerformed=self._button_delete_profile_pressed ) self._profiles_combo_panel.add(self._button_delete_profile) self._profiles_combo.addActionListener(actionlistener(self)) self._rowpanel1.add(self._profiles_combo_panel) self._rowpanel1.add(Box.createHorizontalGlue()) self._rowpanel1.add(self._profile_textfield) self._rowpanel1.add(Box.createHorizontalGlue()) self._rowpanel1.add(self._demo_panel) self._rowpanel1.add(self._quit_panel) self.add(self._rowpanel1)
class NewAtfView(JDialog): ''' Prompt user to choose some options to create a template for a new ATF file. ''' def __init__(self, controller, projects, languages, protocols): self.modalityType = Dialog.ModalityType.APPLICATION_MODAL self.controller = controller self.projects = projects self.languages = languages self.protocols = protocols self.cancelled = False self.springLayout = SpringLayout() self.pane = self.getContentPane() def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("New ATF template") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def build(self): ''' Puts all the window components together in the JFrame ''' layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS) self.setLayout(layout) # Create all necessary panels ampersand_panel = self.build_ampersand_row() project_panel = self.build_projects_row() language_panel = self.build_language_row() buttons_panel = self.build_buttons_row() # Add panels to main JFrame self.add(ampersand_panel) self.add(project_panel) self.add(language_panel) self.add(buttons_panel) def build_ampersand_row(self): ''' Builds the &-line row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. ampersand_label = JLabel("CDLI's ID: ") self.left_field = JTextField('&') equals_label = JLabel('=') self.right_field = JTextField() tooltip_text = ("<html><body>This is the ID and text's designation " "according to<br/>the CDLI catalog. If your text is " "not yet in the<br/>catalog, please email " "[email protected] to get<br/>an ID and designation.") help_label = self.build_help_label(tooltip_text) panel.add(ampersand_label) panel.add(self.left_field) panel.add(equals_label) panel.add(self.right_field) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, ampersand_label, 20, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_field, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, equals_label, 5, SpringLayout.EAST, self.left_field) layout.putConstraint(SpringLayout.NORTH, equals_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_field, 5, SpringLayout.EAST, equals_label) layout.putConstraint(SpringLayout.NORTH, self.right_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_field) layout.putConstraint(SpringLayout.NORTH, help_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_projects_row(self): ''' Builds the projects row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. project_label = JLabel('Project: ') self.right_combo = JComboBox() self.right_combo.setEditable(True) def create_project_list(): ''' Prepares list of projects and subprojects ordered with the default one first. ''' default_project = self.projects['default'][0].split('/')[0] if '/' in self.projects['default']: default_subproject = self.projects['default'].split('/')[1] else: default_subproject = '' projects = [default_project] subprojects = [default_subproject] # User created projects might not be in default dictionary for project in self.projects.keys(): if (project != default_project and project != 'default'): projects.append(project) # Default project might not have subproject if default_project in self.projects.keys(): if default_subproject: for subproject in self.projects[default_project]: if (subproject != default_subproject): subprojects.append(subproject) return projects, subprojects self.left_combo = JComboBox(create_project_list()[0]) # Make left combo keep size no matter how long project names are self.left_combo.setPreferredSize(Dimension(125, 30)) self.left_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.left_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.left_combo.setSize(self.left_combo.getPreferredSize()) self.right_combo = JComboBox(create_project_list()[1]) # Prevent right combo to change sizes dynamically self.right_combo.setPreferredSize(Dimension(100, 30)) self.right_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.right_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.right_combo.setSize(self.left_combo.getPreferredSize()) action_listener = ComboActionListener(self.right_combo, self.projects) self.left_combo.addActionListener(action_listener) self.left_combo.setEditable(True) self.right_combo.setEditable(True) slash_label = JLabel('/') tooltip_text = ("<html><body>Choose project from list or insert a new " "one.<br/>You can leave the right-hand field blank." "</body><html>") help_label = self.build_help_label(tooltip_text) panel.add(project_label) panel.add(self.left_combo) panel.add(slash_label) panel.add(self.right_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, project_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, project_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, slash_label, 5, SpringLayout.EAST, self.left_combo) layout.putConstraint(SpringLayout.NORTH, slash_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_combo, 5, SpringLayout.EAST, slash_label) layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_language_row(self): ''' Builds the language row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Get language list from settings.yaml, removing the default one from # the list languages = self.languages.keys() languages.remove('default') # Create necessary components and add them to panel. language_label = JLabel('Language: ') self.language_combo = JComboBox(languages) # Set selected language to default self.language_combo.setSelectedItem(self.languages['default']) tooltip_text = "Choose a language from the dropdown menu." help_label = self.build_help_label(tooltip_text) panel.add(language_label) panel.add(self.language_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, language_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, language_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.language_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.language_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_buttons_row(self): ''' Add OK/Cancel/Blank buttons. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. create_button = JButton('Create template', actionPerformed=self.create_template) leave_button = JButton('Leave blank', actionPerformed=self.blank) cancel_button = JButton('Cancel', actionPerformed=self.cancel) panel.add(create_button) panel.add(leave_button) panel.add(cancel_button) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, create_button, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, create_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, leave_button, 5, SpringLayout.EAST, create_button) layout.putConstraint(SpringLayout.NORTH, leave_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, cancel_button, 5, SpringLayout.EAST, leave_button) layout.putConstraint(SpringLayout.NORTH, cancel_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, cancel_button) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, cancel_button) # Add this to NewAtf JFrame return panel def build_help_label(self, tooltip_text): icon = ImageIcon(find_image_resource('smallhelp')) label = JLabel() label.setIcon(icon) label.setToolTipText(tooltip_text) return label def cancel(self, event): self.cancelled = True self.dispose() def blank(self, event): self.controller.show_template() self.dispose() def create_template(self, event): ''' Put together user selected elements of the template following ATF file format. ''' # &-line # E.g. &X001001 = JCS 48, 089 and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'), self.right_field.getText().encode('utf-8')) # Project line # E.g. #project: cams/gkab # E.g. #project: rimanum project_line = "#project: {}".format( self.left_combo.getSelectedItem().encode('utf-8')) if self.right_combo.getSelectedItem(): project_line = "{}/{}".format( project_line, self.right_combo.getSelectedItem().encode('utf-8')) # Language line # E.g. #atf: lang akk-x-stdbab language = self.language_combo.getSelectedItem() language_code = self.languages[language] # Protocol line/s # E.g. #atf: use unicode protocols = '' for protocol in self.protocols: protocols += '#atf: use {}\n'.format(protocol) # Put together all lines to create the template and show in ATF area self.controller.template = ('{}\n' '{}\n' '#atf: lang {}\n' '{}\n'.format(and_line, project_line, language_code, protocols)) self.controller.show_template() self.dispose()
main_panel = JPanel() ### panel 1 panel1 = JPanel() panel1.add(lbl1) cb1 = JComboBox(choice_list) btn1 = JButton("Accept") btn1.addActionListener(ButtonListener(btn1)) panel1.add(cb1) panel1.add(btn1) ### panel 2 panel2 = JPanel() panel2.add(lbl2) cb2 = JComboBox(sorted(roi_ni.keys())) cb2.addActionListener(Listener(lbl2, cb2)) panel2.add(cb2) ### panel 3 pnl3 = JPanel() lst1 = JList(listmodel) pnl3.add(lst1) frame = JFrame("Swing GUI Test Frame") frame.getContentPane().add(main_panel) main_panel.add(panel1) main_panel.add(panel2) main_panel.add(pnl3) frame.pack() frame.setVisible(True)
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("PT Vulnerabilities Manager") self.config = SafeConfigParser() self.createSection('projects') self.createSection('general') self.config.read('config.ini') self.chooser = JFileChooser() # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self.logTable = Table(self) self.logTable.getColumnModel().getColumn(0).setMaxWidth(35) self.logTable.getColumnModel().getColumn(1).setMinWidth(100) self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self.initVulnerabilityTab() self.initProjSettingsTab() self.initTabs() self.initCallbacks() if self.projPath.getText() != None: self.loadVulnerabilities(self.projPath.getText()) print "Thank you for installing PT Vulnerabilities Manager v1.0 extension" print "by Barak Tawily\n\n\n" print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition" return def initVulnerabilityTab(self): # ## init vulnerability tab # nameLabel = JLabel("Vulnerability Name:") nameLabel.setBounds(10, 10, 140, 30) self.addButton = JButton("Add",actionPerformed=self.addVuln) self.addButton.setBounds(10, 500, 100, 30) rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln) rmVulnButton.setBounds(465, 500, 100, 30) mitigationLabel = JLabel("Mitigation:") mitigationLabel.setBounds(10, 290, 150, 30) addSSBtn = JButton("Add SS",actionPerformed=self.addSS) addSSBtn.setBounds(750, 40, 110, 30) deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS) deleteSSBtn.setBounds(750, 75, 110, 30) piclistLabel = JLabel("Images list:") piclistLabel.setBounds(580, 10, 140, 30) self.screenshotsList = DefaultListModel() self.ssList = JList(self.screenshotsList) self.ssList.setBounds(580, 40, 150, 250) self.ssList.addListSelectionListener(ssChangedHandler(self)) self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY)) previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)") previewPicLabel.setBounds(580, 290, 500, 30) copyImgMenu = JMenuItem("Copy") copyImgMenu.addActionListener(copyImg(self)) self.imgMenu = JPopupMenu("Popup") self.imgMenu.add(copyImgMenu) self.firstPic = JLabel() self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY)) self.firstPic.setBounds(580, 320, 550, 400) self.firstPic.addMouseListener(imageClicked(self)) self.vulnName = JTextField("") self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self)) self.vulnName.setBounds(140, 10, 422, 30) sevirities = ["Unclassified", "Critical","High","Medium","Low"] self.threatLevel = JComboBox(sevirities); self.threatLevel.setBounds(140, 45, 140, 30) colors = ["Color:", "Green", "Red"] self.colorCombo = JComboBox(colors); self.colorCombo.setBounds(465, 45, 100, 30) self.colorCombo severityLabel = JLabel("Threat Level:") severityLabel.setBounds(10, 45, 100, 30) descriptionLabel = JLabel("Description:") descriptionLabel.setBounds(10, 80, 100, 30) self.descriptionString = JTextArea("", 5, 30) self.descriptionString.setWrapStyleWord(True); self.descriptionString.setLineWrap(True) self.descriptionString.setBounds(10, 110, 555, 175) descriptionStringScroll = JScrollPane(self.descriptionString) descriptionStringScroll.setBounds(10, 110, 555, 175) descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.mitigationStr = JTextArea("", 5, 30) self.mitigationStr.setWrapStyleWord(True); self.mitigationStr.setLineWrap(True) self.mitigationStr.setBounds(10, 320, 555, 175) mitigationStrScroll = JScrollPane(self.mitigationStr) mitigationStrScroll.setBounds(10, 320, 555, 175) mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000); self.pnl.setLayout(None); self.pnl.add(addSSBtn) self.pnl.add(piclistLabel) self.pnl.add(nameLabel) self.pnl.add(deleteSSBtn) self.pnl.add(rmVulnButton) self.pnl.add(severityLabel) self.pnl.add(mitigationLabel) self.pnl.add(descriptionLabel) self.pnl.add(previewPicLabel) self.pnl.add(mitigationStrScroll) self.pnl.add(descriptionStringScroll) self.pnl.add(self.ssList) self.pnl.add(self.firstPic) self.pnl.add(self.addButton) self.pnl.add(self.vulnName) self.pnl.add(self.threatLevel) self.pnl.add(self.colorCombo) def initProjSettingsTab(self): # init project settings projNameLabel = JLabel("Name:") projNameLabel.setBounds(10, 50, 140, 30) self.projName = JTextField("") self.projName.setBounds(140, 50, 320, 30) self.projName.getDocument().addDocumentListener(projTextChanged(self)) detailsLabel = JLabel("Details:") detailsLabel.setBounds(10, 120, 140, 30) reportLabel = JLabel("Generate Report:") reportLabel.setBounds(10, 375, 140, 30) types = ["DOCX","HTML","XLSX"] self.reportType = JComboBox(types) self.reportType.setBounds(10, 400, 140, 30) generateReportButton = JButton("Generate", actionPerformed=self.generateReport) generateReportButton.setBounds(160, 400, 90, 30) self.projDetails = JTextArea("", 5, 30) self.projDetails.setWrapStyleWord(True); self.projDetails.setLineWrap(True) projDetailsScroll = JScrollPane(self.projDetails) projDetailsScroll.setBounds(10, 150, 450, 175) projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) projPathLabel = JLabel("Path:") projPathLabel.setBounds(10, 90, 140, 30) self.projPath = JTextField("") self.projPath.setBounds(140, 90, 320, 30) chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath) chooseProjPathButton.setBounds(470, 90, 100, 30) importProjButton = JButton("Import",actionPerformed=self.importProj) importProjButton.setBounds(470, 10, 100, 30) exportProjButton = JButton("Export",actionPerformed=self.exportProj) exportProjButton.setBounds(575, 10, 100, 30) openProjButton = JButton("Open Directory",actionPerformed=self.openProj) openProjButton.setBounds(680, 10, 130, 30) currentProjectLabel = JLabel("Current:") currentProjectLabel.setBounds(10, 10, 140, 30) projects = self.config.options('projects') self.currentProject = JComboBox(projects) self.currentProject.addActionListener(projectChangeHandler(self)) self.currentProject.setBounds(140, 10, 140, 30) self.autoSave = JCheckBox("Auto Save Mode") self.autoSave.setEnabled(False) # implement this feature self.autoSave.setBounds(300, 10, 140, 30) self.autoSave.setToolTipText("Will save any changed value while focus is out") addProjButton = JButton("Add / Update",actionPerformed=self.addProj) addProjButton.setBounds(10, 330, 150, 30) removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj) removeProjButton.setBounds(315, 330, 146, 30) generalOptions = self.config.options('general') if 'default project' in generalOptions: defaultProj = self.config.get('general','default project') self.currentProject.getModel().setSelectedItem(defaultProj) self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem())) self.clearProjTab = True self.projectSettings = JPanel() self.projectSettings.setBounds(0, 0, 1000, 1000) self.projectSettings.setLayout(None) self.projectSettings.add(reportLabel) self.projectSettings.add(detailsLabel) self.projectSettings.add(projPathLabel) self.projectSettings.add(addProjButton) self.projectSettings.add(openProjButton) self.projectSettings.add(projNameLabel) self.projectSettings.add(projDetailsScroll) self.projectSettings.add(importProjButton) self.projectSettings.add(exportProjButton) self.projectSettings.add(removeProjButton) self.projectSettings.add(generateReportButton) self.projectSettings.add(chooseProjPathButton) self.projectSettings.add(currentProjectLabel) self.projectSettings.add(self.projPath) self.projectSettings.add(self.autoSave) self.projectSettings.add(self.projName) self.projectSettings.add(self.reportType) self.projectSettings.add(self.currentProject) def initTabs(self): # ## init autorize tabs # self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) colorsMenu = JMenu("Paint") redMenu = JMenuItem("Red") noneMenu = JMenuItem("None") greenMenu = JMenuItem("Green") redMenu.addActionListener(paintChange(self, "Red")) noneMenu.addActionListener(paintChange(self, None)) greenMenu.addActionListener(paintChange(self, "Green")) colorsMenu.add(redMenu) colorsMenu.add(noneMenu) colorsMenu.add(greenMenu) self.menu = JPopupMenu("Popup") self.menu.add(colorsMenu) self.tabs = JTabbedPane() self.tabs.addTab("Request", self._requestViewer.getComponent()) self.tabs.addTab("Response", self._responseViewer.getComponent()) self.tabs.addTab("Vulnerability", self.pnl) self.tabs.addTab("Project Settings", self.projectSettings) self.tabs.setSelectedIndex(2) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) def loadVulnerabilities(self, projPath): self.clearList(None) selected = False for root, dirs, files in os.walk(projPath): # make it go only for dirs for dirName in dirs: xmlPath = projPath+"/"+dirName+"/vulnerability.xml" # xmlPath = xmlPath.replace("/","//") document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() vulnName = nodeList.item(0).getTextContent() severity = nodeList.item(1).getTextContent() description = nodeList.item(2).getTextContent() mitigation = nodeList.item(3).getTextContent() color = nodeList.item(4).getTextContent() test = vulnerability(vulnName,severity,description,mitigation,color) self._lock.acquire() row = self._log.size() self._log.add(test) self.fireTableRowsInserted(row, row) self._lock.release() if vulnName == self.vulnName.getText(): self.logTable.setRowSelectionInterval(row,row) selected = True if selected == False and self._log.size() > 0: self.logTable.setRowSelectionInterval(0, 0) self.loadVulnerability(self._log.get(0)) def createSection(self, sectioName): self.config.read('config.ini') if not (sectioName in self.config.sections()): self.config.add_section(sectioName) cfgfile = open("config.ini",'w') self.config.write(cfgfile) cfgfile.close() def saveCfg(self): f = open('config.ini', 'w') self.config.write(f) f.close() def getXMLDoc(self, xmlPath): try: document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath) return document except: self._extender.popup("XML file not found") return def saveXMLDoc(self, doc, xmlPath): transformerFactory = TransformerFactory.newInstance() transformer = transformerFactory.newTransformer() source = DOMSource(doc) result = StreamResult(File(xmlPath)) transformer.transform(source, result) def generateReport(self,event): if self.reportType.getSelectedItem() == "HTML": path = self.reportToHTML() if self.reportType.getSelectedItem() == "XLSX": path = self.reportToXLS() if self.reportType.getSelectedItem() == "DOCX": path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml') n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION) if n == JOptionPane.YES_OPTION: os.system('"' + path + '"') # Bug! stucking burp until the file get closed def exportProj(self,event): self.chooser.setDialogTitle("Save project") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showSaveDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: dst = str(self.chooser.getSelectedFile()) shutil.make_archive(dst,"zip",self.getCurrentProjPath()) self.popup("Project export successfuly") def importProj(self,event): self.chooser.setDialogTitle("Select project zip to directory") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: zipPath = str(self.chooser.getSelectedFile()) self.chooser.setDialogTitle("Select project directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" with zipfile.ZipFile(zipPath, "r") as z: z.extractall(projPath) xmlPath = projPath + "/project.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() projName = nodeList.item(0).getTextContent() nodeList.item(1).setTextContent(projPath) self.saveXMLDoc(document, xmlPath) self.config.set('projects', projName, projPath) self.saveCfg() self.reloadProjects() self.currentProject.getModel().setSelectedItem(projName) self.clearVulnerabilityTab() def reportToXLS(self): if not xlsxwriterImported: self.popup("xlsxwriter library is not imported") return workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) worksheet.write(0, 0, "Vulnerability Name", bold) worksheet.write(0, 1, "Threat Level", bold) worksheet.write(0, 2, "Description", bold) worksheet.write(0, 3, "Mitigation", bold) row = 1 for i in range(0,self._log.size()): worksheet.write(row, 0, self._log.get(i).getName()) worksheet.write(row, 1, self._log.get(i).getSeverity()) worksheet.write(row, 2, self._log.get(i).getDescription()) worksheet.write(row, 3, self._log.get(i).getMitigation()) row = row + 1 # add requests and images as well workbook.close() return self.getCurrentProjPath() + '/PT Manager Report.xlsx' def reportToHTML(self): htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr"> <head> <title>PT Manager Report</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style> body { background-repeat: no-repeat; background-attachment: fixed; font-family: Arial,Tahoma,sens-serif; font-size: 13px; margin: auto; } #warpcenter { width: 900px; margin: 0px auto; } table { border: 2px dashed #000000; } td { border-top: 2px dashed #000000; padding: 10px; } img { border: 0px; } </style> <script language="javascript"> function divHideShow(divToHideOrShow) { var div = document.getElementById(divToHideOrShow); if (div.style.display == "block") { div.style.display = "none"; } else { div.style.display = "block"; } } </script> </head> <body> <div id="warpcenter"> <h1> PT Manager Report </h1> <h2> Project: %s</h1> """ % (self.projName.getText()) for i in range(0,self._log.size()): name = self._log.get(i).getName() request = "None" response = "None" path = self.getVulnReqResPath("request",name) if os.path.exists(path): request = self.newlineToBR(self.getFileContent(path)) path = self.getVulnReqResPath("response",name) if os.path.exists(path): response = self.newlineToBR(self.getFileContent(path)) images = "" for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)): if fileName.endswith(".jpg"): images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName) description = self.newlineToBR(self._log.get(i).getDescription()) mitigation = self.newlineToBR(self._log.get(i).getMitigation()) htmlContent += self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images) htmlContent += "</div></body></html>" f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w') f.writelines(htmlContent) f.close() return self.getCurrentProjPath() + '/PT Manager Report.html' def newlineToBR(self,string): return "<br />".join(string.split("\n")) def getFileContent(self,path): f = open(path, "rb") content = f.read() f.close() return content def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"): return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div> <div id="Table_%s" style="display: none;"> <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;"> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Threat Level: </span> <span style="color:#8b8989">%s</span> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Description</span> <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;"> %s </div> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Mitigration</span> <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Request</span> <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Response</span> <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Images</span> <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> </table> </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images) def clearVulnerabilityTab(self, rmVuln=True): if rmVuln: self.vulnName.setText("") self.descriptionString.setText("") self.mitigationStr.setText("") self.colorCombo.setSelectedIndex(0) self.threatLevel.setSelectedIndex(0) self.screenshotsList.clear() self.addButton.setText("Add") self.firstPic.setIcon(None) def saveRequestResponse(self, type, requestResponse, vulnName): path = self.getVulnReqResPath(type,vulnName) f = open(path, 'wb') f.write(requestResponse) f.close() def openProj(self, event): os.system('explorer ' + self.projPath.getText()) def getVulnReqResPath(self, requestOrResponse, vulnName): return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName) def htmlEscape(self,data): return data.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') def generateReportFromDocxTemplate(self, zipname, newZipName, filename): newZipName = self.getCurrentProjPath() + "/" + newZipName with zipfile.ZipFile(zipname, 'r') as zin: with zipfile.ZipFile(newZipName, 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): if item.filename != filename: zout.writestr(item, zin.read(item.filename)) else: xml_content = zin.read(item.filename) result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0] newXML = result[0] templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0] newBody = "" for i in range(0,self._log.size()): tmp = templateBody tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName())) tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity())) tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription())) tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation())) newBody = newBody + tmp newXML = newXML + newBody newXML = newXML + result[1] with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, newXML) return newZipName def chooseProjPath(self, event): self.chooser.setDialogTitle("Select target directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" os.makedirs(projPath) self.projPath.setText(projPath) def reloadProjects(self): self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects'))) def rmProj(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.projPath.getText()) self.config.remove_option('projects',self.currentProject.getSelectedItem()) self.reloadProjects() self.currentProject.setSelectedIndex(0) self.loadVulnerabilities(self.projPath.getText()) def popup(self,msg): JOptionPane.showMessageDialog(None,msg) def addProj(self, event): projPath = self.projPath.getText() if projPath == None or projPath == "": self.popup("Please select path") return self.config.set('projects', self.projName.getText(), projPath) self.saveCfg() xml = ET.Element('project') name = ET.SubElement(xml, "name") path = ET.SubElement(xml, "path") details = ET.SubElement(xml, "details") autoSaveMode = ET.SubElement(xml, "autoSaveMode") name.text = self.projName.getText() path.text = projPath details.text = self.projDetails.getText() autoSaveMode.text = str(self.autoSave.isSelected()) tree = ET.ElementTree(xml) try: tree.write(self.getCurrentProjPath()+'/project.xml') except: self.popup("Invalid path") return self.reloadProjects() self.clearVulnerabilityTab() self.clearList(None) self.currentProject.getModel().setSelectedItem(self.projName.getText()) def resize(self, image, width, height): bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT) g2d = bi.createGraphics() g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)) g2d.drawImage(image, 0, 0, width, height, None) g2d.dispose() return bi; def clearStr(self, var): return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "") def popUpAreYouSure(self): dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION) if dialogResult == 0: return 0 return 1 def removeSS(self,event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue()) self.ssList.getModel().remove(self.ssList.getSelectedIndex()) self.firstPic.setIcon(ImageIcon(None)) # check if there is images and select the first one # bug in linux def addSS(self,event): clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() try: image = clipboard.getData(DataFlavor.imageFlavor) except: self.popup("Clipboard not contains image") return vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg" fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name file = File(fileName) bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB); g = bufferedImage.createGraphics(); g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None); ImageIO.write(bufferedImage, "jpg", file) self.addVuln(self) self.ssList.setSelectedValue(name,True) def rmVuln(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.getCurrentVulnPath()) self.clearVulnerabilityTab() self.loadVulnerabilities(self.getCurrentProjPath()) def addVuln(self, event): if self.colorCombo.getSelectedItem() == "Color:": colorTxt = None else: colorTxt = self.colorCombo.getSelectedItem() self._lock.acquire() row = self._log.size() vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt) self._log.add(vulnObject) self.fireTableRowsInserted(row, row) self._lock.release() vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) xml = ET.Element('vulnerability') name = ET.SubElement(xml, "name") severity = ET.SubElement(xml, "severity") description = ET.SubElement(xml, "description") mitigation = ET.SubElement(xml, "mitigation") color = ET.SubElement(xml, "color") name.text = self.vulnName.getText() severity.text = self.threatLevel.getSelectedItem() description.text = self.descriptionString.getText() mitigation.text = self.mitigationStr.getText() color.text = colorTxt tree = ET.ElementTree(xml) tree.write(vulnPath+'/vulnerability.xml') self.loadVulnerabilities(self.getCurrentProjPath()) self.loadVulnerability(vulnObject) def vulnNameChanged(self): if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "": self.addButton.setText("Update") elif self.addButton.getText() != "Add": options = ["Create a new vulnerability", "Change current vulnerability name"] n = JOptionPane.showOptionDialog(None, "Would you like to?", "Vulnerability Name", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, None, options, options[0]); if n == 0: self.clearVulnerabilityTab(False) self.addButton.setText("Add") else: newName = JOptionPane.showInputDialog( None, "Enter new name:", "Vulnerability Name", JOptionPane.PLAIN_MESSAGE, None, None, self.vulnName.getText()) row = self.logTable.getSelectedRow() old = self.logTable.getValueAt(row,1) self.changeVulnName(newName,old) def changeVulnName(self,new,old): newpath = self.getCurrentProjPath() + "/" + new oldpath = self.getCurrentProjPath() + "/" + old os.rename(oldpath,newpath) self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml") def getCurrentVulnPath(self): return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) def getCurrentProjPath(self): return self.projPath.getText() def loadSS(self, imgPath): image = ImageIO.read(File(imgPath)) if image.getWidth() <= 550 and image.getHeight() <= 400: self.firstPic.setIcon(ImageIcon(image)) self.firstPic.setSize(image.getWidth(),image.getHeight()) else: self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400))) self.firstPic.setSize(550,400) def clearProjectTab(self): self.projPath.setText("") self.projDetails.setText("") def clearList(self, event): self._lock.acquire() self._log = ArrayList() row = self._log.size() self.fireTableRowsInserted(row, row) self._lock.release() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages(); if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send to PT Manager"); requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request")) ret.add(requestMenuItem); return(ret); return null; # # implement ITab # def getTabCaption(self): return "PT Manager" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 3 def getColumnName(self, columnIndex): if columnIndex == 0: return "#" if columnIndex == 1: return "Vulnerability Name" if columnIndex == 2: return "Threat Level" return "" def getValueAt(self, rowIndex, columnIndex): vulnObject = self._log.get(rowIndex) if columnIndex == 0: return rowIndex+1 if columnIndex == 1: return vulnObject.getName() if columnIndex == 2: return vulnObject.getSeverity() if columnIndex == 3: return vulnObject.getMitigation() if columnIndex == 4: return vulnObject.getColor() return "" def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"): if xmlPath == "def": xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() nodeList.item(fieldNumber).setTextContent(value) self.saveXMLDoc(document, xmlPath) self.loadVulnerabilities(self.getCurrentProjPath()) def loadVulnerability(self, vulnObject): self.addButton.setText("Update") self.vulnName.setText(vulnObject.getName()) self.threatLevel.setSelectedItem(vulnObject.getSeverity()) self.descriptionString.setText(vulnObject.getDescription()) self.mitigationStr.setText(vulnObject.getMitigation()) if vulnObject.getColor() == "" or vulnObject.getColor() == None: self.colorCombo.setSelectedItem("Color:") else: self.colorCombo.setSelectedItem(vulnObject.getColor()) self.screenshotsList.clear() for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())): if fileName.endswith(".jpg"): self.screenshotsList.addElement(fileName) imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName # imgPath = imgPath.replace("/","//") self.loadSS(imgPath) if (self.screenshotsList.getSize() == 0): self.firstPic.setIcon(None) else: self.ssList.setSelectedIndex(0) path = self.getVulnReqResPath("request",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._requestViewer.setMessage(f, False) else: self._requestViewer.setMessage("None", False) path = self.getVulnReqResPath("response",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._responseViewer.setMessage(f, False) else: self._responseViewer.setMessage("None", False)
class BurpExtender(IBurpExtender, IExtensionStateListener, ITab): ext_name = "CompuRacerExtension" ext_version = '1.2' loaded = True t = None def registerExtenderCallbacks(self, callbacks): Cb(callbacks) Cb.callbacks.setExtensionName(self.ext_name) try: global compuracer_communication_lock # option picker item objects (for Java compatibility) item1 = {'key': 'item1', 'name': '2'} item2 = {'key': 'item2', 'name': '3'} item3 = {'key': 'item3', 'name': '4'} item4 = {'key': 'item4', 'name': '5'} item5 = {'key': 'item5', 'name': '10'} item6 = {'key': 'item6', 'name': '15'} item7 = {'key': 'item7', 'name': '20'} item8 = {'key': 'item8', 'name': '25'} item9 = {'key': 'item9', 'name': '50'} item10 = {'key': 'item10', 'name': '100'} # main splitted pane + top pane self._main_splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._outer_settings_pane = JPanel(BorderLayout()) self._settings_pane = JPanel(GridBagLayout()) c = GridBagConstraints() self.label_1 = JLabel("Number of parallel requests:") c.fill = GridBagConstraints.NONE c.gridx = 0 c.gridy = 0 c.insets = Insets(0, 5, 0, 10) c.anchor = GridBagConstraints.LINE_START self._settings_pane.add(self.label_1, c) self.input_parallel_requests = JComboBox([ Item(item1), Item(item2), Item(item3), Item(item4), Item(item5), Item(item6), Item(item7), Item(item8), Item(item9), Item(item10) ]) self.input_parallel_requests.setSelectedIndex(4) self.input_parallel_requests.setToolTipText( "Select the number of parallel requests that will be sent") self.input_parallel_requests.addActionListener( self.change_parallel_requests) c.gridx = 1 c.gridy = 0 c.insets = Insets(0, 5, 0, 10) self._settings_pane.add(self.input_parallel_requests, c) self.option_allow_redirects = JCheckBox( "Allow redirects", actionPerformed=self.check_allow_redirects) self.option_allow_redirects.setToolTipText( "Select whether redirect responses are followed") c.gridx = 2 c.gridy = 0 c.insets = Insets(0, 20, 0, 10) self._settings_pane.add(self.option_allow_redirects, c) self.option_sync_last_byte = JCheckBox( "Sync last byte", actionPerformed=self.check_sync_last_byte) self.option_sync_last_byte.setToolTipText( "Select whether last byte synchronisation is enabled") c.gridx = 2 c.gridy = 1 c.insets = Insets(0, 20, 0, 0) self._settings_pane.add(self.option_sync_last_byte, c) self.label_2 = JLabel("Send timeout in seconds:") c.gridx = 0 c.gridy = 1 c.insets = Insets(0, 5, 0, 0) self._settings_pane.add(self.label_2, c) self.input_send_timeout = JComboBox([ Item(item2), Item(item4), Item(item5), Item(item7), Item(item9), Item(item10) ]) self.input_send_timeout.setSelectedIndex(3) self.input_send_timeout.setToolTipText( "Select the wait-for-response timeout after sending the request(s)" ) self.input_send_timeout.addActionListener(self.change_send_timeout) c.gridx = 1 c.gridy = 1 c.insets = Insets(0, 5, 0, 0) self._settings_pane.add(self.input_send_timeout, c) self.button_resend_batch = JButton("Resend requests") self.button_resend_batch.setToolTipText( "Resend all requests with the current configuration") self.button_resend_batch.setEnabled(False) self.button_resend_batch.addActionListener( MenuFactory.start_request_transmitter_button) c.gridx = 3 c.gridy = 0 c.insets = Insets(0, 20, 0, 10) self._settings_pane.add(self.button_resend_batch, c) immediate_data_ui_elements[ "parallel_requests"] = self.input_parallel_requests immediate_data_ui_elements[ "allow_redirects"] = self.option_allow_redirects immediate_data_ui_elements[ "sync_last_byte"] = self.option_sync_last_byte immediate_data_ui_elements[ "send_timeout"] = self.input_send_timeout immediate_data_ui_elements[ "resend_batch"] = self.button_resend_batch c = GridBagConstraints() c.anchor = GridBagConstraints.WEST self._outer_settings_pane.add(self._settings_pane, BorderLayout.WEST) self._main_splitpane.setTopComponent(self._outer_settings_pane) self._results_splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._main_splitpane.setBottomComponent(self._results_splitpane) # table of log entries self.tabs_right = JTabbedPane() global _textEditors, DEFAULT_RESULTS for i in range(3): _textEditors.append(Cb.callbacks.createTextEditor()) _textEditors[-1].setText(str.encode("\n" + DEFAULT_RESULTS)) self.tabs_right.add("Summary", _textEditors[0].getComponent()) self.tabs_right.add("Full result", _textEditors[1].getComponent()) self.tabs_right.add("Config", _textEditors[2].getComponent()) self._results_splitpane.setRightComponent(self.tabs_right) # tabs with request/response viewers global _requestViewers, _requestPane _requestPane = JTabbedPane() _requestViewers.append( Cb.callbacks.createMessageEditor(None, False)) _requestPane.addTab("Request", _requestViewers[-1].getComponent()) self._results_splitpane.setLeftComponent(_requestPane) # customize our UI components Cb.callbacks.customizeUiComponent(self._settings_pane) Cb.callbacks.customizeUiComponent(self.tabs_right) Cb.callbacks.customizeUiComponent(_requestPane) # add the custom tab to Burp's UI Cb.callbacks.addSuiteTab(self) except RuntimeException as e: callbacks.printError(traceback.format_exc()) e = PyException(e) print("10") print(str(self)) print("{}\t{}\n{}\n".format(e.type, e.value, e.traceback)) Cb.callbacks.registerContextMenuFactory(MenuFactory()) callbacks.registerExtensionStateListener(self) self.start_alive_checker() Cb.callbacks.printOutput('%s v%s extension loaded\n' % (self.ext_name, self.ext_version)) def change_parallel_requests(self, event): global immediate_data try: num_parallel = MenuFactory.item_selected(event) if num_parallel != immediate_data['settings'][0]: self.update_setting(0, num_parallel, "number of parallel requests") except Exception as e: print(e) def change_send_timeout(self, event): global immediate_data try: send_timeout = MenuFactory.item_selected(event) if send_timeout != immediate_data['settings'][4]: self.update_setting(4, send_timeout, "send timeout") except Exception as e: print(e) def check_allow_redirects(self, event): global immediate_data is_selected = MenuFactory.button_selected(event) if is_selected != immediate_data['settings'][2]: self.update_setting(2, is_selected, "allow redirects") def check_sync_last_byte(self, event): global immediate_data is_selected = MenuFactory.button_selected(event) if is_selected != immediate_data['settings'][3]: self.update_setting(3, is_selected, "allow redirects") def resend_batches(self, event): global _storedRequests if _storedRequests is not None: self.sen # helper method for two methods above def update_setting(self, index, new_value, text): global immediate_data success = True print("> Updating {}..".format(text)) old_value = immediate_data['settings'][index] immediate_data['settings'][index] = new_value if MenuFactory.set_immediate_mode_settings( {'settings': immediate_data['settings']}): print("> Success!") else: print("> Failed!") immediate_data['settings'][index] = old_value success = False return success # for ITab def getTabCaption(self): return "CompuRacer" # for ITab def getUiComponent(self): return self._main_splitpane # def getHttpService(self): # global _storedRequest # return _storedRequest.getHttpService() # # def getRequest(self): # global _storedRequest # return _storedRequest.getRequest() # # def getResponse(self): # global _storedRequest # return _storedRequest.getResponse() def start_alive_checker(self): self.t = threading.Thread(name='Alive checker', target=self.alive_checker) self.t.start() def closest_match(self, number, list_of_numbers): return min(list(zip(list_of_numbers, range(len(list_of_numbers)))), key=lambda item: (abs(item[0] - number), item[1])) def alive_checker(self): global compuRacer_ip, compuRacer_port, alive_check_path, racer_alive, immediate_mode, compuracer_communication_lock unloaded = False old_alive = racer_alive parallel_req_options = [2, 3, 4, 5, 10, 15, 20, 25, 50, 100] send_time_options = [3, 5, 10, 20, 50, 100] while not unloaded: try: with compuracer_communication_lock: response = requests.get("http://{}:{}/{}".format( compuRacer_ip, compuRacer_port, alive_check_path), timeout=2) racer_alive = response and response.status_code and response.status_code == 200 success, mode, settings = MenuFactory.get_immediate_mode_settings( ) if success: immediate_data['mode'] = mode immediate_data['settings'] = settings # update UI button states immediate_data_ui_elements[ "parallel_requests"].setSelectedIndex( self.closest_match( immediate_data['settings'][0], parallel_req_options)[1]) immediate_data_ui_elements[ "allow_redirects"].setSelected( bool(immediate_data['settings'][2])) immediate_data_ui_elements[ "sync_last_byte"].setSelected( bool(immediate_data['settings'][3])) immediate_data_ui_elements[ "send_timeout"].setSelectedIndex( self.closest_match( immediate_data['settings'][4], send_time_options)[1]) except Exception as e: # it surely did not work racer_alive = False print(e) if racer_alive and not old_alive: print("> Racer is now alive!") MenuFactory.set_state_of_all_buttons(True) old_alive = True elif not racer_alive and old_alive: print("> Racer became dead!") MenuFactory.set_state_of_all_buttons(False) old_alive = False time.sleep(5) if not self.loaded: unloaded = True def extensionUnloaded(self): print("\n> Unloading..") self.loaded = False self.t.join() print("> Done.")
def __init__(self, logtable_factory=None, external_filter_action_listener=None, external_start_button_action_listener=None, external_stop_button_action_listener=None, external_clear_button_action_listener=None, tools_keys=None): self.this = JPanel() if tools_keys is None: tools_keys = [] self.external_start_button_action_listener = external_start_button_action_listener self.external_stop_button_action_listener = external_stop_button_action_listener self.external_clear_button_action_listener = external_clear_button_action_listener self.this.setLayout(BoxLayout(self.this, BoxLayout.Y_AXIS)) # main split pane splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT) # table of log entries logTableModel = LogTableModel() self.logTableModel = logTableModel if logtable_factory is not None: logTable = logtable_factory(logTableModel) else: # XXX: create a generic logtable that works even without burp to made it work standalone raise ValueError("logtable_factory cannot be none") scrollPane = JScrollPane(logTable) splitPane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() tabs.setBorder(BorderFactory.createLineBorder(Color.black)) tabs.addTab("Request", logTable.getRequestViewer().getComponent()) tabs.addTab("Response", logTable.getResponseViewer().getComponent()) splitPane.setRightComponent(tabs) # top control panel controlPanel = JPanel(FlowLayout(FlowLayout.LEFT)) toolLabel = JLabel("Select tool: ") controlPanel.add(toolLabel) tools = JavaArrayList(tools_keys) toolList = JComboBox(tools) toolList.addActionListener(external_filter_action_listener) controlPanel.add(toolList) startButton = JButton("Start") self.startButton = startButton controlPanel.add(startButton) stopButton = JButton("Stop") self.stopButton = stopButton controlPanel.add(stopButton) clearButton = JButton("Clear") self.clearButton = clearButton startButton.setEnabled(False) controlPanel.add(clearButton) scopeLabel = JLabel("In-scope items only?") controlPanel.add(scopeLabel) scopeCheckBox = JCheckBox() self.scopeCheckBox = scopeCheckBox controlPanel.add(scopeCheckBox) filterLabel = JLabel("Filter Query:") controlPanel.add(filterLabel) queryFilterText = JTextField(40) self.queryFilterText = queryFilterText controlPanel.add(queryFilterText) startButton.addActionListener(self.start_button_action_listener) stopButton.addActionListener(self.stop_button_action_listener) clearButton.addActionListener(self.clear_button_action_listener) controlPanel.setAlignmentX(0) self.this.add(controlPanel) self.this.add(splitPane)
class GameSelector(ActionListener): """ generated source for class GameSelector """ theGameList = JComboBox() theRepositoryList = JComboBox() theSelectedRepository = GameRepository() theCachedRepositories = Map() class NamedItem(object): """ generated source for class NamedItem """ theKey = str() theName = str() def __init__(self, theKey, theName): """ generated source for method __init__ """ self.theKey = theKey self.theName = theName def __str__(self): """ generated source for method toString """ return self.theName def __init__(self): """ generated source for method __init__ """ super(GameSelector, self).__init__() self.theGameList = JComboBox() self.theGameList.addActionListener(self) self.theRepositoryList = JComboBox() self.theRepositoryList.addActionListener(self) self.theCachedRepositories = HashMap() self.theRepositoryList.addItem("games.ggp.org/base") self.theRepositoryList.addItem("games.ggp.org/dresden") self.theRepositoryList.addItem("games.ggp.org/stanford") self.theRepositoryList.addItem("Local Game Repository") def actionPerformed(self, e): """ generated source for method actionPerformed """ if e.getSource() == self.theRepositoryList: if self.theCachedRepositories.containsKey(theRepositoryName): self.theSelectedRepository = self.theCachedRepositories.get(theRepositoryName) else: if theRepositoryName == "Local Game Repository": self.theSelectedRepository = LocalGameRepository() else: self.theSelectedRepository = CloudGameRepository(theRepositoryName) self.theCachedRepositories.put(theRepositoryName, self.theSelectedRepository) repopulateGameList() def getSelectedGameRepository(self): """ generated source for method getSelectedGameRepository """ return self.theSelectedRepository def repopulateGameList(self): """ generated source for method repopulateGameList """ theRepository = self.getSelectedGameRepository() theKeyList = ArrayList(theRepository.getGameKeys()) Collections.sort(theKeyList) self.theGameList.removeAllItems() for theKey in theKeyList: if theGame == None: continue if theName == None: theName = theKey if 24 > len(theName): theName = theName.substring(0, 24) + "..." self.theGameList.addItem(self.NamedItem(theKey, theName)) def getRepositoryList(self): """ generated source for method getRepositoryList """ return self.theRepositoryList def getGameList(self): """ generated source for method getGameList """ return self.theGameList def getSelectedGame(self): """ generated source for method getSelectedGame """ try: return self.getSelectedGameRepository().getGame((self.theGameList.getSelectedItem()).theKey) except Exception as e: return None
class ConfigurationController(IMessageEditorController): def __init__(self, parent): self._parent = parent def getMainComponent(self): self._mainPanel = JPanel() #self._mainPanel.setLayout(BoxLayout(self._mainPanel, BoxLayout.Y_AXIS)) self._mainPanel.setLayout(BorderLayout()) self._titlePanel = JPanel(GridLayout(0, 1)) self._titlePanel.setBorder(EmptyBorder(10, 20, 10, 10)) self._titleText = JLabel("Mode configuration") self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE) self._titleText.setFont(self._titleText.getFont().deriveFont(16.0)) self._titleSubtitleText = JTextArea("Select a mode that works best for the type of exploit you are dealing with.") self._titleSubtitleText.setEditable(False) self._titleSubtitleText.setLineWrap(True) self._titleSubtitleText.setWrapStyleWord(True) self._titleSubtitleText.setHighlighter(None) self._titleSubtitleText.setBorder(None) #Local File Inclusion (LFI): Explore files #Command injection (visual): Shell #Command injection (blind): Shell modes = ['Select mode...', 'Local File Inclusion (LFI) - Discover files', 'OS Command injection (visual) - Shell'] self._cboModes = JComboBox(modes) self._cboModes.addActionListener(self.cboModesChanged()) self._titlePanel.add(self._titleText) self._titlePanel.add(self._titleSubtitleText) self._titlePanel.add(self._cboModes) self._mainPanel.add(self._titlePanel, BorderLayout.NORTH) self._switchPanel = JPanel() self._switchPanel.setLayout(BoxLayout(self._switchPanel, BoxLayout.Y_AXIS)) self._switchPanel.setBorder(EmptyBorder(5, 30, 10, 10)) self._outputCompleteResponseSwitch = JCheckBox("Use full response (not only the response body)") self._outputCompleteResponseSwitch.setSelected(True) self._outputCompleteResponseSwitch.addItemListener(self.OutputCompleteResponseSwitchListener()) self._switchPanel.add(self._outputCompleteResponseSwitch) self._urlEncodeSwitch = JCheckBox("Use url encode") self._urlEncodeSwitch.setSelected(True) self._urlEncodeSwitch.addItemListener(self.UrlEncodeSwitchListener()) self._switchPanel.add(self._urlEncodeSwitch) self._outputIsolatorSwitch = JCheckBox("Use output isolator") self._outputIsolatorSwitch.setSelected(False) self._outputIsolatorSwitch.addItemListener(self.OutputIsolatorSwitchListener()) self._switchPanel.add(self._outputIsolatorSwitch) self._removeSpacesSwitch = JCheckBox("Remove leading and trailing spaces") self._removeSpacesSwitch.setSelected(False) self._removeSpacesSwitch.addItemListener(self.SpacesSwitch()) self._switchPanel.add(self._removeSpacesSwitch) self._removeHtmlTagsSwitch = JCheckBox("Remove html-tags (regex '<.*?>')") self._removeHtmlTagsSwitch.setSelected(False) self._removeHtmlTagsSwitch.addItemListener(self.HtmlTagsSwitch()) self._switchPanel.add(self._removeHtmlTagsSwitch) self._tabCompletionSwitch = JCheckBox("Use tab-completion") self._tabCompletionSwitch.setSelected(False) self._tabCompletionSwitch.addItemListener(self.TabCompletionSwitchListener()) self._switchPanel.add(self._tabCompletionSwitch) self._virtualPersistenceSwitch = JCheckBox("Use virtual persistence") self._virtualPersistenceSwitch.setSelected(False) self._virtualPersistenceSwitch.addItemListener(self.VirtualPersistenceSwitchListener()) self._switchPanel.add(self._virtualPersistenceSwitch) self._wafSwitch = JCheckBox("WAF: Prepend each non-whitespace character (regex '\\w') with '\\'") self._wafSwitch.setSelected(False) self._wafSwitch.addItemListener(self.WafSwitch()) self._switchPanel.add(self._wafSwitch) self._mainPanel.add(self._switchPanel, BorderLayout.CENTER) return self._mainPanel class cboModesChanged(ActionListener): def actionPerformed(self, e): cboModes = e.getSource() mode = cboModes.getSelectedItem() if mode == 'Local File Inclusion (LFI) - Discover files': #Disable output isolator Utils.shellController._outputIsolator = None Utils.outputIsolator = None Utils._outputIsolator = None Utils.configurationController._outputIsolatorSwitch.setSelected(False) Utils.configurationController._outputIsolatorSwitch.setEnabled(False) #Disable remove leading and trailing spaces Utils.shellController._removeSpaces = False Utils.configurationController._removeSpacesSwitch.setSelected(False) Utils.configurationController._removeSpacesSwitch.setEnabled(False) #Disable remove html tags Utils.shellController._removeHtmlTags = False Utils.configurationController._removeHtmlTagsSwitch.setSelected(False) Utils.configurationController._removeHtmlTagsSwitch.setEnabled(False) #Disable tab-completion Utils.shellController._tabCompletion = False Utils.configurationController._tabCompletionSwitch.setSelected(False) Utils.configurationController._tabCompletionSwitch.setEnabled(False) #Disable virtual peristence Utils.shellController._virtualPersistence = False Utils.configurationController._virtualPersistenceSwitch.setSelected(False) Utils.configurationController._virtualPersistenceSwitch.setEnabled(False) #Disable WAF Utils.shellController._waf = False Utils.configurationController._wafSwitch.setSelected(False) Utils.configurationController._wafSwitch.setEnabled(False) if mode == 'OS Command injection (visual) - Shell' or mode == 'Select mode...': Utils.configurationController._outputIsolatorSwitch.setEnabled(True) Utils.configurationController._removeSpacesSwitch.setEnabled(True) Utils.configurationController._removeHtmlTagsSwitch.setEnabled(True) Utils.configurationController._tabCompletionSwitch.setEnabled(True) Utils.configurationController._virtualPersistenceSwitch.setEnabled(True) Utils.configurationController._wafSwitch.setEnabled(True) class OutputIsolatorSwitchListener(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.out("selected") isolator = ["3535start3535", "3535end3535"] Utils.shellController._outputIsolator = isolator Utils.outputIsolator = isolator Utils._outputIsolator = isolator elif e.getStateChange() == ItemEvent.DESELECTED: #TODO If deselected, Virtual persistence should be disabled: unless the body only returns # the command and nothing else, it's near impossible to warrant virtual persistence. # One possibility I have, is to also allow to define positions in the response tab and filter # out the command response like that (without using the outputisolators) Utils.out("deselected") Utils.shellController._outputIsolator = None Utils.outputIsolator = None Utils._outputIsolator = None class SpacesSwitch(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._removeSpaces = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._removeSpaces = False class HtmlTagsSwitch(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._removeHtmlTags = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._removeHtmlTags = False class TabCompletionSwitchListener(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._tabCompletion = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._tabCompletion = False class VirtualPersistenceSwitchListener(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._virtualPersistence = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.consoleController.setPwd(None) Utils.shellController._virtualPersistence = False class UrlEncodeSwitchListener(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._urlEncode = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._urlEncode = False class OutputCompleteResponseSwitchListener(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._outputCompleteResponse = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._outputCompleteResponse = False class WafSwitch(ItemListener): def itemStateChanged(self, e): if e.getStateChange() == ItemEvent.SELECTED: Utils.shellController._waf = True elif e.getStateChange() == ItemEvent.DESELECTED: Utils.shellController._waf = False
class NewAtfView(JDialog): ''' Prompt user to choose some options to create a template for a new ATF file. ''' def __init__(self, controller, projects, languages, protocols): self.modalityType = Dialog.ModalityType.APPLICATION_MODAL self.controller = controller self.projects = projects self.languages = languages self.protocols = protocols self.cancelled = False self.springLayout = SpringLayout() self.pane = self.getContentPane() def display(self): ''' Displays window. ''' self.build() self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.setResizable(False) self.setTitle("New ATF template") self.pack() self.setLocationRelativeTo(None) self.visible = 1 def build(self): ''' Puts all the window components together in the JFrame ''' layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS) self.setLayout(layout) # Create all necessary panels ampersand_panel = self.build_ampersand_row() project_panel = self.build_projects_row() language_panel = self.build_language_row() buttons_panel = self.build_buttons_row() # Add panels to main JFrame self.add(ampersand_panel) self.add(project_panel) self.add(language_panel) self.add(buttons_panel) def build_ampersand_row(self): ''' Builds the &-line row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. ampersand_label = JLabel("CDLI's ID: ") self.left_field = JTextField('&') equals_label = JLabel('=') self.right_field = JTextField() tooltip_text = ("<html><body>This is the ID and text's designation " "according to<br/>the CDLI catalog. If your text is " "not yet in the<br/>catalog, please email " "[email protected] to get<br/>an ID and designation." ) help_label = self.build_help_label(tooltip_text) panel.add(ampersand_label) panel.add(self.left_field) panel.add(equals_label) panel.add(self.right_field) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, ampersand_label, 20, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_field, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, equals_label, 5, SpringLayout.EAST, self.left_field) layout.putConstraint(SpringLayout.NORTH, equals_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_field, 5, SpringLayout.EAST, equals_label) layout.putConstraint(SpringLayout.NORTH, self.right_field, 20, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_field) layout.putConstraint(SpringLayout.NORTH, help_label, 23, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_projects_row(self): ''' Builds the projects row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. project_label = JLabel('Project: ') self.right_combo = JComboBox() self.right_combo.setEditable(True) def create_project_list(): ''' Prepares list of projects and subprojects ordered with the default one first. ''' default_project = self.projects['default'][0].split('/')[0] if '/' in self.projects['default']: default_subproject = self.projects['default'].split('/')[1] else: default_subproject = '' projects = [default_project] subprojects = [default_subproject] # User created projects might not be in default dictionary for project in self.projects.keys(): if (project != default_project and project != 'default'): projects.append(project) # Default project might not have subproject if default_project in self.projects.keys(): if default_subproject: for subproject in self.projects[default_project]: if (subproject != default_subproject): subprojects.append(subproject) return projects, subprojects self.left_combo = JComboBox(create_project_list()[0]) # Make left combo keep size no matter how long project names are self.left_combo.setPreferredSize(Dimension(125, 30)) self.left_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.left_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.left_combo.setSize(self.left_combo.getPreferredSize()) self.right_combo = JComboBox(create_project_list()[1]) # Prevent right combo to change sizes dynamically self.right_combo.setPreferredSize(Dimension(100, 30)) self.right_combo.setMinimumSize(self.left_combo.getPreferredSize()) self.right_combo.setMaximumSize(self.left_combo.getPreferredSize()) self.right_combo.setSize(self.left_combo.getPreferredSize()) action_listener = ComboActionListener(self.right_combo, self.projects) self.left_combo.addActionListener(action_listener) self.left_combo.setEditable(True) self.right_combo.setEditable(True) slash_label = JLabel('/') tooltip_text = ("<html><body>Choose project from list or insert a new " "one.<br/>You can leave the right-hand field blank." "</body><html>") help_label = self.build_help_label(tooltip_text) panel.add(project_label) panel.add(self.left_combo) panel.add(slash_label) panel.add(self.right_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, project_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, project_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.left_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, slash_label, 5, SpringLayout.EAST, self.left_combo) layout.putConstraint(SpringLayout.NORTH, slash_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.right_combo, 5, SpringLayout.EAST, slash_label) layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.right_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_language_row(self): ''' Builds the language row. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Get language list from settings.yaml, removing the default one from # the list languages = self.languages.keys() languages.remove('default') # Create necessary components and add them to panel. language_label = JLabel('Language: ') self.language_combo = JComboBox(languages) # Set selected language to default self.language_combo.setSelectedItem(self.languages['default']) tooltip_text = "Choose a language from the dropdown menu." help_label = self.build_help_label(tooltip_text) panel.add(language_label) panel.add(self.language_combo) panel.add(help_label) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, language_label, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, language_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, self.language_combo, 90, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, help_label, 5, SpringLayout.EAST, self.language_combo) layout.putConstraint(SpringLayout.NORTH, help_label, 18, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, help_label) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, help_label) # Add this to NewAtf JFrame return panel def build_buttons_row(self): ''' Add OK/Cancel/Blank buttons. ''' # Build own panel with SpringLayout. panel = JPanel() layout = SpringLayout() panel.setLayout(layout) # Create necessary components and add them to panel. create_button = JButton('Create template', actionPerformed=self.create_template) leave_button = JButton('Leave blank', actionPerformed=self.blank) cancel_button = JButton('Cancel', actionPerformed=self.cancel) panel.add(create_button) panel.add(leave_button) panel.add(cancel_button) # Set up constraints to tell panel how to position components. layout.putConstraint(SpringLayout.WEST, create_button, 15, SpringLayout.WEST, panel) layout.putConstraint(SpringLayout.NORTH, create_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, leave_button, 5, SpringLayout.EAST, create_button) layout.putConstraint(SpringLayout.NORTH, leave_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.WEST, cancel_button, 5, SpringLayout.EAST, leave_button) layout.putConstraint(SpringLayout.NORTH, cancel_button, 15, SpringLayout.NORTH, panel) layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST, cancel_button) layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH, cancel_button) # Add this to NewAtf JFrame return panel def build_help_label(self, tooltip_text): icon = ImageIcon(find_image_resource('smallhelp')) label = JLabel() label.setIcon(icon) label.setToolTipText(tooltip_text) return label def cancel(self, event): self.cancelled = True self.dispose() def blank(self, event): self.controller.show_template() self.dispose() def create_template(self, event): ''' Put together user selected elements of the template following ATF file format. ''' # &-line # E.g. &X001001 = JCS 48, 089 and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'), self.right_field.getText().encode('utf-8')) # Project line # E.g. #project: cams/gkab # E.g. #project: rimanum project_line = "#project: {}".format( self.left_combo.getSelectedItem().encode('utf-8')) if self.right_combo.getSelectedItem(): project_line = "{}/{}".format( project_line, self.right_combo.getSelectedItem().encode('utf-8')) # Language line # E.g. #atf: lang akk-x-stdbab language = self.language_combo.getSelectedItem() language_code = self.languages[language] # Protocol line/s # E.g. #atf: use unicode protocols = '' for protocol in self.protocols: protocols += '#atf: use {}\n'.format(protocol) # Put together all lines to create the template and show in ATF area self.controller.template = ('{}\n' '{}\n' '#atf: lang {}\n' '{}\n'.format(and_line, project_line, language_code, protocols) ) self.controller.show_template() self.dispose()
def __init__(self, view): JPanel.__init__(self) self.view = view self.background = Color.white self.config_panel_height = 60 mainPanel = JPanel(background=self.background, layout=BorderLayout()) mainPanel.border = self.RoundedBorder() configPanel = JPanel(background=self.background, visible=False) self.layout = BorderLayout() self.add(mainPanel, BorderLayout.NORTH) self.add(configPanel, BorderLayout.SOUTH) self.config_button = JButton(Icon.arrowdown, rolloverIcon=ShadedIcon.arrowdown, toolTipText='configure', actionPerformed=self.configure, borderPainted=False, focusPainted=False, contentAreaFilled=False) self.add(self.config_button) self.configPanel = configPanel self.slider = JSlider(0, 1, 0, background=self.background) self.slider.snapToTicks = True mainPanel.add(self.slider) self.slider.addChangeListener(self) self.min_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.max_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.left_panel = JPanel(background=self.background) self.left_panel.add(JButton(Icon.restart, rolloverIcon=ShadedIcon.restart, toolTipText='restart', actionPerformed=self.start, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.left_panel.add(self.min_time) self.left_panel.add(JButton(icon=Icon.start, rolloverIcon=ShadedIcon.start, toolTipText='jump to beginning', actionPerformed=lambda x: self.slider.setValue(self.slider.minimum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel = JPanel(background=self.background) self.right_panel.add(JButton(icon=Icon.end, rolloverIcon=ShadedIcon.end, toolTipText='jump to end', actionPerformed=lambda x: self.slider.setValue(self.slider.maximum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel.add(self.max_time) self.playpause_button = JButton(Icon.play, actionPerformed=self.pause, rolloverIcon=ShadedIcon.play, toolTipText='continue', borderPainted=False, focusPainted=False, contentAreaFilled=False) self.right_panel.add(self.playpause_button) mainPanel.add(self.left_panel, BorderLayout.WEST) mainPanel.add(self.right_panel, BorderLayout.EAST) pdf = JPanel(layout=BorderLayout(), opaque=False) pdf.add(JButton(Icon.pdf, rolloverIcon=ShadedIcon.pdf, toolTipText='save pdf', actionPerformed=self.save_pdf, borderPainted=False, focusPainted=False, contentAreaFilled=False)) pdf.add(JLabel('pdf', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) pdf.maximumSize = pdf.preferredSize configPanel.add(pdf) self.data = JPanel(layout=BorderLayout(), opaque=False) self.data.add(JButton(Icon.data, rolloverIcon=ShadedIcon.data, toolTipText='examine data', actionPerformed=self.show_data, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.data.add(JLabel('data', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) self.data.maximumSize = self.data.preferredSize configPanel.add(self.data) mode = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['default', 'rate', 'direct']) if self.view.network.mode in [SimulationMode.DEFAULT, SimulationMode.PRECISE]: cb.setSelectedIndex(0) elif self.view.network.mode in [SimulationMode.RATE]: cb.setSelectedIndex(1) elif self.view.network.mode in [SimulationMode.DIRECT, SimulationMode.APPROXIMATE]: cb.setSelectedIndex(2) cb.addActionListener(self) self.mode_combobox = cb mode.add(cb) mode.add(JLabel('mode'), BorderLayout.NORTH) mode.maximumSize = mode.preferredSize configPanel.add(mode) dt = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['0.001', '0.0005', '0.0002', '0.0001']) cb.setSelectedIndex(0) self.view.dt = float(cb.getSelectedItem()) cb.addActionListener(self) self.dt_combobox = cb dt.add(cb) dt.add(JLabel('time step'), BorderLayout.NORTH) dt.maximumSize = dt.preferredSize configPanel.add(dt) rate = JPanel(layout=BorderLayout(), opaque=False) self.rate_combobox = JComboBox(['fastest', '1x', '0.5x', '0.2x', '0.1x', '0.05x', '0.02x', '0.01x', '0.005x', '0.002x', '0.001x']) self.rate_combobox.setSelectedIndex(4) self.view.set_target_rate(self.rate_combobox.getSelectedItem()) self.rate_combobox.addActionListener(self) rate.add(self.rate_combobox) rate.add(JLabel('speed'), BorderLayout.NORTH) rate.maximumSize = rate.preferredSize configPanel.add(rate) spin1 = JPanel(layout=BorderLayout(), opaque=False) self.record_time_spinner = JSpinner(SpinnerNumberModel((self.view.timelog.tick_limit - 1) * self.view.dt, 0.1, 100, 1), stateChanged=self.tick_limit) spin1.add(self.record_time_spinner) spin1.add(JLabel('recording time'), BorderLayout.NORTH) spin1.maximumSize = spin1.preferredSize configPanel.add(spin1) spin2 = JPanel(layout=BorderLayout(), opaque=False) self.filter_spinner = JSpinner(SpinnerNumberModel(self.view.tau_filter, 0, 0.5, 0.01), stateChanged=self.tau_filter) spin2.add(self.filter_spinner) spin2.add(JLabel('filter'), BorderLayout.NORTH) spin2.maximumSize = spin2.preferredSize configPanel.add(spin2) spin3 = JPanel(layout=BorderLayout(), opaque=False) self.time_shown_spinner = JSpinner(SpinnerNumberModel(self.view.time_shown, 0.01, 50, 0.1), stateChanged=self.time_shown) spin3.add(self.time_shown_spinner) spin3.add(JLabel('time shown'), BorderLayout.NORTH) spin3.maximumSize = spin3.preferredSize configPanel.add(spin3) spin4 = JPanel(layout=BorderLayout(), opaque=False) self.freq_spinner = JSpinner(SpinnerNumberModel(1000.0/self.view.data_update_period, 1, 50, 1), stateChanged=self.update_frequency) spin4.add(self.freq_spinner) spin4.add(JLabel('freq (Hz)'), BorderLayout.NORTH) spin4.maximumSize = spin4.preferredSize configPanel.add(spin4) layout = JPanel(layout=BorderLayout(), opaque=False) layout.add(JButton(icon=Icon.save, rolloverIcon=ShadedIcon.save, actionPerformed=self.save, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='save layout'), BorderLayout.WEST) layout.add(JButton(icon=Icon.restore, rolloverIcon=ShadedIcon.restore, actionPerformed=self.restore, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='restore layout'), BorderLayout.EAST) layout.add(JLabel('layout', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) layout.maximumSize = layout.preferredSize configPanel.add(layout) configPanel.setPreferredSize(java.awt.Dimension(20, self.config_panel_height)) configPanel.visible = False for c in [dt, rate, spin1, spin2, spin3]: c.border = javax.swing.border.EmptyBorder(0, 10, 0, 10)
class TimeControl(JPanel, ChangeListener, ActionListener): def __init__(self, view): JPanel.__init__(self) self.view = view self.background = Color.white self.config_panel_height = 60 mainPanel = JPanel(background=self.background, layout=BorderLayout()) mainPanel.border = self.RoundedBorder() configPanel = JPanel(background=self.background, visible=False) self.layout = BorderLayout() self.add(mainPanel, BorderLayout.NORTH) self.add(configPanel, BorderLayout.SOUTH) self.config_button = JButton(Icon.arrowdown, rolloverIcon=ShadedIcon.arrowdown, toolTipText='configure', actionPerformed=self.configure, borderPainted=False, focusPainted=False, contentAreaFilled=False) self.add(self.config_button) self.configPanel = configPanel self.slider = JSlider(0, 1, 0, background=self.background) self.slider.snapToTicks = True mainPanel.add(self.slider) self.slider.addChangeListener(self) self.min_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.max_time = JLabel(' 0.0000 ', opaque=True, background=self.background) self.left_panel = JPanel(background=self.background) self.left_panel.add(JButton(Icon.restart, rolloverIcon=ShadedIcon.restart, toolTipText='restart', actionPerformed=self.start, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.left_panel.add(self.min_time) self.left_panel.add(JButton(icon=Icon.start, rolloverIcon=ShadedIcon.start, toolTipText='jump to beginning', actionPerformed=lambda x: self.slider.setValue(self.slider.minimum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel = JPanel(background=self.background) self.right_panel.add(JButton(icon=Icon.end, rolloverIcon=ShadedIcon.end, toolTipText='jump to end', actionPerformed=lambda x: self.slider.setValue(self.slider.maximum), borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.right_panel.add(self.max_time) self.playpause_button = JButton(Icon.play, actionPerformed=self.pause, rolloverIcon=ShadedIcon.play, toolTipText='continue', borderPainted=False, focusPainted=False, contentAreaFilled=False) self.right_panel.add(self.playpause_button) mainPanel.add(self.left_panel, BorderLayout.WEST) mainPanel.add(self.right_panel, BorderLayout.EAST) pdf = JPanel(layout=BorderLayout(), opaque=False) pdf.add(JButton(Icon.pdf, rolloverIcon=ShadedIcon.pdf, toolTipText='save pdf', actionPerformed=self.save_pdf, borderPainted=False, focusPainted=False, contentAreaFilled=False)) pdf.add(JLabel('pdf', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) pdf.maximumSize = pdf.preferredSize configPanel.add(pdf) self.data = JPanel(layout=BorderLayout(), opaque=False) self.data.add(JButton(Icon.data, rolloverIcon=ShadedIcon.data, toolTipText='examine data', actionPerformed=self.show_data, borderPainted=False, focusPainted=False, contentAreaFilled=False)) self.data.add(JLabel('data', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) self.data.maximumSize = self.data.preferredSize configPanel.add(self.data) mode = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['default', 'rate', 'direct']) if self.view.network.mode in [SimulationMode.DEFAULT, SimulationMode.PRECISE]: cb.setSelectedIndex(0) elif self.view.network.mode in [SimulationMode.RATE]: cb.setSelectedIndex(1) elif self.view.network.mode in [SimulationMode.DIRECT, SimulationMode.APPROXIMATE]: cb.setSelectedIndex(2) cb.addActionListener(self) self.mode_combobox = cb mode.add(cb) mode.add(JLabel('mode'), BorderLayout.NORTH) mode.maximumSize = mode.preferredSize configPanel.add(mode) dt = JPanel(layout=BorderLayout(), opaque=False) cb = JComboBox(['0.001', '0.0005', '0.0002', '0.0001']) cb.setSelectedIndex(0) self.view.dt = float(cb.getSelectedItem()) cb.addActionListener(self) self.dt_combobox = cb dt.add(cb) dt.add(JLabel('time step'), BorderLayout.NORTH) dt.maximumSize = dt.preferredSize configPanel.add(dt) rate = JPanel(layout=BorderLayout(), opaque=False) self.rate_combobox = JComboBox(['fastest', '1x', '0.5x', '0.2x', '0.1x', '0.05x', '0.02x', '0.01x', '0.005x', '0.002x', '0.001x']) self.rate_combobox.setSelectedIndex(4) self.view.set_target_rate(self.rate_combobox.getSelectedItem()) self.rate_combobox.addActionListener(self) rate.add(self.rate_combobox) rate.add(JLabel('speed'), BorderLayout.NORTH) rate.maximumSize = rate.preferredSize configPanel.add(rate) spin1 = JPanel(layout=BorderLayout(), opaque=False) self.record_time_spinner = JSpinner(SpinnerNumberModel((self.view.timelog.tick_limit - 1) * self.view.dt, 0.1, 100, 1), stateChanged=self.tick_limit) spin1.add(self.record_time_spinner) spin1.add(JLabel('recording time'), BorderLayout.NORTH) spin1.maximumSize = spin1.preferredSize configPanel.add(spin1) spin2 = JPanel(layout=BorderLayout(), opaque=False) self.filter_spinner = JSpinner(SpinnerNumberModel(self.view.tau_filter, 0, 0.5, 0.01), stateChanged=self.tau_filter) spin2.add(self.filter_spinner) spin2.add(JLabel('filter'), BorderLayout.NORTH) spin2.maximumSize = spin2.preferredSize configPanel.add(spin2) spin3 = JPanel(layout=BorderLayout(), opaque=False) self.time_shown_spinner = JSpinner(SpinnerNumberModel(self.view.time_shown, 0.01, 50, 0.1), stateChanged=self.time_shown) spin3.add(self.time_shown_spinner) spin3.add(JLabel('time shown'), BorderLayout.NORTH) spin3.maximumSize = spin3.preferredSize configPanel.add(spin3) spin4 = JPanel(layout=BorderLayout(), opaque=False) self.freq_spinner = JSpinner(SpinnerNumberModel(1000.0/self.view.data_update_period, 1, 50, 1), stateChanged=self.update_frequency) spin4.add(self.freq_spinner) spin4.add(JLabel('freq (Hz)'), BorderLayout.NORTH) spin4.maximumSize = spin4.preferredSize configPanel.add(spin4) layout = JPanel(layout=BorderLayout(), opaque=False) layout.add(JButton(icon=Icon.save, rolloverIcon=ShadedIcon.save, actionPerformed=self.save, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='save layout'), BorderLayout.WEST) layout.add(JButton(icon=Icon.restore, rolloverIcon=ShadedIcon.restore, actionPerformed=self.restore, borderPainted=False, focusPainted=False, contentAreaFilled=False, margin=java.awt.Insets(0, 0, 0, 0), toolTipText='restore layout'), BorderLayout.EAST) layout.add(JLabel('layout', horizontalAlignment=javax.swing.SwingConstants.CENTER), BorderLayout.NORTH) layout.maximumSize = layout.preferredSize configPanel.add(layout) configPanel.setPreferredSize(java.awt.Dimension(20, self.config_panel_height)) configPanel.visible = False for c in [dt, rate, spin1, spin2, spin3]: c.border = javax.swing.border.EmptyBorder(0, 10, 0, 10) def show_data(self, event): frame = JFrame('%s Data' % self.view.network.name) frame.visible = True frame.add(timeview.data.DataPanel(self.view)) frame.size = (500, 600) def forward_one_frame(self, event): self.slider.setValue(self.slider.value + 1) def backward_one_frame(self, event): self.slider.setValue(self.slider.value - 1) def set_max_time(self, maximum): self.slider.maximum = maximum self.max_time.text = ' %1.4f ' % (self.view.dt * maximum) def set_min_time(self, minimum): self.slider.minimum = minimum self.min_time.text = ' %1.4f ' % (self.view.dt * minimum) def stateChanged(self, event): self.view.current_tick = self.slider.value self.view.area.repaint() def start(self, event): self.view.restart = True def configure(self, event): view_state = self.view.frame.getExtendedState() if self.configPanel.visible: self.view.frame.setSize(self.view.frame.width, self.view.frame.height - self.config_panel_height) self.configPanel.visible = False self.config_button.icon = Icon.arrowdown self.config_button.rolloverIcon = ShadedIcon.arrowdown self.config_button.toolTipText = 'configure' else: if(view_state & self.view.frame.MAXIMIZED_BOTH == self.view.frame.MAXIMIZED_BOTH): self.view.frame.setSize(self.view.frame.width, self.view.frame.height) else: self.view.frame.setSize(self.view.frame.width, self.view.frame.height + self.config_panel_height) self.configPanel.visible = True self.config_button.icon = Icon.arrowup self.config_button.rolloverIcon = ShadedIcon.arrowup self.config_button.toolTipText = 'hide configuration' self.view.frame.setExtendedState(view_state) self.view.frame.layout.layoutContainer(self.view.frame) self.layout.layoutContainer(self) self.view.frame.layout.layoutContainer(self.view.frame) self.layout.layoutContainer(self) self.view.frame.layout.layoutContainer(self.view.frame) self.view.frame.repaint() def pause(self, event): self.view.paused = not self.view.paused if self.view.paused: self.playpause_button.icon = Icon.play self.playpause_button.rolloverIcon = ShadedIcon.play self.playpause_button.toolTipText = 'continue' else: self.playpause_button.icon = Icon.pause self.playpause_button.rolloverIcon = ShadedIcon.pause self.playpause_button.toolTipText = 'pause' def tau_filter(self, event): self.view.tau_filter = float(event.source.value) self.view.area.repaint() def time_shown(self, event): self.view.time_shown = float(event.source.value) self.view.area.repaint() def actionPerformed(self, event): dt = float(self.dt_combobox.getSelectedItem()) if dt != self.view.dt: self.view.dt = dt self.record_time_spinner.value = (self.view.timelog.tick_limit - 1) * self.view.dt self.dt_combobox.repaint() self.view.restart = True self.view.set_target_rate(self.rate_combobox.getSelectedItem()) if self.mode_combobox is not None: mode = self.mode_combobox.getSelectedItem() if mode == 'default': requested = SimulationMode.DEFAULT elif mode == 'rate': requested = SimulationMode.RATE elif mode == 'direct': requested = SimulationMode.DIRECT if requested != self.view.network.mode: self.view.requested_mode = requested def tick_limit(self, event): self.view.timelog.tick_limit = int(event.source.value / self.view.dt) + 1 def update_frequency(self, event): self.view.data_update_period = 1000.0 / event.source.value def save(self, event): self.view.save() def restore(self, event): self.view.restore() def save_pdf(self, event): from com.itextpdf.text.pdf import PdfWriter from com.itextpdf.text import Document fileChooser = JFileChooser() fileChooser.setSelectedFile(java.io.File('%s.pdf' % self.view.network.name)) if fileChooser.showSaveDialog(self) == JFileChooser.APPROVE_OPTION: f = fileChooser.getSelectedFile() doc = Document() writer = PdfWriter.getInstance(doc, java.io.FileOutputStream(f)) doc.open() cb = writer.getDirectContent() w = self.view.area.size.width h = self.view.area.size.height pw = 550 ph = 800 tp = cb.createTemplate(pw, ph) g2 = tp.createGraphicsShapes(pw, ph) at = java.awt.geom.AffineTransform() s = min(float(pw) / w, float(ph) / h) at.scale(s, s) g2.transform(at) self.view.area.pdftemplate = tp, s self.view.area.paint(g2) self.view.area.pdftemplate = None g2.dispose() cb.addTemplate(tp, 20, 0) doc.close() class RoundedBorder(javax.swing.border.AbstractBorder): def __init__(self): self.color = Color(0.7, 0.7, 0.7) def getBorderInsets(self, component): return java.awt.Insets(5, 5, 5, 5) def paintBorder(self, c, g, x, y, width, height): g.color = self.color g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawRoundRect(x, y, width - 1, height - 1, 10, 10)