def _prepare_components(self, values): for scope_tool in Application.SCOPE_TOOLS: check_box = JCheckBox(scope_tool) check_box.setSelected(scope_tool in values['scope_tools']) check_box.addItemListener(self) self._check_boxes.append(check_box) self.add(check_box)
def addApplicationCheckbox(app, app_id, ap): checkbox = JCheckBox("{} ({})".format(app.capitalize(), app_id), actionPerformed= ap) checkbox.setActionCommand(app) checkbox.setSelected(True) checkbox.setVisible(False) checkbox.setActionCommand(app_id) return checkbox
def display(self, values): self.add(JLabel('<html><b>Statuses:</b></html>')) for status in Application.ITEM_STATUSES: check_box = JCheckBox(status) check_box.setSelected(status in values['statuses']) check_box.addItemListener(self) self._check_boxes.append(check_box) self.add(check_box)
class EditCurveAttr(JPanel): def __init__(self, cattr): self.attr = cattr self.cbox = JColorChooser(self.attr.color) self.sym_panel = EditSymbolAttr(cattr.sym_prop) self.thickness_field = JTextField(str(cattr.thickness), 2) self.draw_symbol_box = JCheckBox("Draw Symbol?", cattr.draw_symbol) self.dps_field = JTextField(str(self.attr.data_per_symbol), 2) self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys()) self.dash_box.setSelectedItem(self.attr.dash_type) self.dash_box.setBorder( BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)")) tpanelx = JPanel() tpanelx.add(self.thickness_field) tpanelx.setBorder( BorderFactory.createTitledBorder("curve thickness (integer)")) tpanely = JPanel() tpanely.add(self.dps_field) tpanely.setBorder( BorderFactory.createTitledBorder("data per symbol(integer)")) tpanel = JPanel() tpanel.setLayout(GridLayout(2, 2)) tpanel.add(self.draw_symbol_box) tpanel.add(tpanelx) tpanel.add(tpanely) tpanel.add(self.dash_box) panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(self.cbox, BorderLayout.CENTER) panel1.add(tpanel, BorderLayout.SOUTH) panel2 = JPanel() panel2.setLayout(BorderLayout()) panel2.add(self.sym_panel, BorderLayout.CENTER) tp1 = JTabbedPane() tp1.addTab("Curve Attributes", panel1) tp1.addTab("Symbol Attributes", panel2) tp1.setSelectedComponent(panel1) self.setLayout(BorderLayout()) self.add(tp1, BorderLayout.CENTER) def setAttribute(self, cattr): self.attr = cattr self.cbox.color = self.attr.color self.sym_panel.setAttribute(cattr.sym_prop) self.thickness_field.text = str(cattr.thickness) self.dps_field.text = str(cattr.data_per_symbol) self.draw_symbol_box.setSelected(cattr.draw_symbol) self.dash_box.setSelectedItem(cattr.dash_type) def update(self): self.attr.color = self.cbox.getColor() self.attr.thickness = string.atoi(self.thickness_field.text) self.attr.data_per_symbol = string.atoi(self.dps_field.text) self.attr.draw_symbol = self.draw_symbol_box.isSelected() self.attr.dash_type = self.dash_box.getSelectedItem() #print 'Updating Self.draw_symbol',self.draw_symbol,self.attr self.sym_panel.update()
class ArloIngestModuleSettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def cache_checkbox_event(self, event): if self.cache_parse_checkbox.isSelected(): self.local_settings.set_parse_cache(True) else: self.local_settings.set_parse_cache(False) def settings_checkbox_event(self, event): if self.settings_parse_checkbox.isSelected(): self.local_settings.set_parse_settings(True) else: self.local_settings.set_parse_settings(False) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.cache_parse_checkbox = JCheckBox( "Parse Cached Files", actionPerformed=self.cache_checkbox_event) self.add(self.cache_parse_checkbox) self.settings_parse_checkbox = JCheckBox( "Parse Setting Files", actionPerformed=self.settings_checkbox_event) self.add(self.settings_parse_checkbox) # TODO: Update this for your UI def customizeComponents(self): self.cache_parse_checkbox.setSelected( self.local_settings.get_parse_cache()) self.settings_parse_checkbox.setSelected( self.local_settings.get_parse_settings()) # Return the settings used def getSettings(self): return self.local_settings
class IMDbUISettingsPanel(IngestModuleIngestJobSettingsPanel): def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() self.area.setText("message, call, user, chat") self.local_settings.setSetting('tableList', self.area.getText()) def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('Flag', 'true') self.local_settings.setSetting('tableList', self.area.getText()) else: self.local_settings.setSetting('Flag', 'false') def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Искать таблицы?".decode('UTF-8'), actionPerformed=self.checkBoxEvent) self.label0 = JLabel(" ") self.label1 = JLabel( "Введите названия интересуемых таблиц".decode('UTF-8')) self.label2 = JLabel( "через запятую, после чего установите флажок".decode('UTF-8')) self.label3 = JLabel(" ") self.panel1.add(self.checkbox) self.panel1.add(self.label0) self.panel1.add(self.label1) self.panel1.add(self.label2) self.panel1.add(self.label3) self.add(self.panel1) self.local_settings.setSetting('Flag', 'false') self.area = JTextArea(5, 25) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) self.add(self.pane) def customizeComponents(self): self.checkbox.setSelected( self.local_settings.getSetting('Flag') == 'true') self.area.setText(self.local_settings.getSetting('tableList')) def getSettings(self): return self.local_settings
class EditCurveAttr(JPanel): def __init__(self, cattr): self.attr = cattr self.cbox = JColorChooser(self.attr.color) self.sym_panel = EditSymbolAttr(cattr.sym_prop) self.thickness_field = JTextField(str(cattr.thickness),2) self.draw_symbol_box = JCheckBox("Draw Symbol?",cattr.draw_symbol) self.dps_field = JTextField(str(self.attr.data_per_symbol),2) self.dash_box = JComboBox(CurveProps.DASH_TYPES.keys()) self.dash_box.setSelectedItem(self.attr.dash_type) self.dash_box.setBorder(BorderFactory.createTitledBorder("Dash type: (Only JDK2 & Slow!)")) tpanelx = JPanel() tpanelx.add(self.thickness_field) tpanelx.setBorder(BorderFactory.createTitledBorder("curve thickness (integer)")) tpanely = JPanel() tpanely.add(self.dps_field) tpanely.setBorder(BorderFactory.createTitledBorder("data per symbol(integer)")) tpanel = JPanel();tpanel.setLayout(GridLayout(2,2)); tpanel.add(self.draw_symbol_box); tpanel.add(tpanelx); tpanel.add(tpanely); tpanel.add(self.dash_box); panel1 = JPanel() panel1.setLayout(BorderLayout()) panel1.add(self.cbox,BorderLayout.CENTER) panel1.add(tpanel, BorderLayout.SOUTH) panel2 = JPanel() panel2.setLayout(BorderLayout()) panel2.add(self.sym_panel,BorderLayout.CENTER) tp1 = JTabbedPane() tp1.addTab("Curve Attributes",panel1) tp1.addTab("Symbol Attributes",panel2) tp1.setSelectedComponent(panel1) self.setLayout(BorderLayout()) self.add(tp1,BorderLayout.CENTER) def setAttribute(self,cattr): self.attr = cattr self.cbox.color = self.attr.color self.sym_panel.setAttribute(cattr.sym_prop) self.thickness_field.text = str(cattr.thickness) self.dps_field.text = str(cattr.data_per_symbol) self.draw_symbol_box.setSelected(cattr.draw_symbol) self.dash_box.setSelectedItem(cattr.dash_type) def update(self): self.attr.color = self.cbox.getColor() self.attr.thickness = string.atoi(self.thickness_field.text) self.attr.data_per_symbol = string.atoi(self.dps_field.text) self.attr.draw_symbol = self.draw_symbol_box.isSelected() self.attr.dash_type = self.dash_box.getSelectedItem() #print 'Updating Self.draw_symbol',self.draw_symbol,self.attr self.sym_panel.update()
class PerceptualHashSettingsPanel(IngestModuleIngestJobSettingsPanel): # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('Flag', 'true') self.local_settings.setSetting('pHash', self.area.getText()) else: self.local_settings.setSetting('Flag', 'false') # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Check to activate/deactivate pHashToCheck", actionPerformed=self.checkBoxEvent) self.label0 = JLabel(" ") self.label1 = JLabel("Input your phash value for checking: ") self.label2 = JLabel(" ") self.panel1.add(self.checkbox) self.panel1.add(self.label0) self.panel1.add(self.label1) self.panel1.add(self.label2) self.add(self.panel1) self.area = JTextArea(5, 25) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected( self.local_settings.getSetting('Flag') == 'true') self.area.setText(self.local_settings.getSetting('pHash')) # Return the settings used def getSettings(self): return self.local_settings
def editRegex(self, event): selectedRowIdx = self.regexTable.getSelectedRow() if selectedRowIdx == -1: return False selectedRow = self.regexTableModel.data[selectedRowIdx] optionPane = JOptionPane() dialog = optionPane.createDialog(self._splitpane, "Edit RegEx") panel = JPanel(GridLayout(0, 2)) panel.setBorder(EmptyBorder(10, 10, 10, 10)) nameField = JTextField('', 15) nameField.text = selectedRow[0] panel.add(JLabel("Name:", SwingConstants.LEFT)) panel.add(nameField) regexField = JTextField('', 15) regexField.text = selectedRow[1] panel.add(JLabel("RegEx:", SwingConstants.LEFT)) panel.add(regexField) crawlField = JCheckBox() crawlField.setSelected(selectedRow[2]) panel.add(JLabel("Crawl:", SwingConstants.LEFT)) panel.add(crawlField) def closeDialog(event): if len(nameField.text) == 0 or len(regexField.text) == 0: JOptionPane.showMessageDialog(self._splitpane, "Name or RegEx can't be empty", "Error", JOptionPane.ERROR_MESSAGE) return self.regexTableModel.editRow( selectedRowIdx, [nameField.text, regexField.text, crawlField.isSelected()]) dialog.hide() editButton = JButton('OK', actionPerformed=closeDialog) panel.add(editButton) dialog.setSize(600, 200) dialog.setContentPane(panel) self._callbacks.customizeUiComponent(dialog) dialog.show() return True
class DropboxInjestWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() def checkBoxEvent(self, event): if self.file_checkbox.isSelected(): self.local_settings.setFileFlag(True) else: self.local_settings.setFileFlag(False) if self.dir_checkbox.isSelected(): self.local_settings.setDirFlag(True) else: self.local_settings.setDirFlag(False) def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.file_checkbox = JCheckBox("Look for Files relating to Dropbox", actionPerformed=self.checkBoxEvent) self.add(self.file_checkbox) self.dir_checkbox = JCheckBox( "Look for Directories relating to Dropbox", actionPerformed=self.checkBoxEvent) self.add(self.dir_checkbox) def customizeComponents(self): self.file_checkbox.setSelected(self.local_settings.getFileFlag()) self.dir_checkbox.setSelected(self.local_settings.getDirFlag()) # Return the settings used def getSettings(self): return self.local_settings
def run(self): #----------------------------------------------------------------------- # Create and set up the window. #----------------------------------------------------------------------- frame = JFrame('GlassPaneDemo') frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) #----------------------------------------------------------------------- # Start creating and adding components. #----------------------------------------------------------------------- changeButton = JCheckBox('Glass pane "visible"') changeButton.setSelected(0) #----------------------------------------------------------------------- # Set up the content pane, where the 'main GUI' lives. #----------------------------------------------------------------------- contentPane = frame.getContentPane() contentPane.setLayout(FlowLayout()) contentPane.add(changeButton) contentPane.add(JButton('Button 1')) contentPane.add(JButton('Button 2')) #----------------------------------------------------------------------- # Set up the menu bar, which appears above the content pane. #----------------------------------------------------------------------- menuBar = JMenuBar() menu = JMenu('Menu') menu.add(JMenuItem('Do nothing')) menuBar.add(menu) frame.setJMenuBar(menuBar) #----------------------------------------------------------------------- # Set up the glass pane, which appears over both menu bar and # content pane and is an item listener on the change button #----------------------------------------------------------------------- myGlassPane = MyGlassPane(changeButton, menuBar, contentPane) changeButton.addItemListener(myGlassPane) frame.setGlassPane(myGlassPane) #----------------------------------------------------------------------- # Resize the frame to display the visible components contain therein, # and have the frame (application) make itself visisble. #----------------------------------------------------------------------- frame.pack() frame.setVisible(1)
class CheckBoxPanel(JPanel, ItemListener): __metaclass__ = Singleton def __init__(self): super(CheckBoxPanel, self).__init__() self._check_box = None def itemStateChanged(self, event): Application.get_instance().execute( SetDomainDictValueCommand(self._get_domain_dict_type(), self._get_domain_dict_key(), self._check_box.isSelected())) def display(self, values): self._check_box = JCheckBox(self._get_label()) self._check_box.setSelected(values[self._get_domain_dict_key()]) self._check_box.addItemListener(self) self.add(self._check_box)
class SampleFileIngestModuleWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setFlag(True) else: self.local_settings.setFlag(False) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) self.checkbox = JCheckBox("Flag", actionPerformed=self.checkBoxEvent) self.add(self.checkbox) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getFlag()) # Return the settings used def getSettings(self): return self.local_settings
class WorkHelper(JFrame): def __init__(self): super(WorkHelper, self).__init__() self.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() #self.initUI() #def initUI(self): #panel = JPanel() #self.getContentPane().add(panel) ############################################################# # Layout layout = GroupLayout(self.getContentPane()) self.getContentPane().setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) ############################################################# ############################################################# # Scroll Area Input + Output Larea1 = JLabel("InputArea:") Larea2 = JLabel("OutputArea:") Sarea1 = JScrollPane() Sarea2 = JScrollPane() self.area1 = JTextArea() self.area1.setToolTipText("Input Area") self.area1.setEditable(True) self.area1.setBorder(BorderFactory.createLineBorder(Color.gray)) Sarea1.setPreferredSize(Dimension(300,100)) Sarea1.getViewport().setView((self.area1)) self.area2 = JTextArea() self.area2.setToolTipText("Output Area") self.area2.setEditable(False) self.area2.setBorder(BorderFactory.createLineBorder(Color.gray)) Sarea2.setPreferredSize(Dimension(300,100)) Sarea2.getViewport().setView((self.area2)) ############################################################# ############################################################# # Buttons self.cCurly = JCheckBox("Curly"); self.cCurly.setToolTipText("When 'Checked' Curly Brackets will surround the Categories") self.cCurly.setSelected(1) self.cCtClipB = JCheckBox("Auto-Copy"); self.cCtClipB.setToolTipText("When 'Checked' after the Categories are created they will added to the clipboard") self.cCtClipB.setSelected(1) self.cSemiC = JCheckBox("SemiColumn"); self.cSemiC.setToolTipText("When 'Checked' after the Categories are created at the end will be a semicolomn") self.cSemiC.setSelected(1) bRemoveNBSP_L = JButton("Clean LText", actionPerformed=self.bRemoveNBSP_L) bRemoveNBSP_L.setToolTipText("Removes Spaces, Tabs from the start of every text line from the input Area") bRemoveNBSP_R = JButton("Clean RText", actionPerformed=self.bRemoveNBSP_R) bRemoveNBSP_R.setToolTipText("Removes Spaces, Tabs from the end of every text line from the input Area") bCopyToInput = JButton("Copy to Input", actionPerformed=self.bCopyToInput) bCopyToInput.setToolTipText("Copy the text from the Output Area to the Input Area for further Operations") bClear = JButton("Clear", actionPerformed=self.bClear) bClear.setToolTipText("Clears the text form both Input and Output text Areas") self.iStart = JTextField(maximumSize=Dimension(40,25)) self.iStart.setToolTipText("The Start Index for the Making of the Categories") self.RThis = JTextField() self.RThis = JTextField(maximumSize=Dimension(120,25)) self.RThis.setToolTipText("Text to be replaced or The Starting C_Index") self.RThat = JTextField() self.RThat = JTextField(maximumSize=Dimension(120,25)) self.RThat.setToolTipText("Text to be placed or The Finish C_Index") bSandReplace = JButton("Replace Text", actionPerformed=self.bSandReplace) bSandReplace.setToolTipText("Replace the text from This with Thext from That in the Text from the Input Area and displays it in the Output Area") bcCat = JButton("CreatCateg", actionPerformed=self.bcCat) bcCat.setToolTipText("Create a categorical form starting C_Index to finish C_Index; Use the above text boxes to define the indexes") bC_S = JButton("Create _Series", actionPerformed=self.bC_S) bC_S.setToolTipText("Create a series form starting C_Index to finish C_Index; Use the above text boxes to define the indexes; It will create a series for every row in the Input Area") bM_Categories = JButton("Categories", actionPerformed=self.mCategories) bM_Categories.setToolTipText("Make Categories using the lines from the Input Area") #bM_Categories = JButton(maximumSize=Dimension(40,25)) # de incercat daca merge cu ; sa grupezi in [dsa] elementele ############################################################# ############################################################# # Aplication Layout 2 groups one Horizontal and one Vertical layout.setHorizontalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(Larea1) .addComponent(Sarea1) .addComponent(Sarea2) .addComponent(bCopyToInput) .addComponent(Larea2)) .addGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(bM_Categories) .addComponent(self.iStart)) .addGroup(layout.createSequentialGroup() .addComponent(self.cCurly) .addComponent(self.cSemiC) .addComponent(self.cCtClipB)) .addGroup(layout.createSequentialGroup() .addComponent(bRemoveNBSP_L) .addComponent(bRemoveNBSP_R)) .addGroup(layout.createSequentialGroup() .addComponent(self.RThis) .addComponent(self.RThat)) .addGroup(layout.createSequentialGroup() .addComponent(bSandReplace) .addComponent(bcCat)) .addGroup(layout.createSequentialGroup() .addComponent(bC_S)) .addComponent(bClear)) ) layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(Larea1) .addGroup(layout.createParallelGroup() .addComponent(Sarea1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(bM_Categories) .addComponent(self.iStart)) .addGroup(layout.createParallelGroup() .addComponent(self.cCurly) .addComponent(self.cSemiC) .addComponent(self.cCtClipB)) .addGroup(layout.createParallelGroup() .addComponent(bRemoveNBSP_L) .addComponent(bRemoveNBSP_R)) .addGroup(layout.createParallelGroup() .addComponent(self.RThis) .addComponent(self.RThat)) .addGroup(layout.createParallelGroup() .addComponent(bSandReplace) .addComponent(bcCat)) .addGroup(layout.createParallelGroup() .addComponent(bC_S)) ) ) .addGroup(layout.createParallelGroup() .addComponent(bCopyToInput) .addComponent(bClear)) .addComponent(Larea2) .addGroup(layout.createParallelGroup() .addComponent(Sarea2)) ) #layout.linkSize(SwingConstants.HORIZONTAL, [ok, bCopyToInput, close, bM_Categories]) layout.linkSize(SwingConstants.HORIZONTAL, [self.RThis,self.RThat,bRemoveNBSP_L,bRemoveNBSP_R,bCopyToInput,bM_Categories,bSandReplace,bcCat,bC_S]) #layout.linkSize(SwingConstants.HORIZONTAL, [self.cCurly,bM_Categories]) ############################################################# ############################################################# # Aplication Settings self.pack() #self.setPreferredSize(Dimension(1000, 1000)) self.setTitle("Workhelper") self.setSize(800, 500) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True) ############################################################# ############################################################# # WorkHelper class methods: def onQuit(self, e): "@sig public void setExpression(java.lang.String e)" System.exit(0) # def addToClipBoard(self, text): # "@sig public void setExpression(java.lang.String text)" # command = 'echo ' + text.strip() + '| clip' # os.system(command) # brute method for pasting into clipboard on windows def mCategories(self, e): "@sig public void setExpression(java.lang.String e)" """ Takes every line of text form the Input Area and by using a string composotion it creates the output in the SPSS dimension categories format. """ try: StartIndex = int(self.iStart.getText()) except ValueError: StartIndex=1 text=self.area1.getText().rstrip() counter=StartIndex lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': textO=textO+("_"+str(counter)+' "'+text[lastindex:i]+'",\n') lastindex=i+1 counter=counter+1 if len(text[lastindex:len(text)])>0: textO=textO+("_"+str(counter)+' "'+text[lastindex:len(text)]+'"') if len(textO)>0: if self.cCurly.isSelected(): textO = "{\n"+ textO + "\n}" if self.cSemiC.isSelected(): textO = textO + ";" self.copyToClipboard(textO) self.area2.setText(textO) def copyToClipboard(self, text): if self.cCtClipB.isSelected(): stringSelection = StringSelection(text) self.clipboard.setContents(stringSelection, None) def bCopyToInput(self, e): "@sig public void setExpression(java.lang.String e)" """Copy the Text from the Output Area to the input Area for further operations""" self.area1.setText(self.area2.getText()) def bRemoveNBSP_L(self, e): "@sig public void setExpression(java.lang.String e)" text=self.area1.getText().rstrip() textO="" lastindex=0 for i in range(0,len(text)): if text[i] == '\n': textO = textO+text[lastindex:i].lstrip()+"\n" lastindex=i+1 #print(text[0:i].lstrip()+'\n') if len(text[lastindex:len(text)])>0: textO=textO+text[lastindex:len(text)].lstrip() self.area2.setText(textO) def bRemoveNBSP_R(self, e): "@sig public void setExpression(java.lang.String e)" text=self.area1.getText().rstrip() textO="" lastindex=0 for i in range(0,len(text)): if text[i] == '\n': textO = textO+text[lastindex:i].rstrip()+"\n" lastindex=i+1 #print(text[0:i].lstrip()+'\n') if len(text[lastindex:len(text)])>0: textO=textO+text[lastindex:len(text)].rstrip() self.area2.setText(textO) def bClear(self, e): "@sig public void setExpression(java.lang.String e)" self.area1.setText("") self.area2.setText("") def bcCat(self, e): "@sig public void setExpression(java.lang.String e)" try: StartIndex = int(self.RThis.getText()) except ValueError: StartIndex=1 try: FinishIndex = int(self.RThat.getText()) except ValueError: FinishIndex=1 cCats="" for i in range(StartIndex,FinishIndex+1): if i<>FinishIndex: cCats=cCats+"_"+str(i)+"," else: cCats=cCats+"_"+str(i) if StartIndex<FinishIndex: cCats="{"+cCats+"}" self.copyToClipboard(cCats) self.area2.setText(cCats) def bSandReplace(self, e): self.area2.setText(self.area1.getText().replace(self.RThis.getText(),self.RThat.getText())) def bC_S(self, e): "@sig public void setExpression(java.lang.String e)" try: StartIndex = int(self.RThis.getText()) except ValueError: StartIndex=1 try: FinishIndex = int(self.RThat.getText()) except ValueError: FinishIndex=1 if StartIndex<FinishIndex: text=self.area1.getText().rstrip() lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': counter=StartIndex for j in range(StartIndex,FinishIndex+1): textO=textO+(text[lastindex:i]+"_"+str(counter)+" ") counter=counter+1 lastindex=i+1 textO=textO+'\n' #if len(text[lastindex:len(text)])>0: # textO=textO+("_"+str(counter)+' "'+text[lastindex:len(text)]+'"') if lastindex==0 and len(text)>0: counter=StartIndex for j in range(StartIndex,FinishIndex+1): textO=textO+(text[lastindex:i]+"_"+str(counter)+" ") counter=counter+1 if len(textO)>0: self.copyToClipboard(textO) self.area2.setText(textO)
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Autorize") # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self._enfocementStatuses = ["Authorization bypass!","Authorization enforced??? (please configure enforcement detector)","Authorization enforced!"] self.intercept = 0 self.initInterceptionFilters() self.initEnforcementDetector() self.initEnforcementDetectorUnauthorized() self.initExport() self.initConfigurationTab() self.initTabs() self.initCallbacks() self.currentRequestNumber = 1 print "Thank you for installing Autorize v0.12 extension" print "Created by Barak Tawily" print "Contributors: Barak Tawily, Federico Dotta" print "\nGithub:\nhttps://github.com/Quitten/Autorize" return def initExport(self): # ## init enforcement detector tab # exportLType = JLabel("File Type:") exportLType.setBounds(10, 10, 100, 30) exportLES = JLabel("Enforcement Statuses:") exportLES.setBounds(10, 50, 160, 30) exportFileTypes = ["HTML","CSV"] self.exportType = JComboBox(exportFileTypes) self.exportType.setBounds(100, 10, 200, 30) exportES = ["All Statuses", self._enfocementStatuses[0], self._enfocementStatuses[1], self._enfocementStatuses[2]] self.exportES = JComboBox(exportES) self.exportES.setBounds(100, 50, 200, 30) exportLES = JLabel("Statuses:") exportLES.setBounds(10, 50, 100, 30) self.exportButton = JButton("Export",actionPerformed=self.export) self.exportButton.setBounds(390, 25, 100, 30) self.exportPnl = JPanel() self.exportPnl.setLayout(None); self.exportPnl.setBounds(0, 0, 1000, 1000); self.exportPnl.add(exportLType) self.exportPnl.add(self.exportType) self.exportPnl.add(exportLES) self.exportPnl.add(self.exportES) self.exportPnl.add(self.exportButton) def initEnforcementDetector(self): # ## init enforcement detector tab # # These two variable appears to be unused... self.EDFP = ArrayList() self.EDCT = ArrayList() EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"] self.EDType = JComboBox(EDStrings) self.EDType.setBounds(80, 10, 430, 30) self.EDText = JTextArea("", 5, 30) self.EDText.setBounds(80, 50, 300, 110) self.EDModel = DefaultListModel(); self.EDList = JList(self.EDModel); self.EDList.setBounds(80, 175, 300, 110) self.EDList.setBorder(LineBorder(Color.BLACK)) self.EDAdd = JButton("Add filter",actionPerformed=self.addEDFilter) self.EDAdd.setBounds(390, 85, 120, 30) self.EDDel = JButton("Remove filter",actionPerformed=self.delEDFilter) self.EDDel.setBounds(390, 210, 120, 30) self.EDPnl = JPanel() self.EDPnl.setLayout(None); self.EDPnl.setBounds(0, 0, 1000, 1000); self.EDPnl.add(EDLType) self.EDPnl.add(self.EDType) self.EDPnl.add(EDLContent) self.EDPnl.add(self.EDText) self.EDPnl.add(self.EDAdd) self.EDPnl.add(self.EDDel) self.EDPnl.add(EDLabelList) self.EDPnl.add(self.EDList) def initEnforcementDetectorUnauthorized(self): # ## init enforcement detector tab # EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = ["Headers (simple string): (enforced message headers contains)", "Headers (regex): (enforced messege headers contains)", "Body (simple string): (enforced messege body contains)", "Body (regex): (enforced messege body contains)", "Full request (simple string): (enforced messege contains)", "Full request (regex): (enforced messege contains)", "Content-Length: (constant Content-Length number of enforced response)"] self.EDTypeUnauth = JComboBox(EDStrings) self.EDTypeUnauth.setBounds(80, 10, 430, 30) self.EDTextUnauth = JTextArea("", 5, 30) self.EDTextUnauth.setBounds(80, 50, 300, 110) self.EDModelUnauth = DefaultListModel(); self.EDListUnauth = JList(self.EDModelUnauth); self.EDListUnauth.setBounds(80, 175, 300, 110) self.EDListUnauth.setBorder(LineBorder(Color.BLACK)) self.EDAddUnauth = JButton("Add filter",actionPerformed=self.addEDFilterUnauth) self.EDAddUnauth.setBounds(390, 85, 120, 30) self.EDDelUnauth = JButton("Remove filter",actionPerformed=self.delEDFilterUnauth) self.EDDelUnauth.setBounds(390, 210, 120, 30) self.EDPnlUnauth = JPanel() self.EDPnlUnauth.setLayout(None); self.EDPnlUnauth.setBounds(0, 0, 1000, 1000); self.EDPnlUnauth.add(EDLType) self.EDPnlUnauth.add(self.EDTypeUnauth) self.EDPnlUnauth.add(EDLContent) self.EDPnlUnauth.add(self.EDTextUnauth) self.EDPnlUnauth.add(self.EDAddUnauth) self.EDPnlUnauth.add(self.EDDelUnauth) self.EDPnlUnauth.add(EDLabelList) self.EDPnlUnauth.add(self.EDListUnauth) def initInterceptionFilters(self): # ## init interception filters tab # IFStrings = ["Scope items only: (Content is not required)","URL Contains (simple string): ","URL Contains (regex): ","URL Not Contains (simple string): ","URL Not Contains (regex): "] self.IFType = JComboBox(IFStrings) self.IFType.setBounds(80, 10, 430, 30) self.IFModel = DefaultListModel(); self.IFList = JList(self.IFModel); self.IFList.setBounds(80, 175, 300, 110) self.IFList.setBorder(LineBorder(Color.BLACK)) self.IFText = JTextArea("", 5, 30) self.IFText.setBounds(80, 50, 300, 110) IFLType = JLabel("Type:") IFLType.setBounds(10, 10, 140, 30) IFLContent = JLabel("Content:") IFLContent.setBounds(10, 50, 140, 30) IFLabelList = JLabel("Filter List:") IFLabelList.setBounds(10, 165, 140, 30) self.IFAdd = JButton("Add filter",actionPerformed=self.addIFFilter) self.IFAdd.setBounds(390, 85, 120, 30) self.IFDel = JButton("Remove filter",actionPerformed=self.delIFFilter) self.IFDel.setBounds(390, 210, 120, 30) self.filtersPnl = JPanel() self.filtersPnl.setLayout(None); self.filtersPnl.setBounds(0, 0, 1000, 1000); self.filtersPnl.add(IFLType) self.filtersPnl.add(self.IFType) self.filtersPnl.add(IFLContent) self.filtersPnl.add(self.IFText) self.filtersPnl.add(self.IFAdd) self.filtersPnl.add(self.IFDel) self.filtersPnl.add(IFLabelList) self.filtersPnl.add(self.IFList) def initConfigurationTab(self): # ## init configuration tab # self.prevent304 = JCheckBox("Prevent 304 Not Modified status code") self.prevent304.setBounds(290, 25, 300, 30) self.ignore304 = JCheckBox("Ignore 304/204 status code responses") self.ignore304.setBounds(290, 5, 300, 30) self.ignore304.setSelected(True) self.autoScroll = JCheckBox("Auto Scroll") #self.autoScroll.setBounds(290, 45, 140, 30) self.autoScroll.setBounds(160, 40, 140, 30) self.doUnauthorizedRequest = JCheckBox("Check unauthenticated") self.doUnauthorizedRequest.setBounds(290, 45, 300, 30) self.doUnauthorizedRequest.setSelected(True) startLabel = JLabel("Authorization checks:") startLabel.setBounds(10, 10, 140, 30) self.startButton = JButton("Autorize is off",actionPerformed=self.startOrStop) self.startButton.setBounds(160, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) self.clearButton = JButton("Clear List",actionPerformed=self.clearList) self.clearButton.setBounds(10, 40, 100, 30) self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30) self.replaceString.setWrapStyleWord(True); self.replaceString.setLineWrap(True) self.replaceString.setBounds(10, 80, 470, 180) self.filtersTabs = JTabbedPane() self.filtersTabs.addTab("Enforcement Detector", self.EDPnl) self.filtersTabs.addTab("Detector Unauthenticated", self.EDPnlUnauth) self.filtersTabs.addTab("Interception Filters", self.filtersPnl) self.filtersTabs.addTab("Export", self.exportPnl) self.filtersTabs.setBounds(0, 280, 2000, 700) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000); self.pnl.setLayout(None); self.pnl.add(self.startButton) self.pnl.add(self.clearButton) self.pnl.add(self.replaceString) self.pnl.add(startLabel) self.pnl.add(self.autoScroll) self.pnl.add(self.ignore304) self.pnl.add(self.prevent304) self.pnl.add(self.doUnauthorizedRequest) self.pnl.add(self.filtersTabs) def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self.logTable.setAutoCreateRowSorter(True) tableWidth = self.logTable.getPreferredSize().width self.logTable.getColumn("ID").setPreferredWidth(Math.round(tableWidth / 50 * 2)) self.logTable.getColumn("URL").setPreferredWidth(Math.round(tableWidth / 50 * 24)) self.logTable.getColumn("Orig. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Modif. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Unauth. Length").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Enforcement Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self.logTable.getColumn("Authorization Unauth. Status").setPreferredWidth(Math.round(tableWidth / 50 * 4)) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener(autoScrollListener(self)) self.menuES0 = JCheckBoxMenuItem(self._enfocementStatuses[0],True) self.menuES1 = JCheckBoxMenuItem(self._enfocementStatuses[1],True) self.menuES2 = JCheckBoxMenuItem(self._enfocementStatuses[2],True) self.menuES0.addItemListener(menuTableFilter(self)) self.menuES1.addItemListener(menuTableFilter(self)) self.menuES2.addItemListener(menuTableFilter(self)) copyURLitem = JMenuItem("Copy URL"); copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.menu.add(self.menuES0) self.menu.add(self.menuES1) self.menu.add(self.menuES2) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor(self, False) self._originalresponseViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedrequestViewer = self._callbacks.createMessageEditor(self, False) self._unauthorizedresponseViewer = self._callbacks.createMessageEditor(self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Unauthenticated Request", self._unauthorizedrequestViewer.getComponent()) self.tabs.addTab("Unauthenticated Response", self._unauthorizedresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(6) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.customizeUiComponent(self.filtersTabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) # ## Events functions # def startOrStop(self, event): if self.startButton.getText() == "Autorize is off": self.startButton.setText("Autorize is on") self.startButton.setBackground(Color.GREEN) self.intercept = 1 self._callbacks.registerHttpListener(self) else: self.startButton.setText("Autorize is off") self.startButton.setBackground(Color(255, 100, 91, 255)) self.intercept = 0 self._callbacks.removeHttpListener(self) def addEDFilter(self, event): typeName = self.EDType.getSelectedItem().split(":")[0] self.EDModel.addElement(typeName + ": " + self.EDText.getText()) def delEDFilter(self, event): index = self.EDList.getSelectedIndex(); if not index == -1: self.EDModel.remove(index); def addEDFilterUnauth(self, event): typeName = self.EDTypeUnauth.getSelectedItem().split(":")[0] self.EDModelUnauth.addElement(typeName + ": " + self.EDTextUnauth.getText()) def delEDFilterUnauth(self, event): index = self.EDListUnauth.getSelectedIndex(); if not index == -1: self.EDModelUnauth.remove(index); def addIFFilter(self, event): typeName = self.IFType.getSelectedItem().split(":")[0] self.IFModel.addElement(typeName + ": " + self.IFText.getText()) def delIFFilter(self, event): index = self.IFList.getSelectedIndex(); if not index == -1: self.IFModel.remove(index); def clearList(self, event): self._lock.acquire() oldSize = self._log.size() self._log.clear() self.fireTableRowsDeleted(0, oldSize - 1) self._lock.release() def export(self, event): if self.exportType.getSelectedItem() == "HTML": self.exportToHTML() else: self.exportToCSV() def exportToCSV(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.csv")); fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() csvContent = "id\tURL\tOriginal length\tModified length\tUnauthorized length\tAuthorization Enforcement Status\tAuthorization Unauthenticated Status\n" for i in range(0,self._log.size()): if enforcementStatusFilter == "All Statuses": csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): csvContent += "%d\t%s\t%d\t%d\t%d\t%s\t%s\n" % (self._log.get(i)._id,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, self._log.get(i)._enfocementStatus, self._log.get(i)._enfocementStatusUnauthorized) f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(csvContent) f.close() def exportToHTML(self): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.html")); fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() htmlContent = """<html><title>Autorize Report by Barak Tawily</title> <style> .datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .datagrid table td, .datagrid table th { padding: 3px 10px; } .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block; padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; } table { width: 100%; table-layout: fixed; } td { border: 1px solid #35f; overflow: hidden; text-overflow: ellipsis; } td.a { width: 13%; white-space: nowrap; } td.b { width: 9%; word-wrap: break-word; } </style> <body> <h1>Autorize Report<h1> <div class="datagrid"><table> <thead><tr><th width=\"3%\">ID</th><th width=\"48%\">URL</th><th width=\"9%\">Original length</th><th width=\"9%\">Modified length</th><th width=\"9%\">Unauthorized length</th><th width=\"11%\">Authorization Enforcement Status</th><th width=\"11%\">Authorization Unauthenticated Status</th></tr></thead> <tbody>""" for i in range(0,self._log.size()): color_modified = "" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[0]: color_modified = "red" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[1]: color_modified = "yellow" if self._log.get(i)._enfocementStatus == self._enfocementStatuses[2]: color_modified = "LawnGreen" color_unauthorized = "" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[0]: color_unauthorized = "red" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[1]: color_unauthorized = "yellow" if self._log.get(i)._enfocementStatusUnauthorized == self._enfocementStatuses[2]: color_unauthorized = "LawnGreen" if enforcementStatusFilter == "All Statuses": htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) else: if (enforcementStatusFilter == self._log.get(i)._enfocementStatus) or (enforcementStatusFilter == self._log.get(i)._enfocementStatusUnauthorized): htmlContent += "<tr><td>%d</td><td><a href=\"%s\">%s</a></td><td>%d</td><td>%d</td><td>%d</td><td bgcolor=\"%s\">%s</td><td bgcolor=\"%s\">%s</td></tr>" % (self._log.get(i)._id,self._log.get(i)._url,self._log.get(i)._url, len(self._log.get(i)._originalrequestResponse.getResponse()) if self._log.get(i)._originalrequestResponse != None else 0, len(self._log.get(i)._requestResponse.getResponse()) if self._log.get(i)._requestResponse != None else 0, len(self._log.get(i)._unauthorizedRequestResponse.getResponse()) if self._log.get(i)._unauthorizedRequestResponse != None else 0, color_modified, self._log.get(i)._enfocementStatus, color_unauthorized, self._log.get(i)._enfocementStatusUnauthorized) htmlContent += "</tbody></table></div></body></html>" f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(htmlContent) f.close() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages(); if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Autorize"); cookieMenuItem = JMenuItem("Send cookie to Autorize"); requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request")) cookieMenuItem.addActionListener(handleMenuItems(self, responses[0], "cookie")) ret.add(requestMenuItem); ret.add(cookieMenuItem); return(ret); return null; # # implement ITab # def getTabCaption(self): return "Autorize" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 7 def getColumnName(self, columnIndex): if columnIndex == 0: return "ID" if columnIndex == 1: return "URL" if columnIndex == 2: return "Orig. Length" if columnIndex == 3: return "Modif. Length" if columnIndex == 4: return "Unauth. Length" if columnIndex == 5: return "Authorization Enforcement Status" if columnIndex == 6: return "Authorization Unauth. Status" return "" def getColumnClass(self, columnIndex): if columnIndex == 0: return Integer if columnIndex == 1: return String if columnIndex == 2: return Integer if columnIndex == 3: return Integer if columnIndex == 4: return Integer if columnIndex == 5: return String if columnIndex == 6: return String return String def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return logEntry._id if columnIndex == 1: return logEntry._url.toString() if columnIndex == 2: return len(logEntry._originalrequestResponse.getResponse()) if columnIndex == 3: return len(logEntry._requestResponse.getResponse()) if columnIndex == 4: if logEntry._unauthorizedRequestResponse != None: return len(logEntry._unauthorizedRequestResponse.getResponse()) else: #return "-" return 0 if columnIndex == 5: return logEntry._enfocementStatus if columnIndex == 6: return logEntry._enfocementStatusUnauthorized return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() # # implement IHttpListener # def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): #if (self.intercept == 1) and (toolFlag != self._callbacks.TOOL_EXTENDER): if (self.intercept == 1) and (toolFlag == self._callbacks.TOOL_PROXY): if self.prevent304.isSelected(): if messageIsRequest: requestHeaders = list(self._helpers.analyzeRequest(messageInfo).getHeaders()) newHeaders = list() found = 0 for header in requestHeaders: if not "If-None-Match:" in header and not "If-Modified-Since:" in header: newHeaders.append(header) found = 1 if found == 1: requestInfo = self._helpers.analyzeRequest(messageInfo) bodyBytes = messageInfo.getRequest()[requestInfo.getBodyOffset():] bodyStr = self._helpers.bytesToString(bodyBytes) messageInfo.setRequest(self._helpers.buildHttpMessage(newHeaders, bodyStr)) if not messageIsRequest: if not self.replaceString.getText() in self._helpers.analyzeRequest(messageInfo).getHeaders(): if self.ignore304.isSelected(): firstHeader = self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders()[0] if "304" in firstHeader or "204" in firstHeader: return if self.IFList.getModel().getSize() == 0: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) else: urlString = str(self._helpers.analyzeRequest(messageInfo).getUrl()) do_the_check = 1 for i in range(0,self.IFList.getModel().getSize()): if self.IFList.getModel().getElementAt(i).split(":")[0] == "Scope items only": currentURL = URL(urlString) if not self._callbacks.isInScope(currentURL): do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (simple string)": if self.IFList.getModel().getElementAt(i)[30:] not in urlString: do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Contains (regex)": regex_string = self.IFList.getModel().getElementAt(i)[22:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(urlString): do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (simple string)": if self.IFList.getModel().getElementAt(i)[34:] in urlString: do_the_check = 0 if self.IFList.getModel().getElementAt(i).split(":")[0] == "URL Not Contains (regex)": regex_string = self.IFList.getModel().getElementAt(i)[26:] p = re.compile(regex_string, re.IGNORECASE) if p.search(urlString): do_the_check = 0 if do_the_check: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) return def sendRequestToAutorizeWork(self,messageInfo): if messageInfo.getResponse() == None: message = self.makeMessage(messageInfo,False,False) requestResponse = self.makeRequest(messageInfo, message) self.checkAuthorization(requestResponse,self._helpers.analyzeResponse(requestResponse.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) else: self.checkAuthorization(messageInfo,self._helpers.analyzeResponse(messageInfo.getResponse()).getHeaders(),self.doUnauthorizedRequest.isSelected()) def makeRequest(self, messageInfo, message): requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() return self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message) def makeMessage(self, messageInfo, removeOrNot, authorizeOrNot): requestInfo = self._helpers.analyzeRequest(messageInfo) headers = requestInfo.getHeaders() if removeOrNot: headers = list(headers) removeHeaders = ArrayList() removeHeaders.add(self.replaceString.getText()[0:self.replaceString.getText().index(":")]) for header in headers[:]: for removeHeader in removeHeaders: if removeHeader in header: headers.remove(header) if authorizeOrNot: headers.append(self.replaceString.getText()) msgBody = messageInfo.getRequest()[requestInfo.getBodyOffset():] return self._helpers.buildHttpMessage(headers, msgBody) def checkBypass(self,oldStatusCode,newStatusCode,oldContentLen,newContentLen,filters,requestResponse): analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse()) impression = "" if oldStatusCode == newStatusCode: if oldContentLen == newContentLen: impression = self._enfocementStatuses[0] else: auth_enforced = 1 for filter in filters: if str(filter).startswith("Headers (simple string): "): if not(filter[25:] in self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])): auth_enforced = 0 if str(filter).startswith("Headers (regex): "): regex_string = filter[17:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[0:analyzedResponse.getBodyOffset()])): auth_enforced = 0 if str(filter).startswith("Body (simple string): "): if not(filter[22:] in self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])): auth_enforced = 0 if str(filter).startswith("Body (regex): "): regex_string = filter[14:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse()[analyzedResponse.getBodyOffset():])): auth_enforced = 0 if str(filter).startswith("Full request (simple string): "): if not(filter[30:] in self._helpers.bytesToString(requestResponse.getResponse())): auth_enforced = 0 if str(filter).startswith("Full request (regex): "): regex_string = filter[22:] p = re.compile(regex_string, re.IGNORECASE) if not p.search(self._helpers.bytesToString(requestResponse.getResponse())): auth_enforced = 0 if str(filter).startswith("Content-Length: "): if newContentLen != filter: auth_enforced = 0 if auth_enforced: impression = self._enfocementStatuses[2] else: impression = self._enfocementStatuses[1] else: impression = self._enfocementStatuses[2] return impression def checkAuthorization(self, messageInfo, originalHeaders, checkUnauthorized): message = self.makeMessage(messageInfo,True,True) requestResponse = self.makeRequest(messageInfo, message) analyzedResponse = self._helpers.analyzeResponse(requestResponse.getResponse()) oldStatusCode = originalHeaders[0] newStatusCode = analyzedResponse.getHeaders()[0] oldContentLen = self.getContentLength(originalHeaders) newContentLen = self.getContentLength(analyzedResponse.getHeaders()) # Check unauthorized request if checkUnauthorized: messageUnauthorized = self.makeMessage(messageInfo,True,False) requestResponseUnauthorized = self.makeRequest(messageInfo, messageUnauthorized) analyzedResponseUnauthorized = self._helpers.analyzeResponse(requestResponseUnauthorized.getResponse()) statusCodeUnauthorized = analyzedResponseUnauthorized.getHeaders()[0] contentLenUnauthorized = self.getContentLength(analyzedResponseUnauthorized.getHeaders()) EDFilters = self.EDModel.toArray() impression = self.checkBypass(oldStatusCode,newStatusCode,oldContentLen,newContentLen,EDFilters,requestResponse) if checkUnauthorized: EDFiltersUnauth = self.EDModelUnauth.toArray() impressionUnauthorized = self.checkBypass(oldStatusCode,statusCodeUnauthorized,oldContentLen,contentLenUnauthorized,EDFiltersUnauth,requestResponseUnauthorized) self._lock.acquire() row = self._log.size() if checkUnauthorized: self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,self._callbacks.saveBuffersToTempFiles(requestResponseUnauthorized),impressionUnauthorized)) # same requests not include again. else: self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,None,"Disabled")) # same requests not include again. self.fireTableRowsInserted(row, row) self.currentRequestNumber = self.currentRequestNumber + 1 self._lock.release() def getContentLength(self, analyzedResponseHeaders): for header in analyzedResponseHeaders: if "Content-Length:" in header: return header; return "null" def getCookieFromMessage(self, messageInfo): headers = list(self._helpers.analyzeRequest(messageInfo.getRequest()).getHeaders()) for header in headers: if "Cookie:" in header: return header return None
class CustomCellRenderer(DefaultTreeCellRenderer): """Renders the various tree controls (checkbox, tristate checkbox, string values etc.)""" def __init__(self): DefaultTreeCellRenderer.__init__(self) flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox() self.cb.setBackground(None) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox() self.tcb.setBackground(None) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton() self.rb.setBackground(None) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel) def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus): """Return a swing control appropriate for the node type of the supplied value""" if isinstance(value, DefaultMutableTreeNode): nodeData = value.getUserObject() if isinstance(nodeData, TreeNodeData): t = nodeData.getNodeType() isEnabled = nodeData.getVisible() > 0 # Boolean checkbox if t.isType([NodeType._bool]): self.cbLabel.setText(nodeData.getText()) self.cb.setEnabled(isEnabled) self.cbLabel.setEnabled(isEnabled) if nodeData.getTriValue() == 0: self.cb.setSelected(False) else: self.cb.setSelected(True) control = self.cbPanel # Tristate chekcbox elif t.isType([NodeType._tri]): control = self.tcbPanel self.tcbLabel.setText(nodeData.getText()) self.tcb.setEnabled(isEnabled) self.tcbLabel.setEnabled(isEnabled) self.tcb.setTriState(nodeData.getTriValue()) # Radio button elif t.isType([NodeType._radio]): self.rbLabel.setText(nodeData.getText()) self.rb.setEnabled(isEnabled) self.rbLabel.setEnabled(isEnabled) if nodeData.getTriValue() == 0: self.rb.setSelected(False) else: self.rb.setSelected(True) control = self.rbPanel # Text field elif t.isType([NodeType._text]): control = DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) control.setText(nodeData.getText() + ": " + str(nodeData.getValue())) # Default tree cell (a node with an icon and a label) else: control = DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) control.setText(nodeData.getText()) self.setColors(control, nodeData, selected) # Background color for the tree item # log.info("getTreeCellRendererComponent", t.getType(), isEnabled, "'" + nodeData.getText() + "'") control.setEnabled(isEnabled) return control # log.info("Warning: getTreeCellRendererComponent() fallthrough", nodeData) return DefaultTreeCellRenderer.getTreeCellRendererComponent( self, tree, value, selected, expanded, leaf, row, hasFocus) def setColors(self, control, data, selected): """Set background color fot the tree item.""" if selected: control.setForeground(self.getTextSelectionColor()) control.setBackground(self.getBackgroundSelectionColor()) else: control.setForeground(self.getTextNonSelectionColor()) control.setBackground(self.getBackgroundNonSelectionColor())
class NEWProcess_AmcacheWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('Default_Mime_Types', 'true') else: self.local_settings.setSetting('Default_Mime_Types', 'false') if self.checkbox1.isSelected(): self.local_settings.setSetting('All_Mime_Types', 'true') else: self.local_settings.setSetting('All_Mime_Types', 'false') if self.checkbox2.isSelected(): self.local_settings.setSetting('Include_Slack_Space', 'true') else: self.local_settings.setSetting('Include_Slack_Space', 'false') # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.label1 = JLabel("*** Default mime types.") self.label2 = JLabel(" ") self.label3 = JLabel("octet-stream x-splite3 vnd.ms-excel.sheet.4 msoffice") self.label4 = JLabel("msword vnd.ms-excel vnd.ms-powerpoint") self.label5 = JLabel(" ") self.checkbox = JCheckBox("Default Mime Types Files", actionPerformed=self.checkBoxEvent) self.checkbox1 = JCheckBox("All Mime Types Files", actionPerformed=self.checkBoxEvent) self.checkbox2 = JCheckBox("Include Slack Space Of Files", actionPerformed=self.checkBoxEvent) self.panel1.add(self.label1) self.panel1.add(self.label2) self.panel1.add(self.label3) self.panel1.add(self.label4) self.panel1.add(self.label5) self.panel1.add(self.checkbox) self.panel1.add(self.checkbox1) self.panel1.add(self.checkbox2) self.add(self.panel1) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getSetting('Default_Mime_Types') == 'true') self.checkbox1.setSelected(self.local_settings.getSetting('All_Mime_Types') == 'true') self.checkbox2.setSelected(self.local_settings.getSetting('Include_Slack_Space') == 'true') # Return the settings used def getSettings(self): return self.local_settings
class GUI_PSQLiteUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setFlag(True) self.local_settings.setArea(self.area.getText()) else: self.local_settings.setFlag(False) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Check to activate/deactivate TextArea", actionPerformed=self.checkBoxEvent) self.label0 = JLabel(" ") self.label1 = JLabel("Input in SQLite DB's in area below,") self.label2 = JLabel("seperate values by commas.") self.label3 = JLabel("then check the box above.") self.label4 = JLabel(" ") self.panel1.add(self.checkbox) self.panel1.add(self.label0) self.panel1.add(self.label1) self.panel1.add(self.label2) self.panel1.add(self.label3) self.panel1.add(self.label4) self.add(self.panel1) self.area = JTextArea(5, 25) #self.area.getDocument().addDocumentListener(self.area) #self.area.addKeyListener(listener) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self.area) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getFlag()) # Return the settings used def getSettings(self): return self.local_settings
class ChartConf(JDialog, ActionListener): def actionPerformed(self, event): option = event.getActionCommand() # print option if option == "Change": self.pingFun(self) elif option == "Exit": self.dispose() def getMarkerColor(self): return self.markerPanel.getBackground() def getPosColor(self): return self.posPanel.getBackground() def getNeuColor(self): return self.neuPanel.getBackground() def getBalColor(self): return self.balPanel.getBackground() def getSelLabel(self): return self.selLabel.isSelected() def getNeuLabel(self): return self.neuLabel.isSelected() def createColorPanel(self, color, pane): colorPanel = JPanel() colorPanel.setBackground(color) colorPanel.addMouseListener(MouseProcessor(self, colorPanel)) pane.add(colorPanel) return colorPanel def __init__(self, frame, chart, pingFun): JDialog(frame) self.setTitle("Chart Settings") self.setModal(True) self.pingFun = pingFun pane = self.getRootPane().getContentPane() pane.setLayout(GridLayout(7, 2)) pane.add(JLabel("Marker color")) self.markerPanel = self.createColorPanel(chart.markerColor, pane) pane.add(JLabel("Positive selection color")) self.posPanel = self.createColorPanel(chart.posColor, pane) pane.add(JLabel("Neutral color")) self.neuPanel = self.createColorPanel(chart.neuColor, pane) pane.add(JLabel("Balancing selection color ")) self.balPanel = self.createColorPanel(chart.balColor, pane) self.add(JLabel("Label candidate selected loci")) self.selLabel = JCheckBox() self.selLabel.setSelected(chart.labelSelected) self.add(self.selLabel) self.add(JLabel("Label candidate neutral loci")) self.neuLabel = JCheckBox() self.neuLabel.setSelected(chart.labelNeutral) self.add(self.neuLabel) change = JButton("Change") change.setActionCommand("Change") change.addActionListener(self) pane.add(change) exit = JButton("Exit") exit.setActionCommand("Exit") exit.addActionListener(self) pane.add(exit) self.pack()
class FEA_ConfigPanel(JPanel): numThreads = 8 generateXLS = True generateCSV = True doNSLookup = True doWBLookup = True cbNSLookup = None cbGenerateExcel = None cbGenerateCSV = None cbWayback = None def __init__(self): self.initComponents() # get previous settings selected by the user if (ModuleSettings.getConfigSetting("FEA", "doNSLookup") != None) and ( ModuleSettings.getConfigSetting("FEA", "doNSLookup") != ""): if ModuleSettings.getConfigSetting("FEA", "doNSLookup"): self.cbNSLookup.setSelected(True) self.doNSLookup = True else: self.cbNSLookup.setSelected(False) self.doNSLookup = False if (ModuleSettings.getConfigSetting("FEA", "generateCSV") != None) and (ModuleSettings.getConfigSetting( "FEA", "generateCSV") != ""): if ModuleSettings.getConfigSetting("FEA", "generateCSV"): self.cbGenerateCSV.setSelected(True) self.generateCSV = True else: self.cbGenerateCSV.setSelected(False) self.generateCSV = False if (ModuleSettings.getConfigSetting("FEA", "generateXLS") != None) and (ModuleSettings.getConfigSetting( "FEA", "generateXLS") != ""): if ModuleSettings.getConfigSetting("FEA", "generateXLS"): self.cbGenerateExcel.setSelected(True) self.generateXLS = True else: self.cbGenerateExcel.setSelected(False) self.generateXLS = False if (ModuleSettings.getConfigSetting("FEA", "numThreads") != None) and ( ModuleSettings.getConfigSetting("FEA", "numThreads") != ""): self.numThreads = ModuleSettings.getConfigSetting( "FEA", "numThreads") self.numberThreadsSlider.setValue(self.numThreads) else: self.numThreads = self.numberThreadsSlider.getValue() def addStatusLabel(self, msg): gbc = GridBagConstraints() gbc.anchor = GridBagConstraints.NORTHWEST gbc.gridx = 0 gbc.gridy = 7 lab = JLabel(msg) self.add(lab, gbc) def getDoNSLookup(self): return self.doNSLookup def getGenerateCSV(self): return self.generateCSV def getGenerateXLS(self): return self.generateXLS def getDoWBLookup(self): return self.doWBLookup def getNumThreads(self): return self.numThreads def initComponents(self): self.setLayout(GridBagLayout()) gbc = GridBagConstraints() gbc.anchor = GridBagConstraints.NORTHWEST gbc.gridx = 0 gbc.gridy = 0 descriptionLabel = JLabel("FEA - Forensics Email Analysis") self.add(descriptionLabel, gbc) gbc.gridy = 1 self.cbNSLookup = JCheckBox( "Perform DNS Lookup on email domains", actionPerformed=self.cbNSLookupActionPerformed) self.cbNSLookup.setSelected(True) self.add(self.cbNSLookup, gbc) # TODO: include option to browse for text file with list of emails to exclude from analysis numberThreadsLabel = JLabel( "Maximum number of threads for DNS Lookup task: ") gbc.gridy = 2 self.add(numberThreadsLabel, gbc) self.numberThreadsSlider = JSlider( JSlider.HORIZONTAL, 1, 16, 8, stateChanged=self.sliderActionPerformed) self.numberThreadsSlider.setMajorTickSpacing(1) self.numberThreadsSlider.setPaintLabels(True) self.numberThreadsSlider.setPaintTicks(True) self.numberThreadsSlider.setSnapToTicks(True) self.numberThreadsSlider.setToolTipText( "set maximum number of concurrent threads when performing DNS lookup on email domains" ) gbc.gridy = 5 gbc.gridwidth = 15 gbc.gridheight = 1 gbc.fill = GridBagConstraints.BOTH gbc.weightx = 0 gbc.weighty = 0 gbc.anchor = GridBagConstraints.NORTHWEST gbc.gridy = 3 self.add(self.numberThreadsSlider, gbc) self.cbGenerateExcel = JCheckBox( "Generate Excel format report (more detailed)", actionPerformed=self.cbGenerateExcelActionPerformed) self.cbGenerateExcel.setSelected(True) gbc.gridy = 4 self.add(self.cbGenerateExcel, gbc) self.cbGenerateCSV = JCheckBox( "Generate CSV format report (plaintext)", actionPerformed=self.cbGenerateCSVActionPerformed) self.cbGenerateCSV.setSelected(True) gbc.gridy = 5 self.add(self.cbGenerateCSV, gbc) gbc.gridy = 6 self.cbWayback = JCheckBox( "Perform Wayback Machine Lookup on email domains (WARNING: can be a slow process!)", actionPerformed=self.cbWaybackActionPerformed) self.cbWayback.setSelected(True) self.add(self.cbWayback, gbc) def cbWaybackActionPerformed(self, event): source = event.getSource() if (source.isSelected()): ModuleSettings.setConfigSetting("FEA", "doWBLookup", "true") self.doWBLookup = True else: ModuleSettings.setConfigSetting("FEA", "doNSLookup", "false") self.doWBLookup = False def cbNSLookupActionPerformed(self, event): source = event.getSource() if (source.isSelected()): ModuleSettings.setConfigSetting("FEA", "doNSLookup", "true") self.doNSLookup = True self.cbWayback.setEnabled(True) else: ModuleSettings.setConfigSetting("FEA", "doNSLookup", "false") self.doNSLookup = False self.cbWayback.setSelected(False) self.cbWayback.setEnabled(False) self.doWBLookup = False def cbGenerateExcelActionPerformed(self, event): source = event.getSource() if (source.isSelected()): ModuleSettings.setConfigSetting("FEA", "generateXLS", "true") self.generateXLS = True else: ModuleSettings.setConfigSetting("FEA", "generateXLS", "false") self.generateXLS = False def cbGenerateCSVActionPerformed(self, event): source = event.getSource() if (source.isSelected()): ModuleSettings.setConfigSetting("FEA", "generateCSV", "true") self.generateCSV = True else: ModuleSettings.setConfigSetting("FEA", "generateCSV", "false") self.generateCSV = False def sliderActionPerformed(self, event): source = event.getSource() self.numThreads = source.getValue() ModuleSettings.setConfigSetting("FEA", "numThreads", self.numThreads) self.addStatusLabel("number of threads set: " + str(self.numThreads))
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # When button to find file is clicked then open dialog to find the file and return it. def Find_Dir(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("All", ["*.*"]) chooseFile.addChoosableFileFilter(filter) #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setSetting('Volatility_Directory', Canonical_file) self.Program_Executable_TF.setText(Canonical_file) def keyPressed(self, event): self.local_settings.setProcessIDs(self.Process_Ids_To_Dump_TF.getText()) #self.Error_Message.setText(self.Process_Ids_To_Dump_TF.getText()) def checkBoxEvent(self, event): if self.Check_Box.isSelected(): self.local_settings.setSetting('Flag', 'true') else: self.local_settings.setSetting('Flag', 'False') # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout( self.gbPanel0 ) self.Error_Message = JLabel( "") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 15 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) self.panel0.add( self.Error_Message ) self.Label_1 = JLabel("Volatility Executable Directory") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) self.panel0.add( self.Label_1 ) self.Program_Executable_TF = JTextField(10) self.Program_Executable_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) self.panel0.add( self.Program_Executable_TF ) self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Dir) self.Find_Program_Exec_BTN.setEnabled(True) self.rbgPanel0.add( self.Find_Program_Exec_BTN ) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) self.panel0.add( self.Find_Program_Exec_BTN ) self.Blank_1 = JLabel( " ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) self.panel0.add( self.Blank_1 ) self.Blank_3 = JLabel( " ") self.Blank_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_3, self.gbcPanel0 ) self.panel0.add( self.Blank_3 ) self.Check_Box = JCheckBox("Extract and Create Memory Image from Hiberfile", actionPerformed=self.checkBoxEvent) self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Check_Box, self.gbcPanel0 ) self.panel0.add( self.Check_Box ) self.Blank_4 = JLabel( " ") self.Blank_4.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_4, self.gbcPanel0 ) self.panel0.add( self.Blank_4 ) self.Label_3 = JLabel( "Message:") self.Label_3.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) self.panel0.add( self.Label_3 ) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.Check_Box.setSelected(self.local_settings.getSetting('Flag') == 'true') self.Program_Executable_TF.setText(self.local_settings.getSetting('Volatility_Directory')) #pass # Return the settings used def getSettings(self): return self.local_settings
def defineCheckBox(self, caption, selected=True, enabled=True): checkBox = JCheckBox(caption) checkBox.setSelected(selected) checkBox.setEnabled(enabled) return checkBox
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 WorkHelper(JFrame): def __init__(self): super(WorkHelper, self).__init__() self.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() ############################################################# # Layout: layout = GroupLayout(self.getContentPane()) self.getContentPane().setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) ############################################################# ############################################################# # Frame Area: Larea1 = JLabel("InputArea:") Sarea1 = JScrollPane() self.area1 = JTextArea() self.area1.setToolTipText("Input Area") self.area1.setEditable(True) self.area1.setBorder(BorderFactory.createLineBorder(Color.gray)) Sarea1.setPreferredSize(Dimension(300,100)) Sarea1.getViewport().setView((self.area1)) bClear = JButton("Clear", actionPerformed=self.bClear) bClear.setToolTipText("Clears the text form both Input and Output text Areas") bCopyToInput = JButton("Copy to Input", actionPerformed=self.bCopyToInput) bCopyToInput.setToolTipText("Copy the text from the Output Area to the Input Area for further Operations") self.cCtClipB = JCheckBox("Auto-Copy"); self.cCtClipB.setToolTipText("When 'Checked' after the Categories are created they will added to the clipboard") self.cCtClipB.setSelected(1) Larea2 = JLabel("OutputArea:") Sarea2 = JScrollPane() self.area2 = JTextArea() self.area2.setToolTipText("Output Area") self.area2.setEditable(False) self.area2.setBorder(BorderFactory.createLineBorder(Color.gray)) Sarea2.setPreferredSize(Dimension(300,100)) Sarea2.getViewport().setView((self.area2)) ############################################################# # Tabbed Area: tabPane = JTabbedPane(JTabbedPane.TOP) self.getContentPane().add(tabPane) ##################################################### # Text Edit pane panel_TEdit = JPanel() layout2 = GroupLayout(panel_TEdit) layout2.setAutoCreateGaps(True) layout2.setAutoCreateContainerGaps(True) panel_TEdit.setLayout(layout2) bRemoveNBSP_L = JButton("Clean LText", actionPerformed=self.bRemoveNBSP_L) bRemoveNBSP_L.setToolTipText("Removes Spaces, Tabs from the start of every text line from the input Area") bRemoveNBSP_R = JButton("Clean RText", actionPerformed=self.bRemoveNBSP_R) bRemoveNBSP_R.setToolTipText("Removes Spaces, Tabs from the end of every text line from the input Area") self.ReplaceThis = JTextField() self.ReplaceThis = JTextField(maximumSize=Dimension(120,25)) self.ReplaceThis.setToolTipText("Text to be replaced") self.ReplaceThat = JTextField() self.ReplaceThat = JTextField(maximumSize=Dimension(120,25)) self.ReplaceThat.setToolTipText("Text to be placed") bSandReplace = JButton("Replace Text", actionPerformed=self.bSandReplace) bSandReplace.setToolTipText("Replace the text from This with Text from That in the Text from the Input Area and displays it in the Output Area") bRemNumbers = JButton("Rem Numbers", actionPerformed=self.RemNumbers) bRemNumbers.setToolTipText("Removes numbers from the start of every line") ##################################################### # Dimension pane panel_Dimensions = JPanel() layout3 = GroupLayout(panel_Dimensions) layout3.setAutoCreateGaps(True) layout3.setAutoCreateContainerGaps(True) panel_Dimensions.setLayout(layout3) self.cCurly = JCheckBox("Curly"); self.cCurly.setToolTipText("When 'Checked' Curly Brackets will surround the Categories") self.cCurly.setSelected(1) self.cSemiC = JCheckBox("SemiColumn"); self.cSemiC.setToolTipText("When 'Checked' after the Categories are created at the end will be a semicolomn") self.cSemiC.setSelected(1) self.iStart = JTextField(maximumSize=Dimension(40,25)) self.iStart.setToolTipText("The Start Index for the Making of the Categories") self.RThis = JTextField() self.RThis = JTextField(maximumSize=Dimension(120,25)) self.RThis.setToolTipText("The Starting Index used in creating the Categorical") self.RThat = JTextField() self.RThat = JTextField(maximumSize=Dimension(120,25)) self.RThat.setToolTipText("The Finish Index used in creating the Categorical") optioncCategories = JLabel("Options:") bcCat = JButton("CreatCateg", actionPerformed=self.bcCat) bcCat.setToolTipText("Create a categorical form starting C_Index to finish C_Index; Use the text boxes to define the indexes") bM_Categories = JButton("Categories", actionPerformed=self.mCategories) bM_Categories.setToolTipText("Make Categories using the lines from the Input Area. Use it to define Categorical questions.") ##################################################### # ConfirmIt pane panel_ConfirmIt = JPanel() layout4 = GroupLayout(panel_ConfirmIt) layout4.setAutoCreateGaps(True) layout4.setAutoCreateContainerGaps(True) panel_ConfirmIt.setLayout(layout4) self.PID = JTextField() self.PID = JTextField(maximumSize=Dimension(120,25)) self.PID.setToolTipText("The PID number used for creating links with PID and ids from every line of the Input Area") bClinks = JButton("Create Links", actionPerformed=self.bClinks) bClinks.setToolTipText("Create links for a project using PID and ID, ID`s are read from every line of the Input Area") bClinksNA = JButton("Create Links NA ", actionPerformed=self.bClinksNA) bClinksNA.setToolTipText("Create links for a project using PID and ID`s from the standard sample test for US") bClinksCA = JButton("Create Links CA", actionPerformed=self.bClinksCA) bClinksCA.setToolTipText("Create links for a project using PID and ID`s from the standard sample test for CA") self.Width = JTextField() self.Width = JTextField(maximumSize=Dimension(120,25)) self.Width.setToolTipText("The Width used in creating the DIV html tag, note the dimension used is in px") baddDIVt = JButton("Add DIV tag", actionPerformed=self.baddDIVt) baddDIVt.setToolTipText("Create a DIV tag for every line in the Input Area") ##################################################### # Statistics pane panel_Statistics = JPanel() layout5 = GroupLayout(panel_Statistics) layout5.setAutoCreateGaps(True) layout5.setAutoCreateContainerGaps(True) panel_Statistics.setLayout(layout5) ##################################################### # TimeTraking pane panel_TimeTraking = JPanel() layout6 = GroupLayout(panel_TimeTraking) layout6.setAutoCreateGaps(True) layout6.setAutoCreateContainerGaps(True) panel_TimeTraking.setLayout(layout6) ##################################################### # Tabbed Area Tabs tabPane.addTab("Text Edit", panel_TEdit) tabPane.addTab("Dimensions", panel_Dimensions) tabPane.addTab("ConfirmIt", panel_ConfirmIt) tabPane.addTab("Statistics", panel_Statistics) tabPane.addTab("TimeTraking", panel_TimeTraking) ############################################################# ############################################################# # Aplication Layouts: 2 groups one Horizontal and one Vertical ############################################################# # Frame Layout: 2 groups one Horizontal and one Vertical layout.setHorizontalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(Larea1) .addComponent(Sarea1) .addComponent(Sarea2) .addGroup(layout.createSequentialGroup() .addComponent(bCopyToInput) .addComponent(bClear) .addComponent(self.cCtClipB)) .addComponent(Larea2)) .addGroup(layout.createParallelGroup() .addComponent(tabPane)) ) layout.setVerticalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(Larea1) .addComponent(Sarea1) .addGroup(layout.createParallelGroup() .addComponent(bCopyToInput) .addComponent(bClear) .addComponent(self.cCtClipB) ) .addComponent(Larea2) .addComponent(Sarea2)) .addGroup(layout.createSequentialGroup() .addComponent(tabPane)) ) ) ############################################################# # TEdit Layout: 2 groups one Horizontal and one Vertical layout2.setHorizontalGroup(layout2.createSequentialGroup() .addGroup(layout2.createParallelGroup() .addGroup(layout2.createSequentialGroup() .addComponent(bRemNumbers) .addComponent(bRemoveNBSP_L) .addComponent(bRemoveNBSP_R)) .addGroup(layout2.createSequentialGroup() .addComponent(bSandReplace) .addComponent(self.ReplaceThis) .addComponent(self.ReplaceThat)) )) layout2.setVerticalGroup(layout2.createSequentialGroup() .addGroup(layout2.createParallelGroup() .addComponent(bRemNumbers) .addComponent(bRemoveNBSP_L) .addComponent(bRemoveNBSP_R)) .addGroup(layout2.createParallelGroup() .addComponent(bSandReplace) .addComponent(self.ReplaceThis) .addComponent(self.ReplaceThat)) ) ############################################################# # Dimensions Layout: 2 groups one Horizontal and one Vertical layout3.setHorizontalGroup(layout3.createSequentialGroup() .addGroup(layout3.createParallelGroup() .addGroup(layout3.createSequentialGroup() .addComponent(bM_Categories) .addComponent(self.iStart)) .addGroup(layout3.createSequentialGroup() .addComponent(optioncCategories) .addComponent(self.cCurly) .addComponent(self.cSemiC) ) .addGroup(layout3.createSequentialGroup() .addComponent(bcCat) .addComponent(self.RThis) .addComponent(self.RThat)) .addGroup(layout3.createSequentialGroup() ) ) ) layout3.setVerticalGroup(layout3.createSequentialGroup() .addGroup(layout3.createSequentialGroup() .addGroup(layout3.createParallelGroup() .addComponent(bM_Categories) .addComponent(self.iStart)) .addGroup(layout3.createParallelGroup() .addComponent(bcCat) .addComponent(self.RThis) .addComponent(self.RThat)) .addGroup(layout3.createParallelGroup() .addGroup(layout3.createParallelGroup() .addComponent(optioncCategories) .addComponent(self.cCurly) .addComponent(self.cSemiC) ) ) ) ) ############################################################# # ConfimIT Layout: 2 groups one Horizontal and one Vertical layout4.setHorizontalGroup(layout4.createSequentialGroup() .addGroup(layout4.createParallelGroup() .addGroup(layout4.createSequentialGroup() .addComponent(bClinks) .addComponent(self.PID) ) .addGroup(layout4.createSequentialGroup() .addComponent(bClinksNA) .addComponent(bClinksCA) ) .addGroup(layout4.createSequentialGroup() .addComponent(baddDIVt) .addComponent(self.Width) ) )) layout4.setVerticalGroup(layout4.createSequentialGroup() .addGroup(layout4.createSequentialGroup() .addGroup(layout4.createParallelGroup() .addComponent(bClinks) .addComponent(self.PID)) .addGroup(layout4.createParallelGroup() .addComponent(bClinksNA) .addComponent(bClinksCA) ) .addGroup(layout4.createParallelGroup() .addComponent(baddDIVt) .addComponent(self.Width) ) )) #layout2.linkSize(SwingConstants.HORIZONTAL, [self.cCurly,bM_Categories]) #layout.linkSize(SwingConstants.HORIZONTAL, [ok, bCopyToInput, close, bM_Categories]) #layout3.linkSize(SwingConstants.HORIZONTAL, [self.RThis,self.RThat,bRemoveNBSP_L,bRemoveNBSP_R,bM_Categories,bSandReplace,bcCat]) ############################################################# ############################################################# # Aplication Settings self.pack() #self.setPreferredSize(Dimension(1000, 1000)) self.setTitle("Workhelper") self.setSize(800, 500) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True) ############################################################# ############################################################# # WorkHelper class methods: def onQuit(self, e): "@sig public void setExpression(java.lang.String e)" os.system.exit(0) # def addToClipBoard(self, text): # "@sig public void setExpression(java.lang.String text)" # command = 'echo ' + text.strip() + '| clip' # os.system(command) # brute method for pasting into clipboard on windows def mCategories(self, e): "@sig public void setExpression(java.lang.String e)" """ Takes every line of text form the Input Area and by using a string composition it creates the output in the SPSS dimension categories format. """ try: StartIndex = int(self.iStart.getText()) except ValueError: StartIndex=1 text=self.area1.getText().rstrip() counter=StartIndex lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': textO=textO+("_"+str(counter)+' "'+text[lastindex:i]+'",\n') lastindex=i+1 counter=counter+1 if len(text[lastindex:len(text)])>0: textO=textO+("_"+str(counter)+' "'+text[lastindex:len(text)]+'"') if len(textO)>0: if self.cCurly.isSelected(): textO = "{\n"+ textO + "\n}" if self.cSemiC.isSelected(): textO = textO + ";" self.copyToClipboard(textO) self.area2.setText(textO) def copyToClipboard(self, text): if self.cCtClipB.isSelected(): stringSelection = StringSelection(text) self.clipboard.setContents(stringSelection, None) def bCopyToInput(self, e): "@sig public void setExpression(java.lang.String e)" """Copy the Text from the Output Area to the input Area for further operations""" self.area1.setText(self.area2.getText()) def bRemoveNBSP_L(self, e): "@sig public void setExpression(java.lang.String e)" text=self.area1.getText().rstrip() textO="" lastindex=0 for i in range(0,len(text)): if text[i] == '\n': textO = textO+text[lastindex:i].lstrip()+"\n" lastindex=i+1 #print(text[0:i].lstrip()+'\n') if len(text[lastindex:len(text)])>0: textO=textO+text[lastindex:len(text)].lstrip() self.area2.setText(textO) def bRemoveNBSP_R(self, e): "@sig public void setExpression(java.lang.String e)" text=self.area1.getText().rstrip() textO="" lastindex=0 for i in range(0,len(text)): if text[i] == '\n': textO = textO+text[lastindex:i].rstrip()+"\n" lastindex=i+1 #print(text[0:i].lstrip()+'\n') if len(text[lastindex:len(text)])>0: textO=textO+text[lastindex:len(text)].rstrip() self.area2.setText(textO) def bClear(self, e): "@sig public void setExpression(java.lang.String e)" self.area1.setText("") self.area2.setText("") def bcCat(self, e): "@sig public void setExpression(java.lang.String e)" try: StartIndex = int(self.RThis.getText()) except ValueError: StartIndex=1 try: FinishIndex = int(self.RThat.getText()) except ValueError: FinishIndex=1 cCats="" for i in range(StartIndex,FinishIndex+1): if i<>FinishIndex: cCats=cCats+"_"+str(i)+"," else: cCats=cCats+"_"+str(i) if StartIndex<FinishIndex: cCats="{"+cCats+"}" self.copyToClipboard(cCats) self.area2.setText(cCats) def bSandReplace(self, e): self.area2.setText(self.area1.getText().replace(self.ReplaceThis.getText(),self.ReplaceThat.getText())) self.copyToClipboard(self.area2.getText()) ############################################################# # Confirmit def bClinks(self, e): text=self.area1.getText().rstrip() lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': textO=textO+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+text[lastindex:i]+'\n' lastindex=i+1 if len(text[lastindex:len(text)])>0: textO=textO+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+text[lastindex:len(text)] self.copyToClipboard(textO) self.area2.setText(textO) def bClinksNA(self, e): output="" for i in range (1,201): if i<10: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'US9900'+str(i)+'\n' else: if i<100: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'US990'+str(i)+'\n' else: if i==200: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'US99'+str(i) else: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'US99'+str(i)+'\n' self.area2.setText(output) self.copyToClipboard(self.area2.getText()) def bClinksCA(self, e): output="" for i in range (1,201): if i<10: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'CA9900'+str(i)+'\n' else: if i<100: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'CA990'+str(i)+'\n' else: if i==200: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'CA99'+str(i) else: output=output+'http://surveys.ipsosinteractive.com/surveys2/?pid='+self.PID.getText()+'&id='+'CA99'+str(i)+'\n' self.area2.setText(output) self.copyToClipboard(self.area2.getText()) def baddDIVt(self, e): try: Width = int(self.Width.getText()) except ValueError: Width=1 text=self.area1.getText().rstrip() lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': textO=textO+'<div style="width:'+str(Width)+'px">'+text[lastindex:i]+'</div>'+'\n' lastindex=i+1 if len(text[lastindex:len(text)])>0: textO=textO+'<div style="width:'+str(Width)+'px">'+text[lastindex:len(text)]+'</div>' self.copyToClipboard(textO) self.area2.setText(textO) def RemNumbers(self, e): text=self.area1.getText().rstrip() lastindex=0 textO="" for i in range(0,len(text)): if text[i]=='\n': textO=textO+text[lastindex:i].lstrip('1234567890')+'\n' lastindex=i+1 if len(text[lastindex:len(text)])>0: textO=textO+text[lastindex:len(text)].lstrip('1234567890') self.copyToClipboard(textO) self.area2.setText(textO)
class BurpExtender(IBurpExtender, IScannerCheck, ITab): def __init__(self): self.ext_name = 'AWS Extender' self.callbacks = None self.gui_elements = None self.aws_access_key_inpt = None self.aws_secret_key_inpt = None self.aws_session_token_inpt = None self.gs_access_key_inpt = None self.gs_secret_key_inpt = None self.wordlist_path_inpt = None self.checkbox_inpt = None self.aws_access_key = '' self.aws_secret_key = '' self.aws_session_token = '' self.gs_access_key = '' self.gs_secret_key = '' self.wordlist_path = '' def registerExtenderCallbacks(self, callbacks): """Register extender callbacks.""" self.callbacks = callbacks # Set the name of the extension self.callbacks.setExtensionName(self.ext_name) # Register the extension as a scanner check self.callbacks.registerScannerCheck(self) # Build GUI elements self.gui_elements = self.build_gui() callbacks.customizeUiComponent(self.gui_elements) callbacks.addSuiteTab(self) self.check_loading_issues() self.reload_config() def show_errors(self, label): """Display error messages.""" top_label = JLabel(label, JLabel.CENTER) frame = JFrame(self.ext_name) frame.setSize(550, 300) frame.setLayout(GridLayout(1, 1)) frame.add(top_label) frame.setLocationRelativeTo(None) frame.setVisible(True) def check_loading_issues(self): """Check for any loading issues.""" missing_libs = [] tips = [] label = """<html> <body style='margin: 10px'> <b>The following dependencies could not be loaded successfully:</b><br> <ul><li>%s</li></ul><br> <b>Tips:</b><br> <ul><li>%s</li><br></ul> <b>For detailed information on how to load the plugin, see:</b><br> <ul> <li> <a href='#'>https://github.com/VirtueSecurity/aws-extender#getting-started</a> </li> </ul> </body> </html>""" if not RUN_TESTS: missing_libs.append('boto/boto3') tips.append( 'Make sure that the boto/boto3 library is installed properly, and\ the right path is specified in the "Folder for loading modules" setting.' ) try: CET.fromstring('<test></test>') except SAXException: # Try to workaround "http://bugs.jython.org/issue1127" try: def xml_parser(**_): class Parser(object): def feed(*_): raise XMLParseError def close(*_): return None return Parser() CET.XMLParser = xml_parser except TypeError: missing_libs.append('SAXParser') tips.append("""Run Burp Suite using the following command: <br><code style='background: #f7f7f9; color: red'>$ java -classpath xercesImpl.jar;burpsuite_pro.jar burp.StartBurp</code>""") if not missing_libs: return label %= ('</li><li>'.join(missing_libs), '</li><li>'.join(tips)) self.show_errors(label) def build_gui(self): """Construct GUI elements.""" panel = JPanel(BorderLayout(3, 3)) panel.setBorder(EmptyBorder(160, 160, 160, 160)) self.aws_access_key_inpt = JTextField(10) self.aws_secret_key_inpt = JTextField(10) self.aws_session_token_inpt = JTextField(10) self.gs_access_key_inpt = JTextField(10) self.gs_secret_key_inpt = JTextField(10) self.wordlist_path_inpt = JTextField(10) self.checkbox_inpt = JCheckBox('Enabled') save_btn = JButton('Save', actionPerformed=self.save_config) labels = JPanel(GridLayout(0, 1)) inputs = JPanel(GridLayout(0, 1)) panel.add(labels, BorderLayout.WEST) panel.add(inputs, BorderLayout.CENTER) top_label = JLabel('<html><b>Settings</b><br><br></html>') top_label.setHorizontalAlignment(JLabel.CENTER) panel.add(top_label, BorderLayout.NORTH) labels.add(JLabel('AWS Access Key:')) inputs.add(self.aws_access_key_inpt) labels.add(JLabel('AWS Secret Key:')) inputs.add(self.aws_secret_key_inpt) labels.add(JLabel('AWS Session Key (optional):')) inputs.add(self.aws_session_token_inpt) labels.add(JLabel('GS Access Key:')) inputs.add(self.gs_access_key_inpt) labels.add(JLabel('GS Secret Key:')) inputs.add(self.gs_secret_key_inpt) labels.add(JLabel('Wordlist Filepath (optional):')) inputs.add(self.wordlist_path_inpt) labels.add(JLabel('Passive Mode:')) inputs.add(self.checkbox_inpt) panel.add(save_btn, BorderLayout.SOUTH) return panel def save_config(self, _): """Save settings.""" error_message = '' wordlist_path = self.wordlist_path_inpt.getText() save_setting = self.callbacks.saveExtensionSetting save_setting('aws_access_key', self.aws_access_key_inpt.getText()) save_setting('aws_secret_key', self.aws_secret_key_inpt.getText()) save_setting('aws_session_token', self.aws_session_token_inpt.getText()) save_setting('gs_access_key', self.gs_access_key_inpt.getText()) save_setting('gs_secret_key', self.gs_secret_key_inpt.getText()) save_setting('wordlist_path', wordlist_path) if self.checkbox_inpt.isSelected(): save_setting('passive_mode', 'True') else: save_setting('passive_mode', '') if wordlist_path and not os.path.isfile(wordlist_path): error_message = 'Error: Invalid filepath for the "Wordlist Filepath" setting.' self.show_errors(error_message) self.reload_config() def reload_config(self): """Reload saved settings.""" global RUN_TESTS load_setting = self.callbacks.loadExtensionSetting aws_access_key_val = load_setting('aws_access_key') or '' aws_secret_key_val = load_setting('aws_secret_key') or '' aws_session_token_val = load_setting('aws_session_token') or '' gs_access_key_val = load_setting('gs_access_key') or '' gs_secret_key_val = load_setting('gs_secret_key') or '' wordlist_path_val = load_setting('wordlist_path') or '' checkbox_inpt_val = load_setting('passive_mode') checkbox_inpt_val = bool( str(checkbox_inpt_val)) if checkbox_inpt_val else False if checkbox_inpt_val: RUN_TESTS = False else: RUN_TESTS = True self.aws_access_key = aws_access_key_val self.aws_secret_key = aws_secret_key_val self.aws_session_token = aws_session_token_val self.gs_access_key = gs_access_key_val self.gs_secret_key = gs_secret_key_val self.wordlist_path = wordlist_path_val self.aws_access_key_inpt.setText(aws_access_key_val) self.aws_secret_key_inpt.setText(aws_secret_key_val) self.aws_session_token_inpt.setText(aws_session_token_val) self.gs_access_key_inpt.setText(gs_access_key_val) self.gs_secret_key_inpt.setText(gs_secret_key_val) self.wordlist_path_inpt.setText(wordlist_path_val) self.checkbox_inpt.setSelected(checkbox_inpt_val) def getTabCaption(self): """Return tab caption.""" return self.ext_name def getUiComponent(self): """Return GUI elements.""" return self.gui_elements def doPassiveScan(self, request_response): """Perform a passive scan.""" scan_issues = [] opts = { 'aws_access_key': self.aws_access_key, 'aws_secret_key': self.aws_secret_key, 'aws_session_token': self.aws_session_token, 'gs_access_key': self.gs_access_key, 'gs_secret_key': self.gs_secret_key, 'wordlist_path': self.wordlist_path } bucket_scan = BucketScan(request_response, self.callbacks, opts) bucket_issues = bucket_scan.check_buckets() cognito_scan = CognitoScan(request_response, self.callbacks) cognito_issues = cognito_scan.identify_identity_pools() scan_issues = bucket_issues + cognito_issues if len(scan_issues) > 0: return scan_issues return None @staticmethod def doActiveScan(*_): pass @staticmethod def consolidateDuplicateIssues(existing_issue, new_issue): """Eliminate duplicate issues.""" if existing_issue.getIssueDetail() == new_issue.getIssueDetail(): return -1 else: return 0
class GUI_Test_SQLSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # Check the checkboxs to see what actions need to be taken def checkBoxEvent(self, event): if self.Exec_Program_CB.isSelected(): self.local_settings.setSetting('Exec_Prog_Flag', 'true') self.Program_Executable_TF.setEnabled(True) self.Find_Program_Exec_BTN.setEnabled(True) else: self.local_settings.setSetting('Exec_Prog_Flag', 'false') self.Program_Executable_TF.setText("") self.Program_Executable_TF.setEnabled(False) self.Find_Program_Exec_BTN.setEnabled(False) # Check to see if there are any entries that need to be populated from the database. def check_Database_entries(self): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = os.path.join(head, "GUI_Settings.db3") try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings DB!") try: stmt = dbConn.createStatement() SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' resultSet = stmt.executeQuery(SQL_Statement) while resultSet.next(): if resultSet.getString("Setting_Name") == "Program_Exec_Name": self.Program_Executable_TF.setText(resultSet.getString("Setting_Value")) self.local_settings.setSetting('ExecFile', resultSet.getString("Setting_Value")) self.local_settings.setSetting('Exec_Prog_Flag', 'true') self.Exec_Program_CB.setSelected(True) self.Program_Executable_TF.setEnabled(True) self.Find_Program_Exec_BTN.setEnabled(True) self.Error_Message.setText("Settings Read successfully!") except SQLException as e: self.Error_Message.setText("Error Reading Settings Database") stmt.close() dbConn.close() # Save entries from the GUI to the database. def SaveSettings(self, e): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = os.path.join(head, "GUI_Settings.db3") try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings") try: stmt = dbConn.createStatement() SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' + \ self.Program_Executable_TF.getText() + '");' resultSet = stmt.executeQuery(SQL_Statement) self.Error_Message.setText("Settings Saved") except SQLException as e: self.Error_Message.setText("Error Inserting Settings " + str(e)) stmt.close() dbConn.close() # When button to find file is clicked then open dialog to find the file and return it. def onClick(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("SQLite", ["sqlite"]) chooseFile.addChoosableFileFilter(filter) ret = chooseFile.showDialog(self.panel0, "Select SQLite") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setSetting('ExecFile', Canonical_file) self.Program_Executable_TF.setText(Canonical_file) # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout( self.gbPanel0 ) self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Exec_Program_CB, self.gbcPanel0 ) self.panel0.add( self.Exec_Program_CB ) self.Program_Executable_TF = JTextField(20) self.Program_Executable_TF.setEnabled(False) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) self.panel0.add( self.Program_Executable_TF ) self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick) self.Find_Program_Exec_BTN.setEnabled(False) self.rbgPanel0.add( self.Find_Program_Exec_BTN ) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) self.panel0.add( self.Find_Program_Exec_BTN ) self.Blank_1 = JLabel( " ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) self.panel0.add( self.Blank_1 ) self.Save_Settings_BTN = JButton( "Save Settings", actionPerformed=self.SaveSettings) self.Save_Settings_BTN.setEnabled(True) self.rbgPanel0.add( self.Save_Settings_BTN ) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Save_Settings_BTN, self.gbcPanel0 ) self.panel0.add( self.Save_Settings_BTN ) self.Blank_2 = JLabel( " ") self.Blank_2.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_2, self.gbcPanel0 ) self.panel0.add( self.Blank_2 ) self.Label_1 = JLabel( "Error Message:") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) self.panel0.add( self.Label_1 ) self.Error_Message = JLabel( "") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) self.panel0.add( self.Error_Message ) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.Exec_Program_CB.setSelected(self.local_settings.getSetting('Exec_Prog_Flag') == 'true') self.check_Database_entries() # Return the settings used def getSettings(self): return self.local_settings
class Parse_SRUDBWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setFlag(True) else: self.local_settings.setFlag(False) if self.checkbox1.isSelected(): self.local_settings.setFlag1(True) else: self.local_settings.setFlag1(False) if self.checkbox2.isSelected(): self.local_settings.setFlag2(True) else: self.local_settings.setFlag2(False) if self.checkbox3.isSelected(): self.local_settings.setFlag3(True) else: self.local_settings.setFlag3(False) if self.checkbox4.isSelected(): self.local_settings.setFlag4(True) else: self.local_settings.setFlag4(False) if self.checkbox5.isSelected(): self.local_settings.setFlag5(True) else: self.local_settings.setFlag5(False) if self.checkbox5.isSelected(): self.local_settings.setFlag5(True) else: self.local_settings.setFlag5(False) def keyPressed(self, event): self.local_settings.setArea(self.area.getText()) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("All Logs", actionPerformed=self.checkBoxEvent) self.checkbox1 = JCheckBox("Application Resource Usage", actionPerformed=self.checkBoxEvent) self.checkbox2 = JCheckBox("Energy Estimation Provider", actionPerformed=self.checkBoxEvent) self.checkbox3 = JCheckBox("Energy Usage Data", actionPerformed=self.checkBoxEvent) self.checkbox4 = JCheckBox("Network Connectivity", actionPerformed=self.checkBoxEvent) self.checkbox5 = JCheckBox("Network Usage", actionPerformed=self.checkBoxEvent) self.checkbox6 = JCheckBox("Windows Push Notification", actionPerformed=self.checkBoxEvent) self.panel1.add(self.checkbox) self.panel1.add(self.checkbox1) self.panel1.add(self.checkbox2) self.panel1.add(self.checkbox3) self.panel1.add(self.checkbox4) self.panel1.add(self.checkbox5) self.panel1.add(self.checkbox6) self.add(self.panel1) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getFlag()) self.checkbox1.setSelected(self.local_settings.getFlag1()) self.checkbox2.setSelected(self.local_settings.getFlag2()) self.checkbox3.setSelected(self.local_settings.getFlag3()) self.checkbox4.setSelected(self.local_settings.getFlag4()) self.checkbox5.setSelected(self.local_settings.getFlag4()) self.checkbox6.setSelected(self.local_settings.getFlag4()) # Return the settings used def getSettings(self): return self.local_settings
class GUI_PSQLiteUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('Flag', 'true') self.local_settings.setSetting('plists', self.area.getText()); else: self.local_settings.setSetting('Flag', 'false') # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Check to activate/deactivate TextArea", actionPerformed=self.checkBoxEvent) self.label0 = JLabel(" ") self.label1 = JLabel("Input in SQLite DB's in area below,") self.label2 = JLabel("seperate values by commas.") self.label3 = JLabel("then check the box above.") self.label4 = JLabel(" ") self.panel1.add(self.checkbox) self.panel1.add(self.label0) self.panel1.add(self.label1) self.panel1.add(self.label2) self.panel1.add(self.label3) self.panel1.add(self.label4) self.add(self.panel1) self.area = JTextArea(5,25) #self.area.getDocument().addDocumentListener(self.area) #self.area.addKeyListener(listener) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self.area) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getSetting('Flag') == 'true') self.area.setText(self.local_settings.getSetting('plists')) # Return the settings used def getSettings(self): return self.local_settings
class AmcacheScanWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # Check the checkboxs to see what actions need to be taken def checkBoxEvent(self, event): if self.Private_API_Key_CB.isSelected(): self.local_settings.setPrivate(True) self.local_settings.setAPI_Key(self.API_Key_TF.getText()) else: self.local_settings.setPrivate(False) self.local_settings.setAPI_Key(self.API_Key_TF.getText()) # Check to see if there are any entries that need to be populated from the database. def check_Database_entries(self): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = head + "\\GUI_Settings.db3" try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings DB!") try: stmt = dbConn.createStatement() SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' resultSet = stmt.executeQuery(SQL_Statement) while resultSet.next(): if resultSet.getString("Setting_Name") == "API_Key": self.local_settings.setAPI_Key(resultSet.getString("Setting_Value")) self.API_Key_TF.setText(resultSet.getString("Setting_Value")) if resultSet.getString("Setting_Name") == "Private": private = resultSet.getString("Setting_Value") if private == "1": self.local_settings.setPrivate(True) else: self.local_settings.setPrivate(False) self.Error_Message.setText("Settings Read successfully!") except SQLException as e: self.Error_Message.setText("Error Reading Settings Database") stmt.close() dbConn.close() # Save entries from the GUI to the database. def SaveSettings(self, e): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = head + "\\GUI_Settings.db3" try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings") try: stmt = dbConn.createStatement() SQL_Statement = 'UPDATE settings SET Setting_Value = "' + self.API_Key_TF.getText() + '" WHERE Setting_Name = "API_Key";' resultSet = stmt.executeQuery(SQL_Statement) except: pass try: if self.local_settings.getPrivate(): SQL_Statement = 'UPDATE settings SET Setting_Value = "1" WHERE Setting_Name = "Private";' resultSet = stmt.executeQuery(SQL_Statement) else: SQL_Statement = 'UPDATE settings SET Setting_Value = "0" WHERE Setting_Name = "Private";' resultSet = stmt.executeQuery(SQL_Statement) except: pass self.Error_Message.setText("Settings Saved") stmt.close() dbConn.close() # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout( self.gbPanel0 ) self.LabelA = JLabel("VirusTotal API Key:") self.LabelA.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.LabelA, self.gbcPanel0 ) self.panel0.add( self.LabelA ) self.API_Key_TF = JTextField(20) self.API_Key_TF.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.API_Key_TF, self.gbcPanel0 ) self.panel0.add( self.API_Key_TF ) self.Blank_1 = JLabel( " ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 6 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) self.panel0.add( self.Blank_1 ) self.Private_API_Key_CB = JCheckBox("Private API Key?", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Private_API_Key_CB, self.gbcPanel0 ) self.panel0.add( self.Private_API_Key_CB ) self.Save_Settings_BTN = JButton( "Save Settings", actionPerformed=self.SaveSettings) self.Save_Settings_BTN.setEnabled(True) self.rbgPanel0.add( self.Save_Settings_BTN ) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 8 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Save_Settings_BTN, self.gbcPanel0 ) self.panel0.add( self.Save_Settings_BTN ) self.Label_1 = JLabel( "Error Message:") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) self.panel0.add( self.Label_1 ) self.Error_Message = JLabel( "") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) self.panel0.add( self.Error_Message ) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.check_Database_entries() self.Private_API_Key_CB.setSelected(self.local_settings.getPrivate()) # Return the settings used def getSettings(self): return self.local_settings
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 Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('All', 'true') else: self.local_settings.setSetting('All', 'false') if self.checkbox4.isSelected(): self.local_settings.setSetting('Other', 'true') self.local_settings.setSetting('Eventids', self.area.getText()) # self.local_settings.setFlag(False) # self.checkbox.setSelected(self.local_settings.getFlag()) else: self.local_settings.setSetting('Other', 'false') def keyPressed(self, event): self.local_settings.setArea('Eventids', self.area.getText()) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Create Content View of Unique Event Id's", actionPerformed=self.checkBoxEvent) self.checkbox4 = JCheckBox( "Other - Input in text area below then check this box", actionPerformed=self.checkBoxEvent) self.text1 = JLabel( "*** Only run this once otherwise it adds it to the data again.") self.text2 = JLabel(" ") self.text3 = JLabel( "*** Format is a comma delimited text ie: 8001, 8002") self.panel1.add(self.checkbox) self.panel1.add(self.text1) self.panel1.add(self.text2) self.panel1.add(self.checkbox4) self.panel1.add(self.text3) self.add(self.panel1) self.area = JTextArea(5, 25) #self.area.addKeyListener(self) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected( self.local_settings.getSetting('All') == 'true') self.checkbox4.setSelected( self.local_settings.getSetting('Other') == 'true') self.area.setText(self.local_settings.getSetting('Eventids')) # Return the settings used def getSettings(self): return self.local_settings
class GUI_TestWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.Exec_Program_CB.isSelected(): self.local_settings.setSetting('Exec_Prog_Flag', 'true') self.Program_Executable_TF.setEnabled(True) self.Find_Program_Exec_BTN.setEnabled(True) else: self.local_settings.setSetting('Exec_Prog_Flag', 'false') self.Program_Executable_TF.setText("") self.Program_Executable_TF.setEnabled(False) self.Find_Program_Exec_BTN.setEnabled(False) if self.Imp_File_CB.isSelected(): self.local_settings.setSetting('Imp_File_Flag', 'true') self.File_Imp_TF.setEnabled(True) self.Find_Imp_File_BTN.setEnabled(True) else: self.local_settings.setSetting('Imp_File_Flag', 'false') self.File_Imp_TF.setText("") self.local_settings.setSetting('File_Imp_TF', "") self.File_Imp_TF.setEnabled(False) self.Find_Imp_File_BTN.setEnabled(False) def keyPressed(self, event): self.local_settings.setSetting('Area', self.area.getText()) def onchange_cb(self, event): self.local_settings.setSetting('ComboBox', event.item) #self.Error_Message.setText(event.item) def onchange_lb(self, event): self.local_settings.setSetting('ListBox', "") list_selected = self.List_Box_LB.getSelectedValuesList() self.local_settings.setSetting('ListBox', str(list_selected)) # if (len(list_selected) > 0): # self.Error_Message.setText(str(list_selected)) # else: # self.Error_Message.setText("") def onClick(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("SQLite", ["sqlite"]) chooseFile.addChoosableFileFilter(filter) ret = chooseFile.showDialog(self.panel0, "Select SQLite") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) if self.File_Imp_TF.isEnabled(): self.File_Imp_TF.setText(Canonical_file) self.local_settings.setSetting('File_Imp_TF', Canonical_file) else: self.local_settings.setSetting('ExecFile', Canonical_file) self.Program_Executable_TF.setText(Canonical_file) # TODO: Update this for your UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout( self.gbPanel0 ) self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Exec_Program_CB, self.gbcPanel0 ) self.panel0.add( self.Exec_Program_CB ) self.Program_Executable_TF = JTextField(20) self.Program_Executable_TF.setEnabled(False) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) self.panel0.add( self.Program_Executable_TF ) self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick) self.Find_Program_Exec_BTN.setEnabled(False) self.rbgPanel0.add( self.Find_Program_Exec_BTN ) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) self.panel0.add( self.Find_Program_Exec_BTN ) self.Imp_File_CB = JCheckBox( "Import File", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Imp_File_CB, self.gbcPanel0 ) self.panel0.add( self.Imp_File_CB ) self.File_Imp_TF = JTextField(20) self.File_Imp_TF.setEnabled(False) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.File_Imp_TF, self.gbcPanel0 ) self.panel0.add( self.File_Imp_TF ) self.Find_Imp_File_BTN = JButton( "Find File", actionPerformed=self.onClick) self.Find_Imp_File_BTN.setEnabled(False) self.rbgPanel0.add( self.Find_Imp_File_BTN ) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Find_Imp_File_BTN, self.gbcPanel0 ) self.panel0.add( self.Find_Imp_File_BTN ) self.Check_Box_CB = JCheckBox( "Check Box 1", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Check_Box_CB, self.gbcPanel0 ) self.panel0.add( self.Check_Box_CB ) self.dataComboBox_CB = ("Chocolate", "Ice Cream", "Apple Pie") self.ComboBox_CB = JComboBox( self.dataComboBox_CB) self.ComboBox_CB.itemStateChanged = self.onchange_cb self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.ComboBox_CB, self.gbcPanel0 ) self.panel0.add( self.ComboBox_CB ) self.dataList_Box_LB = ("Chocolate", "Ice Cream", "Apple Pie", "Pudding", "Candy" ) self.List_Box_LB = JList( self.dataList_Box_LB, valueChanged=self.onchange_lb) #self.List_Box_LB.itemStateChanged = self.onchange_lb self.List_Box_LB.setVisibleRowCount( 3 ) self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 15 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 1 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) self.panel0.add( self.scpList_Box_LB ) # self.Radio_Button_RB = JRadioButton( "Radio Button" ) # self.rbgPanel0.add( self.Radio_Button_RB ) # self.gbcPanel0.gridx = 7 # self.gbcPanel0.gridy = 17 # self.gbcPanel0.gridwidth = 1 # self.gbcPanel0.gridheight = 1 # self.gbcPanel0.fill = GridBagConstraints.BOTH # self.gbcPanel0.weightx = 1 # self.gbcPanel0.weighty = 0 # self.gbcPanel0.anchor = GridBagConstraints.NORTH # self.gbPanel0.setConstraints( self.Radio_Button_RB, self.gbcPanel0 ) # self.panel0.add( self.Radio_Button_RB ) # self.Label_1 = JLabel( "Error Message:") # self.Label_1.setEnabled(True) # self.gbcPanel0.gridx = 2 # self.gbcPanel0.gridy = 19 # self.gbcPanel0.gridwidth = 1 # self.gbcPanel0.gridheight = 1 # self.gbcPanel0.fill = GridBagConstraints.BOTH # self.gbcPanel0.weightx = 1 # self.gbcPanel0.weighty = 0 # self.gbcPanel0.anchor = GridBagConstraints.NORTH # self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) # self.panel0.add( self.Label_1 ) # self.Error_Message = JLabel( "") # self.Error_Message.setEnabled(True) # self.gbcPanel0.gridx = 6 # self.gbcPanel0.gridy = 19 # self.gbcPanel0.gridwidth = 1 # self.gbcPanel0.gridheight = 1 # self.gbcPanel0.fill = GridBagConstraints.BOTH # self.gbcPanel0.weightx = 1 # self.gbcPanel0.weighty = 0 # self.gbcPanel0.anchor = GridBagConstraints.NORTH # self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) # self.panel0.add( self.Error_Message ) self.add(self.panel0) # TODO: Update this for your UI def customizeComponents(self): self.Exec_Program_CB.setSelected(self.local_settings.getSetting('Exec_Prog_Flag') == 'true') self.Imp_File_CB.setSelected(self.local_settings.getSetting('Imp_File_Flag') == 'true') self.Check_Box_CB.setSelected(self.local_settings.getSetting('Check_Box_1') == 'true') # Return the settings used def getSettings(self): return self.local_settings
class CustomCellEditor(TreeCellEditor, ActionListener): """Renders the various tree edit controls (checkbox, tristate checkbox, text box etc.)""" def __init__(self, tree): TreeCellEditor.__init__(self) self.editor = None self.tree = tree flowLayout = FlowLayout(FlowLayout.LEFT, 0, 0) self.cbPanel = JPanel(flowLayout) self.cb = JCheckBox(actionPerformed=self.checked) self.cbPanel.add(self.cb) self.cbLabel = JLabel() self.cbPanel.add(self.cbLabel) self.tcbPanel = JPanel(flowLayout) self.tcb = TristateCheckBox(self.checked) self.tcbPanel.add(self.tcb) self.tcbLabel = JLabel() self.tcbPanel.add(self.tcbLabel) self.rbPanel = JPanel(flowLayout) self.rb = JRadioButton(actionPerformed=self.checked) self.rbPanel.add(self.rb) self.rbLabel = JLabel() self.rbPanel.add(self.rbLabel) self.tfPanel = JPanel(flowLayout) self.tfLabel = JLabel() self.tfPanel.add(self.tfLabel) self.tf = JTextField() self.tf.setColumns(12) self.tf.addActionListener(self) self.tfPanel.add(self.tf) def addCellEditorListener(self, l): """Register for edit events""" self.listener = l def isCellEditable(self, event): if event != None and isinstance( event.getSource(), JTree) and isinstance(event, MouseEvent): tree = event.getSource() path = tree.getPathForLocation(event.getX(), event.getY()) userData = path.getLastPathComponent().getUserObject() if isinstance(userData, TreeNodeData) and (not userData.getNodeType().isType( [NodeType._comment, NodeType._menu ])) and (userData.getVisible() > 0): return True return False def shouldSelectCell(self, event): # log.info("shouldSelectCell") return True def cancelCellEditing(self): # log.info("Cancel editing, please!") # super(CustomCellEditor, self).cancelCellEditing() pass def stopCellEditing(self): # log.info("stopCellEditing") if self.nodeData.getNodeType().isType([NodeType._text]): # log.info("stopCellEditing for sure!") self.nodeData.setValue(str(self.tf.getText())) return True def getTreeCellEditorComponent(self, tree, value, selected, expanded, leaf, row): """Return a swing edit control appropriate for the node type of the supplied value""" self.nodeData = self.getNodeUserData(value) if self.nodeData: text = self.nodeData.getText() t = self.nodeData.getNodeType() # Boolean checkbox if t.isType([NodeType._bool]): self.editor = self.cbPanel self.cbLabel.setText(text) if self.nodeData.getTriValue() > 0: self.cb.setSelected(True) else: self.cb.setSelected(False) # Tristate checkbox elif t.isType([NodeType._tri]): # log.info("getTreeCellEditorComponent tristate") self.editor = self.tcbPanel self.tcbLabel.setText(text) self.tcb.setTriState(self.nodeData.getTriValue()) # Radio button elif t.isType([NodeType._radio]): self.editor = self.rbPanel self.rbLabel.setText(text) if self.nodeData.getTriValue() > 0: self.rb.setSelected(True) else: self.rb.setSelected(False) # Text field elif t.isType([NodeType._text]): self.editor = self.tfPanel self.tfLabel.setText(str(self.nodeData.getText()) + ":") self.tf.setText(str(self.nodeData.getValue())) else: self.editor = self.tcb self.editor.setText(text) return self.editor def getNodeUserData(self, value): """Gets the TreeNodeData from the tree node""" if isinstance(value, DefaultMutableTreeNode): nodeData = value.getUserObject() if isinstance(nodeData, TreeNodeData): return nodeData return None def getCellEditorValue(self): newNode = TreeNodeData(self.nodeData.knode, self.tree) if isinstance(self.editor, JTextField): newNode.setValue(str(self.editor.getText())) return newNode def checked(self, e): """Updates the node data when a checkbox has been clicked""" control = e.getSource() if isinstance(control, TristateCheckBox): # log.info("tristate checked") self.nodeData.setTriValue(control.getTriState()) else: # log.info("checkbox checked") if control.isSelected(): self.nodeData.setValue(2) else: self.nodeData.setValue(0) def actionPerformed(self, event): """ ENTER pressed in text field, stop editing.""" tf = event.getSource() self.listener.editingStopped(ChangeEvent(tf))
class BurpExtender(IBurpExtender, ISessionHandlingAction, IExtensionStateListener, IHttpListener, ITab): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.helpers self.checkboxEnable = JCheckBox('Enabled') self.checkboxEnable.setSelected(False) self.checkboxEnable.setEnabled(True) self.scriptpane = JTextPane() self.scriptpane.setFont(Font('Monospaced', Font.PLAIN, 11)) self.scrollpane = JScrollPane() self.scrollpane.setViewportView(self.scriptpane) self.tab = JPanel() layout = GroupLayout(self.tab) self.tab.setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) layout.setHorizontalGroup(layout.createParallelGroup().addComponent( self.checkboxEnable).addComponent(self.scrollpane)) layout.setVerticalGroup(layout.createSequentialGroup().addComponent( self.checkboxEnable).addComponent(self.scrollpane)) self._code = compile('', '<string>', 'exec') self._script = '' script = callbacks.loadExtensionSetting('script') if script: script = base64.b64decode(script) self.scriptpane.document.insertString( self.scriptpane.document.length, script, SimpleAttributeSet()) self._script = script try: self._code = compile(script, '<string>', 'exec') except Exception as e: traceback.print_exc(file=self.callbacks.getStderr()) callbacks.setExtensionName("Python Scripter (modified)") callbacks.registerSessionHandlingAction(self) callbacks.registerExtensionStateListener(self) callbacks.registerHttpListener(self) callbacks.customizeUiComponent(self.getUiComponent()) callbacks.addSuiteTab(self) self.scriptpane.requestFocus() return def getActionName(self): return 'Send to Python Scripter' def extensionUnloaded(self): try: self.callbacks.saveExtensionSetting('script', base64.b64encode(self._script)) except Exception: traceback.print_exc(file=self.callbacks.getStderr()) return def performAction(self, currentRequest, macroItems): self.processHttpMessage(self.callbacks.TOOL_MACRO, 1, currentRequest, macroItems) return def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo, macroItems=[]): if not self.checkboxEnable.isSelected(): return try: globals_ = {} locals_ = { 'extender': self, 'callbacks': self.callbacks, 'helpers': self.helpers, 'toolFlag': toolFlag, 'messageIsRequest': messageIsRequest, 'messageInfo': messageInfo, 'macroItems': macroItems } exec(self.script, globals_, locals_) except Exception: traceback.print_exc(file=self.callbacks.getStderr()) return def getTabCaption(self): return 'Script' def getUiComponent(self): return self.tab @property def script(self): end = self.scriptpane.document.length _script = self.scriptpane.document.getText(0, end) if _script == self._script: return self._code self._script = _script self._code = compile(_script, '<string>', 'exec') return self._code
def addDeviceCheckbox(device, ap, visible=False): checkbox = JCheckBox(device, actionPerformed=ap) checkbox.setActionCommand(device) checkbox.setSelected(True) checkbox.setVisible(visible) return checkbox
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # smart xss feature (print conclusion and observation) # mark resulsts # add automatic check pages in the same domain self.tagPayloads = [ "<b>test", "<b onmouseover=test()>test", "<img src=err onerror=test()>", "<script>test</script>" "", "<scr ipt>test</scr ipt>", "<SCRIPT>test;</SCRIPT>", "<scri<script>pt>test;</scr</script>ipt>", "<SCRI<script>PT>test;</SCR</script>IPT>", "<scri<scr<script>ipt>pt>test;</scr</sc</script>ript>ipt>", "<IMG \"\"\"><SCRIPT>test</SCRIPT>\">", "<IMG '''><SCRIPT>test</SCRIPT>'>", "<SCR%00IPT>test</SCR%00IPT>", "<IFRAME SRC='f' onerror=\"test\"></IFRAME>", "<IFRAME SRC='f' onerror='test'></IFRAME>", "<<SCRIPT>test//<</SCRIPT>", "<img src=\"1\" onerror=\"test\">", "<img src='1' onerror='test'", "<STYLE TYPE=\"text/javascript\">test;</STYLE>", "<<SCRIPT>test//<</SCRIPT>" ] self.attributePayloads = [ "\"\"\"><SCRIPT>test", "'''><SCRIPT>test'", "\"><script>test</script>", "\"><script>test</script><\"", "'><script>test</script>", "'><script>test</script><'", "\";test;\"", "';test;'", ";test;", "\";test;//", "\"onmouseover=test ", "onerror=\"test\"", "onerror='test'", "onload=\"test\"", "onload='test'" ] self.xssKey = 'xssme' # 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("XSSor") self.affectedResponses = ArrayList() self._log = ArrayList() self._lock = Lock() # main split pane self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) # table of log entries logTable = Table(self) scrollPane = JScrollPane(logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) clearAPListBtn = JButton("Clear List", actionPerformed=self.clearAPList) clearAPListBtn.setBounds(10, 85, 120, 30) apListLabel = JLabel('Affected Pages List:') apListLabel.setBounds(10, 10, 140, 30) self.affectedModel = DefaultListModel() self.affectedList = JList(self.affectedModel) self.affectedList.addListSelectionListener(listSelectedChange(self)) scrollAList = JScrollPane(self.affectedList) scrollAList.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollAList.setBounds(150, 10, 550, 200) scrollAList.setBorder(LineBorder(Color.BLACK)) APtabs = JTabbedPane() self._requestAPViewer = callbacks.createMessageEditor(self, False) self._responseAPViewer = callbacks.createMessageEditor(self, False) APtabs.addTab("Request", self._requestAPViewer.getComponent()) APtabs.addTab("Affeced Page Response", self._responseAPViewer.getComponent()) APtabs.setBounds(0, 250, 700, 350) APtabs.setSelectedIndex(1) self.APpnl = JPanel() self.APpnl.setBounds(0, 0, 1000, 1000) self.APpnl.setLayout(None) self.APpnl.add(scrollAList) self.APpnl.add(clearAPListBtn) self.APpnl.add(APtabs) self.APpnl.add(apListLabel) tabs.addTab("Affected Pages", self.APpnl) self.intercept = 0 ## init conf panel startLabel = JLabel("Plugin status:") startLabel.setBounds(10, 10, 140, 30) payloadLabel = JLabel("Basic Payload:") payloadLabel.setBounds(10, 50, 140, 30) self.basicPayload = "<script>alert(1)</script>" self.basicPayloadTxt = JTextArea(self.basicPayload, 5, 30) self.basicPayloadTxt.setBounds(120, 50, 305, 30) self.bruteForceMode = JCheckBox("Brute Force Mode") self.bruteForceMode.setBounds(120, 80, 300, 30) self.bruteForceMode.addItemListener(handleBFModeChange(self)) self.tagPayloadsCheck = JCheckBox("Tag paylods") self.tagPayloadsCheck.setBounds(120, 100, 300, 30) self.tagPayloadsCheck.setSelected(True) self.tagPayloadsCheck.setEnabled(False) self.tagPayloadsCheck.addItemListener(handleBFModeList(self)) self.attributePayloadsCheck = JCheckBox("Attribute payloads") self.attributePayloadsCheck.setBounds(260, 100, 300, 30) self.attributePayloadsCheck.setSelected(True) self.attributePayloadsCheck.setEnabled(False) self.attributePayloadsCheck.addItemListener(handleBFModeList(self)) payloadListLabel = JLabel("Payloads list (for BF mode):") payloadListLabel.setBounds(10, 130, 140, 30) self.payloadsModel = DefaultListModel() self.payloadsList = JList(self.payloadsModel) scrollPayloadsList = JScrollPane(self.payloadsList) scrollPayloadsList.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollPayloadsList.setBounds(120, 170, 300, 200) scrollPayloadsList.setBorder(LineBorder( Color.BLACK)) # add buttons to remove payloads and add for payload in self.tagPayloads: self.payloadsModel.addElement(payload) for payload in self.attributePayloads: self.payloadsModel.addElement(payload) self.startButton = JButton("XSSor is off", actionPerformed=self.startOrStop) self.startButton.setBounds(120, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) consoleTab = JTabbedPane() self.consoleLog = JTextArea("", 5, 30) scrollLog = JScrollPane(self.consoleLog) scrollLog.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) scrollLog.setBounds(120, 170, 550, 200) scrollLog.setBorder(LineBorder(Color.BLACK)) scrollLog.getVerticalScrollBar().addAdjustmentListener( autoScrollListener(self)) consoleTab.addTab("Console", scrollLog) consoleTab.setBounds(0, 400, 500, 200) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000) self.pnl.setLayout(None) self.pnl.add(self.startButton) self.pnl.add(startLabel) self.pnl.add(payloadLabel) self.pnl.add(self.basicPayloadTxt) self.pnl.add(self.bruteForceMode) self.pnl.add(payloadListLabel) self.pnl.add(scrollPayloadsList) self.pnl.add(self.attributePayloadsCheck) self.pnl.add(self.tagPayloadsCheck) self.pnl.add(consoleTab) tabs.addTab("Configuration", self.pnl) tabs.setSelectedIndex(3) self._splitpane.setRightComponent(tabs) # customize our UI components callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self._callbacks.registerContextMenuFactory(self) print "Thank you for installing XSSor v0.1 extension" print "Created by Barak Tawily" print "\nGithub:\nhttps://github.com/Quitten/XSSor" return # # implement ITab # def getTabCaption(self): return "XSSor" def getUiComponent(self): return self._splitpane # # implement IHttpListener # def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if self.intercept == 1: if toolFlag == 4: # only process requests if not messageIsRequest: self.checkForKey(messageInfo) return def printLog(self, message): self.consoleLog.setText(self.consoleLog.getText() + '\r\n' + message) def checkXSS(self, messageInfo, urlStr, requestBody, currentPayload): self.printLog('trying exploit with the payload: ' + currentPayload) requestURL = URL(urlStr.replace(self.xssKey, currentPayload)) requestBody = requestBody.replace(self.xssKey, urllib.pathname2url(currentPayload)) httpService = self._helpers.buildHttpService( str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https") response = self._callbacks.makeHttpRequest(httpService, requestBody) responseInfo = self._helpers.analyzeResponse(response.getResponse()) analyzedResponse = self._helpers.bytesToString(response.getResponse( )) # change body offeset + make ui for affeccted pages responseBody = analyzedResponse.encode('utf-8') vulnOrNot = 'no' if currentPayload in responseBody: self.printLog('payload: ' + currentPayload + ' found to be vulnarble') vulnOrNot = 'yes' # mark the payload if not len(self.affectedResponses) == 0: for request in self.affectedResponses: # bug in case of no response in messageinfo self.printLog('checking affeccted page' + str(request.getUrl())) requestURL = request.getUrl() httpService = self._helpers.buildHttpService( str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https") affectedPageResponse = self._callbacks.makeHttpRequest( httpService, request.getRequest()) analyzedResponse = self._helpers.bytesToString( affectedPageResponse.getResponse()) responseBody = analyzedResponse.encode('utf-8') if currentPayload in responseBody: vulnOrNot = 'yes, affected page' self.printLog('affeccted page has been found as vulnerable') self._lock.acquire() row = self._log.size() self._log.add( LogEntry( self._helpers.analyzeRequest(response).getUrl(), self._callbacks.saveBuffersToTempFiles(response), currentPayload, vulnOrNot)) self.fireTableRowsInserted(row, row) self._lock.release() def checkForKey(self, messageInfo): currentPayload = self.tagPayloads[0] requestInfo = self._helpers.analyzeRequest(messageInfo) requestHeaders = list(requestInfo.getHeaders()) requestURL = requestInfo.getUrl() urlStr = str(requestURL) self.printLog('checking for xss key in URL: ' + urlStr) requestBody = self._helpers.bytesToString(messageInfo.getRequest()) requestBody = re.sub( 'Referer:.*\n', '', requestBody, flags=re.MULTILINE, count=1) # workaround avoid xsskey in the referer newHeaders if self.xssKey in urlStr or self.xssKey in requestBody: self.printLog('xss key has been found') if self.bruteForceMode.isSelected(): for i in range(0, self.payloadsModel.getSize()): payload = self.payloadsModel.getElementAt(i) self.checkXSS(messageInfo, urlStr, requestBody, payload) else: self.checkXSS(messageInfo, urlStr, requestBody, self.basicPayloadTxt.getText()) # # 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 "URL" if columnIndex == 1: return "Payload" if columnIndex == 2: return "Vulnerable?" return "" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: # return self._callbacks.getToolName(logEntry._tool) return logEntry._url.toString() if columnIndex == 1: return logEntry._payload if columnIndex == 2: return logEntry._vulnOrNot return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() def startOrStop(self, event): if self.startButton.getText() == "XSSor is off": self.startButton.setText("XSSor is on") self.startButton.setBackground(Color.GREEN) self.printLog('on, waiting for key word to be found (' + self.xssKey + ')') self.intercept = 1 else: self.startButton.setText("XSSor is off") self.startButton.setBackground(Color(255, 100, 91, 255)) self.intercept = 0 def clearAPList(self, event): self.affectedModel.clear() self.affectedResponses = ArrayList() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() affectedMenuItem = JMenuItem("XSSor: Add affected page") affectedMenuItem.addActionListener( handleMenuItems(self, responses[0], "affected")) ret.add(affectedMenuItem) return (ret) return null def addAfectedPage(self, messageInfo): self.affectedModel.addElement( str(self._helpers.analyzeRequest(messageInfo).getUrl())) self.affectedResponses.add(messageInfo)
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Autorize") # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self.intercept = 0 self.initInterceptionFilters() self.initEnforcementDetector() self.initExport() self.initConfigurationTab() self.initTabs() self.initCallbacks() print "Thank you for installing Autorize v0.9 extension" print "by Barak Tawily" return def initExport(self): # ## init enforcement detector tab # exportLType = JLabel("File Type:") exportLType.setBounds(10, 10, 100, 30) exportLES = JLabel("Enforcement Statuses:") exportLES.setBounds(10, 50, 160, 30) exportFileTypes = ["HTML"] self.exportType = JComboBox(exportFileTypes) self.exportType.setBounds(100, 10, 200, 30) exportES = [ "All Statuses", "Authorization bypass!", "Authorization enforced??? (please configure enforcement detector)", "Authorization enforced!" ] self.exportES = JComboBox(exportES) self.exportES.setBounds(100, 50, 200, 30) exportLES = JLabel("Statuses:") exportLES.setBounds(10, 50, 100, 30) self.exportButton = JButton("Export", actionPerformed=self.exportToHTML) self.exportButton.setBounds(390, 25, 100, 30) self.exportPnl = JPanel() self.exportPnl.setLayout(None) self.exportPnl.setBounds(0, 0, 1000, 1000) self.exportPnl.add(exportLType) self.exportPnl.add(self.exportType) self.exportPnl.add(exportLES) self.exportPnl.add(self.exportES) self.exportPnl.add(self.exportButton) def initEnforcementDetector(self): # ## init enforcement detector tab # self.EDFP = ArrayList() self.EDCT = ArrayList() EDLType = JLabel("Type:") EDLType.setBounds(10, 10, 140, 30) EDLContent = JLabel("Content:") EDLContent.setBounds(10, 50, 140, 30) EDLabelList = JLabel("Filter List:") EDLabelList.setBounds(10, 165, 140, 30) EDStrings = [ "Finger Print: (enforced message body contains)", "Content-Length: (constant Content-Length number of enforced response)" ] self.EDType = JComboBox(EDStrings) self.EDType.setBounds(80, 10, 430, 30) self.EDText = JTextArea("", 5, 30) self.EDText.setBounds(80, 50, 300, 110) self.EDModel = DefaultListModel() self.EDList = JList(self.EDModel) self.EDList.setBounds(80, 175, 300, 110) self.EDList.setBorder(LineBorder(Color.BLACK)) self.EDAdd = JButton("Add filter", actionPerformed=self.addEDFilter) self.EDAdd.setBounds(390, 85, 120, 30) self.EDDel = JButton("Remove filter", actionPerformed=self.delEDFilter) self.EDDel.setBounds(390, 210, 120, 30) self.EDPnl = JPanel() self.EDPnl.setLayout(None) self.EDPnl.setBounds(0, 0, 1000, 1000) self.EDPnl.add(EDLType) self.EDPnl.add(self.EDType) self.EDPnl.add(EDLContent) self.EDPnl.add(self.EDText) self.EDPnl.add(self.EDAdd) self.EDPnl.add(self.EDDel) self.EDPnl.add(EDLabelList) self.EDPnl.add(self.EDList) def initInterceptionFilters(self): # ## init interception filters tab # IFStrings = [ "URL Contains: ", "Scope items only: (Content is not required)" ] self.IFType = JComboBox(IFStrings) self.IFType.setBounds(80, 10, 430, 30) self.IFModel = DefaultListModel() self.IFList = JList(self.IFModel) self.IFList.setBounds(80, 175, 300, 110) self.IFList.setBorder(LineBorder(Color.BLACK)) self.IFText = JTextArea("", 5, 30) self.IFText.setBounds(80, 50, 300, 110) IFLType = JLabel("Type:") IFLType.setBounds(10, 10, 140, 30) IFLContent = JLabel("Content:") IFLContent.setBounds(10, 50, 140, 30) IFLabelList = JLabel("Filter List:") IFLabelList.setBounds(10, 165, 140, 30) self.IFAdd = JButton("Add filter", actionPerformed=self.addIFFilter) self.IFAdd.setBounds(390, 85, 120, 30) self.IFDel = JButton("Remove filter", actionPerformed=self.delIFFilter) self.IFDel.setBounds(390, 210, 120, 30) self.filtersPnl = JPanel() self.filtersPnl.setLayout(None) self.filtersPnl.setBounds(0, 0, 1000, 1000) self.filtersPnl.add(IFLType) self.filtersPnl.add(self.IFType) self.filtersPnl.add(IFLContent) self.filtersPnl.add(self.IFText) self.filtersPnl.add(self.IFAdd) self.filtersPnl.add(self.IFDel) self.filtersPnl.add(IFLabelList) self.filtersPnl.add(self.IFList) def initConfigurationTab(self): # ## init configuration tab # self.prevent304 = JCheckBox("Prevent 304 Not Modified status code") self.prevent304.setBounds(290, 25, 300, 30) self.ignore304 = JCheckBox("Ignore 304/204 status code responses") self.ignore304.setBounds(290, 5, 300, 30) self.ignore304.setSelected(True) self.autoScroll = JCheckBox("Auto Scroll") self.autoScroll.setBounds(290, 45, 140, 30) startLabel = JLabel("Authorization checks:") startLabel.setBounds(10, 10, 140, 30) self.startButton = JButton("Autorize is off", actionPerformed=self.startOrStop) self.startButton.setBounds(160, 10, 120, 30) self.startButton.setBackground(Color(255, 100, 91, 255)) self.clearButton = JButton("Clear List", actionPerformed=self.clearList) self.clearButton.setBounds(10, 40, 100, 30) self.replaceString = JTextArea("Cookie: Insert=injected; header=here;", 5, 30) self.replaceString.setWrapStyleWord(True) self.replaceString.setLineWrap(True) self.replaceString.setBounds(10, 80, 470, 180) self.filtersTabs = JTabbedPane() self.filtersTabs.addTab("Enforcement Detector", self.EDPnl) self.filtersTabs.addTab("Interception Filters", self.filtersPnl) self.filtersTabs.addTab("Export", self.exportPnl) self.filtersTabs.setBounds(0, 280, 2000, 700) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000) self.pnl.setLayout(None) self.pnl.add(self.startButton) self.pnl.add(self.clearButton) self.pnl.add(self.replaceString) self.pnl.add(startLabel) self.pnl.add(self.autoScroll) self.pnl.add(self.ignore304) self.pnl.add(self.prevent304) self.pnl.add(self.filtersTabs) def initTabs(self): # ## init autorize tabs # self.logTable = Table(self) self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self._splitpane.setResizeWeight(1) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) self.scrollPane.getVerticalScrollBar().addAdjustmentListener( autoScrollListener(self)) copyURLitem = JMenuItem("Copy URL") copyURLitem.addActionListener(copySelectedURL(self)) self.menu = JPopupMenu("Popup") self.menu.add(copyURLitem) self.tabs = JTabbedPane() self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self._originalrequestViewer = self._callbacks.createMessageEditor( self, False) self._originalresponseViewer = self._callbacks.createMessageEditor( self, False) self.tabs.addTab("Modified Request", self._requestViewer.getComponent()) self.tabs.addTab("Modified Response", self._responseViewer.getComponent()) self.tabs.addTab("Original Request", self._originalrequestViewer.getComponent()) self.tabs.addTab("Original Response", self._originalresponseViewer.getComponent()) self.tabs.addTab("Configuration", self.pnl) self.tabs.setSelectedIndex(4) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.customizeUiComponent(self.filtersTabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) # ## Events functions # def startOrStop(self, event): if self.startButton.getText() == "Autorize is off": self.startButton.setText("Autorize is on") self.startButton.setBackground(Color.GREEN) self.intercept = 1 self._callbacks.registerHttpListener(self) else: self.startButton.setText("Autorize is off") self.startButton.setBackground(Color(255, 100, 91, 255)) self.intercept = 0 self._callbacks.removeHttpListener(self) def addEDFilter(self, event): typeName = self.EDType.getSelectedItem().split(":")[0] self.EDModel.addElement(typeName + ": " + self.EDText.getText()) def delEDFilter(self, event): index = self.EDList.getSelectedIndex() if not index == -1: self.EDModel.remove(index) def addIFFilter(self, event): typeName = self.IFType.getSelectedItem().split(":")[0] self.IFModel.addElement(typeName + ": " + self.IFText.getText()) def delIFFilter(self, event): index = self.IFList.getSelectedIndex() if not index == -1: self.IFModel.remove(index) def clearList(self, event): self._lock.acquire() self._log = ArrayList() row = self._log.size() self.fireTableRowsInserted(row, row) self._lock.release() def exportToHTML(self, event): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setSelectedFile(File("AutorizeReprort.html")) fileChooser.setDialogTitle("Save Autorize Report") userSelection = fileChooser.showSaveDialog(parentFrame) if userSelection == JFileChooser.APPROVE_OPTION: fileToSave = fileChooser.getSelectedFile() enforcementStatusFilter = self.exportES.getSelectedItem() htmlContent = """<html><title>Autorize Report by Barak Tawily</title> <style> .datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .datagrid table td, .datagrid table th { padding: 3px 10px; } .datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }.datagrid table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .datagrid table tfoot td { padding: 0; font-size: 12px } .datagrid table tfoot td div{ padding: 2px; }.datagrid table tfoot td ul { margin: 0; padding:0; list-style: none; text-align: right; }.datagrid table tfoot li { display: inline; }.datagrid table tfoot li a { text-decoration: none; display: inline-block; padding: 2px 8px; margin: 1px;color: #FFFFFF;border: 1px solid #006699;-webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');background-color:#006699; }.datagrid table tfoot ul.active, .datagrid table tfoot ul a:hover { text-decoration: none;border-color: #006699; color: #FFFFFF; background: none; background-color:#00557F;}div.dhtmlx_window_active, div.dhx_modal_cover_dv { position: fixed !important; } table { width: 100%; table-layout: fixed; } td { border: 1px solid #35f; overflow: hidden; text-overflow: ellipsis; } td.a { width: 13%; white-space: nowrap; } td.b { width: 9%; word-wrap: break-word; } </style> <body> <h1>Autorize Report<h1> <div class="datagrid"><table> <thead><tr><th>URL</th><th>Authorization Enforcement Status</th></tr></thead> <tbody>""" for i in range(0, self._log.size()): color = "" if self._log.get( i )._enfocementStatus == "Authorization enforced??? (please configure enforcement detector)": color = "yellow" if self._log.get(i)._enfocementStatus == "Authorization bypass!": color = "red" if self._log.get(i)._enfocementStatus == "Authorization enforced!": color = "LawnGreen" if enforcementStatusFilter == "All Statuses": htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % ( color, self._log.get(i)._url, self._log.get(i)._url, self._log.get(i)._enfocementStatus) else: if enforcementStatusFilter == self._log.get( i)._enfocementStatus: htmlContent += "<tr bgcolor=\"%s\"><td><a href=\"%s\">%s</a></td><td>%s</td></tr>" % ( color, self._log.get(i)._url, self._log.get(i)._url, self._log.get(i)._enfocementStatus) htmlContent += "</tbody></table></div></body></html>" f = open(fileToSave.getAbsolutePath(), 'w') f.writelines(htmlContent) f.close() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send request to Autorize") cookieMenuItem = JMenuItem("Send cookie to Autorize") requestMenuItem.addActionListener( handleMenuItems(self, responses[0], "request")) cookieMenuItem.addActionListener( handleMenuItems(self, responses[0], "cookie")) ret.add(requestMenuItem) ret.add(cookieMenuItem) return (ret) return null # # implement ITab # def getTabCaption(self): return "Autorize" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 2 def getColumnName(self, columnIndex): if columnIndex == 0: return "URL" if columnIndex == 1: return "Authorization Enforcement Status" return "" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) if columnIndex == 0: return logEntry._url.toString() if columnIndex == 1: return logEntry._enfocementStatus return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() # # implement IHttpListener # def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if self.intercept == 1: if self.prevent304.isSelected(): if messageIsRequest: requestHeaders = list( self._helpers.analyzeRequest(messageInfo).getHeaders()) newHeaders = list() found = 0 for header in requestHeaders: if not "If-None-Match:" in header and not "If-Modified-Since:" in header: newHeaders.append(header) found = 1 if found == 1: requestInfo = self._helpers.analyzeRequest(messageInfo) bodyBytes = messageInfo.getRequest()[requestInfo. getBodyOffset():] bodyStr = self._helpers.bytesToString(bodyBytes) messageInfo.setRequest( self._helpers.buildHttpMessage( newHeaders, bodyStr)) if not messageIsRequest: if not self.replaceString.getText( ) in self._helpers.analyzeRequest(messageInfo).getHeaders(): if self.ignore304.isSelected(): firstHeader = self._helpers.analyzeResponse( messageInfo.getResponse()).getHeaders()[0] if "304" in firstHeader or "204" in firstHeader: return if self.IFList.getModel().getSize() == 0: self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()).getHeaders()) else: urlString = str( self._helpers.analyzeRequest(messageInfo).getUrl()) for i in range(0, self.IFList.getModel().getSize()): if self.IFList.getModel().getElementAt(i).split( ":")[0] == "Scope items only": currentURL = URL(urlString) if self._callbacks.isInScope(currentURL): self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()). getHeaders()) if self.IFList.getModel().getElementAt(i).split( ":")[0] == "URL Contains": if self.IFList.getModel().getElementAt( i)[14:] in urlString: self.checkAuthorization( messageInfo, self._helpers.analyzeResponse( messageInfo.getResponse()). getHeaders()) return def makeRequest(self, messageInfo, message): requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() return self._callbacks.makeHttpRequest( self._helpers.buildHttpService( str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), message) def makeMessage(self, messageInfo, removeOrNot): requestInfo = self._helpers.analyzeRequest(messageInfo) headers = requestInfo.getHeaders() if removeOrNot: headers = list(headers) removeHeaders = ArrayList() removeHeaders.add(self.replaceString.getText() [0:self.replaceString.getText().index(":")]) for header in headers[:]: for removeHeader in removeHeaders: if removeHeader in header: headers.remove(header) headers.append(self.replaceString.getText()) msgBody = messageInfo.getRequest()[requestInfo.getBodyOffset():] return self._helpers.buildHttpMessage(headers, msgBody) def checkAuthorization(self, messageInfo, originalHeaders): message = self.makeMessage(messageInfo, True) requestResponse = self.makeRequest(messageInfo, message) analyzedResponse = self._helpers.analyzeResponse( requestResponse.getResponse()) oldStatusCode = originalHeaders[0] newStatusCode = analyzedResponse.getHeaders()[0] oldContentLen = self.getContentLength(originalHeaders) newContentLen = self.getContentLength(analyzedResponse.getHeaders()) impression = "" EDFilters = self.EDModel.toArray() if oldStatusCode == newStatusCode: if oldContentLen == newContentLen: impression = "Authorization bypass!" else: impression = "Authorization enforced??? (please configure enforcement detector)" for filter in EDFilters: if str(filter).startswith("Content-Length: "): if newContentLen == filter: impression = "Authorization enforced!" if str(filter).startswith("Finger Print: "): if filter[14:] in self._helpers.bytesToString( requestResponse.getResponse() [analyzedResponse.getBodyOffset():]): impression = "Authorization enforced!" else: impression = "Authorization enforced!" self._lock.acquire() row = self._log.size() self._log.add( LogEntry(self._callbacks.saveBuffersToTempFiles(requestResponse), self._helpers.analyzeRequest(requestResponse).getUrl(), messageInfo, impression)) # same requests not include again. self.fireTableRowsInserted(row, row) self._lock.release() def getContentLength(self, analyzedResponseHeaders): for header in analyzedResponseHeaders: if "Content-Length:" in header: return header return "null" def getCookieFromMessage(self, messageInfo): headers = list( self._helpers.analyzeRequest( messageInfo.getRequest()).getHeaders()) for header in headers: if "Cookie:" in header: return header return None
class Remove_ArtifactsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.artifact_list = [] self.initComponents() self.customizeComponents() # Check to see if there are any entries that need to be populated from the database. def checkBoxEvent(self, event): if self.All_Artifacts_CB.isSelected(): self.local_settings.setSetting('allArtifacts', 'true') self.List_Box_LB.setEnabled(False) else: self.local_settings.setSetting('allArtifacts', 'false') self.List_Box_LB.setEnabled(True) if self.All_Attributes_CB.isSelected(): self.local_settings.setSetting('allAttributes', 'true') self.List_Box_LB.setEnabled(False) else: self.local_settings.setSetting('allAttributes', 'false') self.List_Box_LB.setEnabled(True) def onchange_lb(self, event): self.local_settings.setSetting('listSelected', '') list_selected = self.List_Box_LB.getSelectedValuesList() self.local_settings.setSetting('listSelected', list_selected) def get_artifacts(self): sql_statement = "select distinct(type_name) 'type_name' from blackboard_artifacts a, blackboard_artifact_types b " + \ " where a.artifact_type_id = b.artifact_type_id;" skCase = Case.getCurrentCase().getSleuthkitCase() dbquery = skCase.executeQuery(sql_statement) resultSet = dbquery.getResultSet() while resultSet.next(): self.artifact_list.append(resultSet.getString("type_name")) dbquery.close() # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout( self.gbPanel0 ) self.All_Artifacts_CB = JCheckBox("Remove All Custom Artifacts", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.All_Artifacts_CB, self.gbcPanel0 ) self.panel0.add( self.All_Artifacts_CB ) self.All_Attributes_CB = JCheckBox("Remove All Custom Attributes", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.All_Attributes_CB, self.gbcPanel0 ) self.panel0.add( self.All_Attributes_CB ) self.Blank_0 = JLabel( " ") self.Blank_0.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_0, self.gbcPanel0 ) self.panel0.add( self.Blank_0 ) self.Label_0 = JLabel( "Remove selected Artifacts") self.Label_0.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_0, self.gbcPanel0 ) self.panel0.add( self.Label_0 ) self.Blank_0 = JLabel( " ") self.Blank_0.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_0, self.gbcPanel0 ) self.panel0.add( self.Blank_0 ) self.get_artifacts() self.List_Box_LB = JList( self.artifact_list, valueChanged=self.onchange_lb) self.List_Box_LB.setVisibleRowCount( 3 ) self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 1 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) self.panel0.add( self.scpList_Box_LB ) self.Blank_1 = JLabel( " ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) self.panel0.add( self.Blank_1 ) self.Label_1 = JLabel( "Message:") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) self.panel0.add( self.Label_1 ) self.Blank_2 = JLabel( " ") self.Blank_2.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 13 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Blank_2, self.gbcPanel0 ) self.panel0.add( self.Blank_2 ) self.Error_Message = JLabel( "For developer purposes only, it may fubar your case") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 15 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) self.panel0.add( self.Error_Message ) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.All_Artifacts_CB.setSelected(self.local_settings.getSetting('allArtifacts') == 'true') self.All_Attributes_CB.setSelected(self.local_settings.getSetting('allAttributes') == 'true') # Return the settings used def getSettings(self): return self.local_settings
class SourceCellRenderer(TreeCellRenderer): def __init__(self,tree,mapContext): self.tree = tree self.mapContext = mapContext ## Group self.lblFolder = JLabel() self.lblFolder.setBackground(Color(222,227,233)) #.BLUE.brighter()) self.lblFolder.setOpaque(True) self.lblFolder.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd") ### Folder self.pnlFolder = JPanel() self.pnlFolder.setOpaque(False) self.pnlFolder.setLayout(FlowLayout(FlowLayout.LEFT)) self.lblGroup = JLabel() #self.lblGroup.setBackground(Color(222,227,233)) #.BLUE.brighter()) #self.lblGroup.setOpaque(True) self.lblGroup.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd") self.lblGroupPreferredSize = self.lblGroup.getPreferredSize() self.lblGroupIcon = JLabel() self.pnlFolder.add(self.lblGroupIcon) self.pnlFolder.add(self.lblGroup) #self.lblGroup.setBorder( # BorderFactory.createLineBorder(Color(222,227,233).darker(),1) #) #self.lblGroupPreferredSize.setSize(30,200)#self.lblGroupPreferredSize.getHeight()+4, self.lblGroupPreferredSize.getWidth()) ### LAYER self.pnlLayer = JPanel() self.pnlLayer.setOpaque(False) #self.pnlLayer.setBorder(EmptyBorder(2,2,2,2)) self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT)) self.chkLayerVisibility = JCheckBox() self.chkLayerVisibility.setOpaque(False) self.pnlLayer.add(self.chkLayerVisibility) self.lblLayerIcon = JLabel() self.lblLayerName = JLabel() self.pnlLayer.add(self.lblLayerIcon) self.pnlLayer.add(self.lblLayerName) #self.tree.setRowHeight(int(self.pnlLayer.getPreferredSize().getHeight())) #+2 self.tree.setRowHeight(int(self.pnlFolder.getPreferredSize().getHeight())) self.lblUnknown = JLabel() def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus): uo = value.getUserObject() if isinstance(uo, DataFolder): #self.lblFolder.setText(uo.getName()) text = "[" + str(value.getChildCount()) +"] " + uo.getName() self.lblFolder.setText(text) self.lblFolder.setPreferredSize(self.lblGroupPreferredSize) if uo.getIcon()!=None: self.lblGroupIcon.setIcon(uo.getIcon()) else: self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open")) return self.lblFolder if isinstance(uo, DataGroup): self.lblGroup.setText(uo.getName()) self.lblGroup.setPreferredSize(self.lblGroupPreferredSize) if uo.getIcon()!=None: self.lblGroupIcon.setIcon(uo.getIcon()) else: #import pdb #pdb.set_trace() self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open")) return self.pnlFolder if isinstance(uo, DataLayer): layer = uo.getLayer() self.lblLayerName.setText(layer.getName()) self.lblLayerIcon.setIcon(getIconFromLayer(layer)) self.chkLayerVisibility.setSelected(layer.isVisible()) if layer.isWithinScale(self.mapContext.getScaleView()): # and layer.isVisible(): self.chkLayerVisibility.setEnabled(True) else: self.chkLayerVisibility.setEnabled(False) self.lblLayerName.setForeground(Color.BLACK) font = self.lblLayerName.getFont() self.lblLayerName.setForeground(Color.BLACK) if layer.isEditing(): self.lblLayerName.setForeground(Color.RED) if layer.isActive() and font.isBold(): pass elif layer.isActive() and not font.isBold(): newfont = font.deriveFont(Font.BOLD) self.lblLayerName.setFont(newfont) else: newfont = font.deriveFont(Font.PLAIN) self.lblLayerName.setFont(newfont) #self.pnlLayer.repaint() return self.pnlLayer self.lblUnknown.setText("") self.lblUnknown.setPreferredSize(Dimension(0,0)) return self.lblUnknown
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener): """Dialog with preferences """ def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder() self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = ["", self.app.strings.getString("Type"), self.app.strings.getString("Name")] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack() def windowClosing(self, windowEvent): self.on_cancelBtn_clicked() def hyperlinkUpdate(self, e): if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED: OpenBrowser.displayUrl(e.getURL().toString()) def itemStateChanged(self, e): """A ttol has been activated/deactivated. Check if at least one tool is on. """ if all(not button.isSelected() for button in self.toolsCBtns): JOptionPane.showMessageDialog( Main.parent, self.app.strings.getString("tools_disabled_warning"), self.app.strings.getString("tools_disabled_warning_title"), JOptionPane.WARNING_MESSAGE) source = e.getItemSelectable() source.setSelected(True) def actionPerformed(self, e=None): """Enable/disable favourite zones panel """ for container in (self.scrollPane, self.buttonsPanel): self.enableComponents(container, self.favZoneStatusCBtn.isSelected()) if self.favZoneStatusCBtn.isSelected(): self.check_removeBtn_status() def enableComponents(self, container, enable): components = container.getComponents() for component in components: component.setEnabled(enable) if isinstance(component, Container): self.enableComponents(component, enable) def on_downloadBtn_clicked(self, e): update_checker.Updater(self.app, "manual") def clean_map(self): """Remove all rectangles and polygons from the map """ self.zonesMap.removeAllMapRectangles() self.zonesMap.removeAllMapPolygons() def update_gui_from_preferences(self): """Update gui status of preferences frame from config file """ #print "\n- updating Preferences gui" onOff = {"on": True, "off": False} #1 Tab #check for update self.updateCBtn.setSelected(onOff[self.app.checkUpdate]) #tools status, enabled or not for toolIndex, tool in enumerate(self.app.realTools): if "tool.%s" % tool.name in self.app.properties.keys(): configstatus = self.app.properties.getProperty("tool.%s" % tool.name) else: configstatus = "on" # new tool self.toolsCBtns[toolIndex].setSelected(onOff[configstatus]) #layers preferences for mode, button in self.layersRBtns.iteritems(): button.setSelected(mode == self.app.layersMode) #max errors number self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber)) #stats panel self.app.dlg.update_favourite_zone_indicator() #2 Tab #favourite area self.update_favourite_area_gui_from_preferences() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: tool.prefsGui.update_gui(tool.prefs) def update_favourite_area_gui_from_preferences(self): #status self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus) #table #store zones to a temporary list, used to store changes #and save them when preferences dialog is closed self.app.tempZones = list(self.app.zones) self.zonesTable.getModel().setNumRows(0) for zone in self.app.tempZones: self.zonesTable.getModel().addRow([zone.country, zone.icon, zone.name]) if self.app.favZone is not None: selectedRow = self.app.tempZones.index(self.app.favZone) self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow) self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30) self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50) #enable or disable favourite zone buttons self.actionPerformed() ### fav area editing buttons ########################################### def on_removeBtn_clicked(self, e): rowsNum = self.zonesTable.getSelectedRows() rowsNum.reverse() for rowNum in rowsNum: del self.app.tempZones[rowNum] self.zonesTable.getModel().removeRow(rowNum) if len(self.app.tempZones) != 0: if rowNum == 0: self.zonesTable.setRowSelectionInterval(0, 0) else: self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1) self.check_removeBtn_status() def check_removeBtn_status(self): if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0: self.removeBtn.setEnabled(True) else: self.removeBtn.setEnabled(False) self.clean_map() def on_newBtn_clicked(self, e): try: self.newZoneDialog except AttributeError: self.newZoneDialog = NewZoneDialog(self.app) bbox = self.app.get_frame_bounds() self.app.newZone = Zone(self.app, self.app.strings.getString("New_zone"), "rectangle", ",".join(["%0.4f" % x for x in bbox]), "") self.newZoneDialog.update_gui_from_preferences() self.newZoneDialog.show() ### Exit from preferences ############################################## def on_cancelBtn_clicked(self, event=None): if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible(): self.newZoneDialog.close_dialog() self.dispose() def on_saveBtn_clicked(self, event): """Read preferences from gui and save them to config.properties file """ #print "\n- saving preferences to config file" onOff = {True: "on", False: "off"} #1 Tab #check for update self.app.properties.setProperty("check_for_update", onOff[self.updateCBtn.isSelected()]) #tools status for toolIndex, tool in enumerate(self.app.realTools): prop = "tool.%s" % tool.name toolCBtn = self.toolsCBtns[toolIndex] self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()]) #layers preferences for mode, button in self.layersRBtns.iteritems(): if button.isSelected(): self.app.properties.setProperty("layers_mode", mode) break #max errors number try: num = Integer.parseInt(self.maxErrorsNumberTextField.getText()) except NumberFormatException: num = "" self.app.properties.setProperty("max_errors_number", str(num)) #2 Tab #Favourite zones changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones], "deleted": [z for z in self.app.zones if not z in self.app.tempZones]} #delete files of removed favourite zones for zone in changes["deleted"]: f = File(File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name])) f.delete() #create files for new favourite zones for zone in changes["new"]: print "\nsave new zone", zone.name fileName = File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name]) f = open(fileName, "w") zoneData = zone.geomString if zone.country != "": zoneData += "|" + zone.country f.write(zoneData.encode("utf-8")) f.close() self.app.zones = self.app.tempZones if len(self.app.zones) == 0: self.app.favZone = None self.app.properties.setProperty("favourite_area.name", "") self.favZoneStatusCBtn.setSelected(False) else: if len(self.zonesTable.getSelectedRows()) == 0: self.app.favZone = self.app.zones[0] else: self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]] self.app.properties.setProperty("favourite_area.name", self.app.favZone.name) favZoneStatus = self.favZoneStatusCBtn.isSelected() self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus]) self.app.favouriteZoneStatus = favZoneStatus #stats panel self.app.dlg.update_favourite_zone_indicator() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: for pref, value in tool.prefsGui.read_gui().iteritems(): prefKey = "tool.%s.%s" % (tool.name, pref) self.app.properties.setProperty(prefKey, value) self.app.save_config() self.dispose()
class UISettingsPanel(IngestModuleIngestJobSettingsPanel): def __init__(self, settings): self.localSettings = settings self.buttons = { '1': JButton("Choose", actionPerformed=self.chooseFolder), } self.textInputs = { "1": JTextField('', 5), } self.initComponents() self.customizeComponents() def checkBoxEvent(self, event): self.localSettings.setFlag(self.checkboxJPG.isSelected(), 0) self.localSettings.setFlag(self.checkboxJPEG.isSelected(), 1) self.localSettings.setFlag(self.checkboxPNG.isSelected(), 2) self.localSettings.setFlag(self.chckbxGenerateImageHash.isSelected(), 3) def clear(self, e): button = e.getSource() code = button.getActionCommand() self.localSettings.setPath(code, "") self.textInputs[code].text = "" def chooseFolder(self, e): button = e.getSource() code = button.getActionCommand() fileChooser = JFileChooser() fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) text = "Choose folder" ret = fileChooser.showDialog(self, text) if ret == JFileChooser.APPROVE_OPTION: ff = fileChooser.getSelectedFile() path = ff.getCanonicalPath() self.localSettings.setPath(code, path) self.textInputs[code].text = path def initComponents(self): self.setLayout(None) lblFileExtensionsTo = JLabel("File extensions to look for:") lblFileExtensionsTo.setBounds(43, 37, 161, 16) self.add(lblFileExtensionsTo) self.checkboxPNG = JCheckBox(".PNG", actionPerformed=self.checkBoxEvent) self.checkboxPNG.setBounds(43, 62, 72, 25) self.add(self.checkboxPNG) self.checkboxJPG = JCheckBox(".JPG", actionPerformed=self.checkBoxEvent) self.checkboxJPG.setBounds(43, 92, 72, 25) self.add(self.checkboxJPG) self.checkboxJPEG = JCheckBox(".JPEG", actionPerformed=self.checkBoxEvent) self.checkboxJPEG.setBounds(118, 62, 113, 25) self.add(self.checkboxJPEG) lblNewLabel = JLabel("Folder with images of person to find:") lblNewLabel.setBounds(43, 145, 223, 16) self.add(lblNewLabel) textField = self.textInputs['1'] textField.setBounds(43, 167, 223, 22) self.add(textField) textField.setColumns(30) self.buttons['1'].setActionCommand("1") self.buttons['1'].setBounds(43, 195, 113, 25) self.add(self.buttons['1']) #TODO:: This no longer is required, it's done within the executable self.chckbxGenerateImageHash = JCheckBox("Generate image hash for DFXML") self.chckbxGenerateImageHash.setBounds(43, 239, 223, 25) self.add(self.chckbxGenerateImageHash) def customizeComponents(self): self.localSettings.loadConfig() self.checkboxJPG.setSelected(self.localSettings.getFlag(0)) self.checkboxJPEG.setSelected(self.localSettings.getFlag(1)) self.checkboxPNG.setSelected(self.localSettings.getFlag(2)) self.chckbxGenerateImageHash.setSelected(self.localSettings.getFlag(3)) for code in self.textInputs: self.textInputs[code].text = self.localSettings.getPath(code) def getSettings(self): return self.localSettings
class BurpExtender(IBurpExtender, ITab, IHttpListener, IMessageEditorController, AbstractTableModel, IContextMenuFactory, IExtensionStateListener): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Burp Scope Monitor Experimental") self.GLOBAL_HANDLER_ANALYZED = False self.GLOBAL_HANDLER = False self.STATUS = False self.AUTOSAVE_REQUESTS = 10 self.AUTOSAVE_TIMEOUT = 600 # 10 minutes should be fine self.CONFIG_INSCOPE = True self.BAD_EXTENSIONS_DEFAULT = [ '.gif', '.png', '.js', '.woff', '.woff2', '.jpeg', '.jpg', '.css', '.ico', '.m3u8', '.ts', '.svg' ] self.BAD_MIMES_DEFAULT = [ 'gif', 'script', 'jpeg', 'jpg', 'png', 'video', 'mp2t' ] self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.BAD_MIMES = self.BAD_MIMES_DEFAULT # create the log and a lock on which to synchronize when adding log entries self._currentlyDisplayedItem = None self.SELECTED_MODEL_ROW = 0 self.SELECTED_VIEW_ROW = 0 self._log = ArrayList() self._fullLog = ArrayList() self._lock = Lock() self._lockFile = Lock() # main split pane self._parentPane = JTabbedPane() self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) ##### config pane self._config = JTabbedPane() config = JPanel() iexport = JPanel() #config.setLayout(BorderLayout()) config.setLayout(None) iexport.setLayout(None) # config radio button X_BASE = 40 Y_OFFSET = 5 Y_OPTION = 200 Y_OPTION_SPACING = 20 Y_CHECKMARK_SPACING = 20 self.showAllButton = JRadioButton(SHOW_ALL_BUTTON_LABEL, True) self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.setBounds(40, 60 + Y_OFFSET, 400, 30) self.showNewButton.setBounds(40, 80 + Y_OFFSET, 400, 30) self.showTestedButton.setBounds(40, 100 + Y_OFFSET, 400, 30) #self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False) #self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False) self.showAllButton.addActionListener(self.handleRadioConfig) self.showNewButton.addActionListener(self.handleRadioConfig) self.showTestedButton.addActionListener(self.handleRadioConfig) self.clearButton = JButton("Clear") self.clearButton.addActionListener(self.handleClearButton) self.clearButton.setBounds(40, 20, 100, 30) self.startButton = JButton(MONITOR_ON_LABEL) self.startButton.addActionListener(self.handleStartButton) self.startButton.setBounds(150, 20, 200, 30) self.badExtensionsLabel = JLabel("Ignore extensions:") self.badExtensionsLabel.setBounds(X_BASE, 150, 200, 30) self.badExtensionsText = JTextArea("") self.loadBadExtensions() self.badExtensionsText.setBounds(X_BASE, 175, 310, 30) self.badExtensionsButton = JButton("Save") self.badExtensionsButton.addActionListener( self.handleBadExtensionsButton) self.badExtensionsButton.setBounds(355, 175, 70, 30) self.badExtensionsDefaultButton = JButton("Load Defaults") self.badExtensionsDefaultButton.addActionListener( self.handleBadExtensionsDefaultButton) self.badExtensionsDefaultButton.setBounds(430, 175, 120, 30) self.badMimesLabel = JLabel("Ignore mime types:") self.badMimesLabel.setBounds(X_BASE, 220, 200, 30) self.badMimesText = JTextArea("") self.loadBadMimes() self.badMimesText.setBounds(X_BASE, 245, 310, 30) self.badMimesButton = JButton("Save") self.badMimesButton.addActionListener(self.handleBadMimesButton) self.badMimesButton.setBounds(355, 245, 70, 30) self.badMimesDefaultButton = JButton("Load Defaults") self.badMimesDefaultButton.addActionListener( self.handleBadMimesDefaultButton) self.badMimesDefaultButton.setBounds(430, 245, 120, 30) self.otherLabel = JLabel("Other:") self.otherLabel.setBounds(40, 300, 120, 30) self.otherLabel2 = JLabel("Other:") self.otherLabel2.setBounds(X_BASE, Y_OPTION, 120, 30) self.autoSaveOption = JCheckBox("Auto save periodically") self.autoSaveOption.setSelected(True) self.autoSaveOption.addActionListener(self.handleAutoSaveOption) self.autoSaveOption.setBounds(X_BASE, Y_OPTION + Y_CHECKMARK_SPACING, 420, 30) self.repeaterOptionButton = JCheckBox( "Repeater request automatically marks as analyzed") self.repeaterOptionButton.setSelected(True) self.repeaterOptionButton.addActionListener( self.handleRepeaterOptionButton) self.repeaterOptionButton.setBounds(50, 330, 420, 30) self.scopeOptionButton = JCheckBox("Follow Burp Target In Scope rules") self.scopeOptionButton.setSelected(True) self.scopeOptionButton.addActionListener(self.handleScopeOptionButton) self.scopeOptionButton.setBounds(50, 350, 420, 30) self.startOptionButton = JCheckBox("Autostart Scope Monitor") self.startOptionButton.setSelected(True) self.startOptionButton.addActionListener(self.handleStartOption) self.startOptionButton.setBounds(50, 350 + Y_OPTION_SPACING, 420, 30) self.markTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if analyzed") self.markTestedRequestsProxy.setSelected(True) self.markTestedRequestsProxy.addActionListener( self.handleTestedRequestsProxy) self.markTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 2, 420, 30) self.markNotTestedRequestsProxy = JCheckBox( "Color request in Proxy tab if NOT analyzed") self.markNotTestedRequestsProxy.setSelected(True) self.markNotTestedRequestsProxy.addActionListener( self.handleNotTestedRequestsProxy) self.markNotTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 3, 420, 30) self.saveButton = JButton("Save now") self.saveButton.addActionListener(self.handleSaveButton) self.saveButton.setBounds(X_BASE + 320, 95, 90, 30) self.loadButton = JButton("Load now") self.loadButton.addActionListener(self.handleLoadButton) self.loadButton.setBounds(X_BASE + 420, 95, 90, 30) self.selectPath = JButton("Select path") self.selectPath.addActionListener(self.selectExportFile) self.selectPath.setBounds(X_BASE + 530, 60, 120, 30) self.selectPathText = JTextArea("") self.selectPathText.setBounds(X_BASE, 60, 510, 30) self.selectPathLabel = JLabel("State file:") self.selectPathLabel.setBounds(X_BASE, 30, 200, 30) bGroup = ButtonGroup() bGroup.add(self.showAllButton) bGroup.add(self.showNewButton) bGroup.add(self.showTestedButton) config.add(self.clearButton) config.add(self.startButton) config.add(self.startOptionButton) config.add(self.showAllButton) config.add(self.showNewButton) config.add(self.showTestedButton) config.add(self.badExtensionsButton) config.add(self.badExtensionsText) config.add(self.badExtensionsLabel) config.add(self.badMimesButton) config.add(self.badMimesText) config.add(self.badMimesLabel) config.add(self.badExtensionsDefaultButton) config.add(self.badMimesDefaultButton) config.add(self.otherLabel) config.add(self.repeaterOptionButton) config.add(self.scopeOptionButton) config.add(self.markTestedRequestsProxy) config.add(self.markNotTestedRequestsProxy) iexport.add(self.saveButton) iexport.add(self.loadButton) iexport.add(self.selectPath) iexport.add(self.selectPathText) iexport.add(self.selectPathLabel) iexport.add(self.otherLabel2) iexport.add(self.autoSaveOption) self._config.addTab("General", config) self._config.addTab("Import/Export", iexport) ##### end config pane self._parentPane.addTab("Monitor", self._splitpane) self._parentPane.addTab("Config", self._config) # table of log entries self.logTable = Table(self) #self.logTable.setDefaultRenderer(self.logTable.getColumnClass(0), ColoredTableCellRenderer(self)) self.logTable.setAutoCreateRowSorter(True) self.logTable.setRowSelectionAllowed(True) renderer = ColoredTableCellRenderer(self) #column = TableColumn(0, 190, renderer, None) print 'Initiating... ' # this could be improved by fetching initial dimensions self.logTable.getColumn("URL").setPreferredWidth(720) # noscope self.logTable.getColumn("URL").setResizable(True) self.logTable.getColumn("Checked").setCellRenderer(renderer) self.logTable.getColumn("Checked").setPreferredWidth(80) self.logTable.getColumn("Checked").setMaxWidth(80) self.logTable.getColumn("Method").setPreferredWidth(120) #self.logTable.getColumn("Method").setMaxWidth(120) self.logTable.getColumn("Method").setResizable(True) self.logTable.getColumn("Time").setPreferredWidth(120) # noscope self.logTable.getColumn("Time").setResizable(True) scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) self._splitpane.setRightComponent(tabs) ## Row sorter shit #self._tableRowSorterAutoProxyAutoAction = CustomTableRowSorter(self.logTable.getModel()) #self.logTable.setRowSorter(self._tableRowSorterAutoProxyAutoAction) markAnalyzedButton = JMenuItem("Mark Requests as Analyzed") markAnalyzedButton.addActionListener(markRequestsHandler(self, True)) markNotAnalyzedButton = JMenuItem("Mark Requests as NOT Analyzed") markNotAnalyzedButton.addActionListener( markRequestsHandler(self, False)) sendRequestMenu = JMenuItem("Send Request to Repeater") sendRequestMenu.addActionListener(sendRequestRepeater(self)) deleteRequestMenu = JMenuItem("Delete request") deleteRequestMenu.addActionListener(deleteRequestHandler(self)) self.menu = JPopupMenu("Popup") self.menu.add(markAnalyzedButton) self.menu.add(markNotAnalyzedButton) self.menu.add(sendRequestMenu) self.menu.add(deleteRequestMenu) # customize our UI components callbacks.customizeUiComponent(self._parentPane) callbacks.customizeUiComponent(self._splitpane) callbacks.customizeUiComponent(self._config) callbacks.customizeUiComponent(config) callbacks.customizeUiComponent(self.logTable) callbacks.customizeUiComponent(scrollPane) callbacks.customizeUiComponent(tabs) callbacks.registerContextMenuFactory(self) callbacks.registerExtensionStateListener(self) callbacks.registerScannerCheck(passiveScanner(self)) # add the custom tab to Burp's UI callbacks.addSuiteTab(self) # register ourselves as an HTTP listener callbacks.registerHttpListener(self) self.loadConfigs() print "Loaded!" print "Experimental import state.. " self.importState("") self.SC = sched.scheduler(time.time, time.sleep) self.SCC = self.SC.enter(10, 1, self.autoSave, (self.SC, )) self.SC.run() return ##### CUSTOM CODE ##### def loadConfigs(self): if self._callbacks.loadExtensionSetting("CONFIG_AUTOSTART") == "False": self.startOptionButton.setSelected(False) self.startOrStop(None, False) else: self.startOptionButton.setSelected(True) self.startOrStop(None, True) if self._callbacks.loadExtensionSetting("exportFile") != "": self.selectPathText.setText( self._callbacks.loadExtensionSetting("exportFile")) if self._callbacks.loadExtensionSetting("CONFIG_REPEATER") == "True": self.repeaterOptionButton.setSelected(True) else: self.repeaterOptionButton.setSelected(False) if self._callbacks.loadExtensionSetting("CONFIG_INSCOPE") == "True": self.scopeOptionButton.setSelected(True) else: self.scopeOptionButton.setSelected(False) if self._callbacks.loadExtensionSetting("CONFIG_AUTOSAVE") == "True": self.autoSaveOption.setSelected(True) else: self.autoSaveOption.setSelected(False) if self._callbacks.loadExtensionSetting( "CONFIG_HIGHLIGHT_TESTED") == "True": self.markTestedRequestsProxy.setSelected(True) else: self.markTestedRequestsProxy.setSelected(False) if self._callbacks.loadExtensionSetting( "CONFIG_HIGHLIGHT_NOT_TESTED") == "True": self.markNotTestedRequestsProxy.setSelected(True) else: self.markNotTestedRequestsProxy.setSelected(False) return def selectExportFile(self, event): parentFrame = JFrame() fileChooser = JFileChooser() fileChooser.setDialogTitle("Specify file to save state") fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY) userSelection = fileChooser.showOpenDialog(parentFrame) if (userSelection == JFileChooser.APPROVE_OPTION): fileLoad = fileChooser.getSelectedFile() filename = fileLoad.getAbsolutePath() self.selectPathText.setText(filename) print 'Filename selected:' + filename self._callbacks.saveExtensionSetting("exportFile", filename) return def extensionUnloaded(self): print 'extension unloading.. ' print 'canceling scheduler.. ' map(self.SC.cancel, self.SC.queue) return def loadBadExtensions(self): bad = self._callbacks.loadExtensionSetting("badExtensions") if bad: self.badExtensionsText.setText(bad) # transform text to array bad = bad.replace(" ", "") self.BAD_EXTENSIONS = bad.split(",") else: print 'no bad extension saved, reverting' self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS)) def loadBadMimes(self): bad = self._callbacks.loadExtensionSetting("badMimes") if bad: self.badMimesText.setText(bad) bad = bad.replace(" ", "") self.BAD_MIMES = bad.split(",") else: print 'no bad mimes saved, reverting' self.badMimesText.setText(", ".join(self.BAD_MIMES)) ## GLOBAL CONTEXT CODE ## def createMenuItems(self, invocation): responses = invocation.getSelectedMessages() if responses > 0: ret = LinkedList() analyzedMenuItem = JMenuItem("Mark as analyzed") notAnalyzedMenuItem = JMenuItem("Mark as NOT analyzed") for response in responses: analyzedMenuItem.addActionListener( handleMenuItems(self, response, "analyzed")) notAnalyzedMenuItem.addActionListener( handleMenuItems(self, response, "not")) ret.add(analyzedMenuItem) ret.add(notAnalyzedMenuItem) return ret def getEndpoint(self, requestResponse): url_ = str(self._helpers.analyzeRequest(requestResponse).getUrl()) o = urlparse(url_) url = o.scheme + "://" + o.netloc + o.path #print "Url3: " + url return url def getMethod(self, requestResponse): return self._helpers.analyzeRequest(requestResponse).getMethod() ##### CUSTOM CODE ##### def handleTestedRequestsProxy(self, event): self._callbacks.saveExtensionSetting( "CONFIG_HIGHLIGHT_TESTED", str(self.markTestedRequestsProxy.isSelected())) return def handleNotTestedRequestsProxy(self, event): self._callbacks.saveExtensionSetting( "CONFIG_HIGHLIGHT_NOT_TESTED", str(self.markNotTestedRequestsProxy.isSelected())) return def handleStartOption(self, event): self._callbacks.saveExtensionSetting( "CONFIG_AUTOSTART", str(self.startOptionButton.isSelected())) #print 'saving autostart: ' + str(self.startOptionButton.isSelected()) return def startOrStop(self, event, autoStart): if (self.startButton.getText() == MONITOR_OFF_LABEL) or autoStart: self.startButton.setText(MONITOR_ON_LABEL) self.startButton.setBackground(GREEN_COLOR) self.STATUS = True else: self.startButton.setText(MONITOR_OFF_LABEL) self.startButton.setBackground(RED_COLOR) self.STATUS = False def handleStartButton(self, event): self.startOrStop(event, False) def handleAutoSaveOption(self, event): self._callbacks.saveExtensionSetting( "CONFIG_AUTOSAVE", str(self.autoSaveOption.isSelected())) return def handleSaveButton(self, event): self.exportState("") def handleLoadButton(self, event): self.importState("") def handleRepeaterOptionButton(self, event): self._callbacks.saveExtensionSetting( "CONFIG_REPEATER", str(self.repeaterOptionButton.isSelected())) return def handleScopeOptionButton(self, event): self.CONFIG_INSCOPE = self.scopeOptionButton.isSelected() self._callbacks.saveExtensionSetting("CONFIG_INSCOPE", str(self.CONFIG_INSCOPE)) return def handleBadExtensionsButton(self, event): #print "before BAD array: " print self.BAD_EXTENSIONS extensions = self.badExtensionsText.getText() self._callbacks.saveExtensionSetting("badExtensions", extensions) print 'New extensions blocked: ' + extensions bad = extensions.replace(" ", "") self.BAD_EXTENSIONS = bad.split(",") #print "BAD array: " #print self.BAD_EXTENSIONS def handleBadExtensionsDefaultButton(self, event): self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS)) self._callbacks.saveExtensionSetting("badExtensions", ", ".join(self.BAD_EXTENSIONS)) return def handleBadMimesDefaultButton(self, event): self.BAD_MIMES = self.BAD_MIMES_DEFAULT self.badMimesText.setText(", ".join(self.BAD_MIMES)) self._callbacks.saveExtensionSetting("badExtensions", ", ".join(self.BAD_MIMES)) return def handleBadMimesButton(self, event): mimes = self.badMimesText.getText() self._callbacks.saveExtensionSetting("badMimes", mimes) print 'New mimes blocked: ' + mimes bad = mimes.replace(" ", "") self.BAD_MIMES = bad.split(",") def handleClearButton(self, event): print 'Clearing table' self._lock.acquire() self._log = ArrayList() self._fullLog = ArrayList() self._lock.release() return def handleRadioConfig(self, event): #print ' radio button clicked ' #print event.getActionCommand() self._lock.acquire() if event.getActionCommand() == SHOW_ALL_BUTTON_LABEL: print "Showing all" self._log = self._fullLog elif event.getActionCommand() == SHOW_NEW_BUTTON_LABEL: print "Showing new scope only" tmpLog = ArrayList() for item in self._fullLog: if not (item._analyzed): tmpLog.add(item) self._log = tmpLog elif event.getActionCommand() == SHOW_TEST_BUTTON_LABEL: print "Showing tested scope only" tmpLog = ArrayList() for item in self._fullLog: if item._analyzed: tmpLog.add(item) self._log = tmpLog else: print "unrecognized radio label" self.fireTableDataChanged() #self._tableRowSorterAutoProxyAutoAction.toggleSortOrder(1) #self.toggleSortOrder(2) #self.logTable.toggleSortOrder(2) # refresh table? self._lock.release() # # implement ITab # def getTabCaption(self): return "Scope Monitor" def getUiComponent(self): return self._parentPane # # implement IHttpListener # def markAnalyzed(self, messageIsRequest, state): #print "markAnalyzed..." self._lock.acquire() url = self.getEndpoint(messageIsRequest) for item in self._log: if url == item._url: item._analyzed = state self._lock.release() return self._lock.release() return def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): # only process requests #print "processing httpMessage.." #print messageIsRequest print "processHttpMessage toolFlag: " + str(toolFlag) #print " -- " + str(self._callbacks.getToolName(toolFlag)) + " -- " if not (self.STATUS): return #print "global handler status: (true): " + str(self.GLOBAL_HANDLER) #print "(processHTTP) messageIsRequest" #print messageIsRequest isFromPassiveScan = False if toolFlag == 1234: print "1 processHttpMessage: processing passiveScan item" isFromPassiveScan = True if toolFlag != 1234: if messageIsRequest and not (self.GLOBAL_HANDLER): print "1.5 processHttpMessage droping message" return if self.scopeOptionButton.isSelected(): url = self._helpers.analyzeRequest(messageInfo).getUrl() if not self._callbacks.isInScope(url): #print 'Url not in scope, skipping.. ' return #print "still processing httpMessage.., request came from: " + self._callbacks.getToolName(toolFlag) if toolFlag == 1234: print "2 processHttpMessage: processing passiveScan item; setting toolFlag to proxy (4)" toolFlag = 4 #toolFlag = 4 if ((self._callbacks.getToolName(toolFlag) != "Repeater") and (self._callbacks.getToolName(toolFlag) != "Proxy") and (self._callbacks.getToolName(toolFlag) != "Target")): #print 'Aborting processHTTP, request came from: ' + str(self._callbacks.getToolName(toolFlag)) print "Droping request from " + str( self._callbacks.getToolName(toolFlag)) return #print "---> still processing from tool: " + str(self._callbacks.getToolName(toolFlag)) url = self.getEndpoint(messageInfo) method = self.getMethod(messageInfo) #print "(processHTTP) before extensions check: " + url for extension in self.BAD_EXTENSIONS: if url.endswith(extension): return if messageInfo.getResponse(): mime = self._helpers.analyzeResponse( messageInfo.getResponse()).getStatedMimeType() #print 'Declared mime:' + mime mime = mime.lower() if mime in self.BAD_MIMES: #print 'Bad mime:' + mime return #print "[httpMessage] before lock" # create a new log entry with the message details self._lock.acquire() row = self._log.size() for item in self._log: if url == item._url: if method == self._helpers.analyzeRequest( item._requestResponse).getMethod(): #print 'duplicate URL+method, skipping.. ' self._lock.release() # has it been analyzed? analyzed = False if self._callbacks.getToolName(toolFlag) == "Repeater": if self.repeaterOptionButton.isSelected(): analyzed = True #print "[httpMessage] setting analyzed as true" if self.GLOBAL_HANDLER_ANALYZED: analyzed = True item._analyzed = analyzed self.paintItems(messageInfo, item) return #print "[httpMessage] before setComment" if not (isFromPassiveScan): messageInfo.setComment(SCOPE_MONITOR_COMMENT) # reached here, must be new entry analyzed = False if self._callbacks.getToolName(toolFlag) == "Repeater": if self.repeaterOptionButton.isSelected(): analyzed = True #print "[httpMessage] setting analyzed as true" if self.GLOBAL_HANDLER_ANALYZED: analyzed = True #print "[httpMessage] after comment" #print 'in httpmessage, response:' #print self._helpers.analyzeResponse(messageInfo.getResponse()) date = datetime.datetime.fromtimestamp( time.time()).strftime('%H:%M:%S %d %b %Y') entry = LogEntry(toolFlag, self._callbacks.saveBuffersToTempFiles(messageInfo), url, analyzed, date, method) #print "toolFlag: " + str(toolFlag) #print "(processHTTP) Adding URL: " + url self._log.add(entry) self._fullLog.add(entry) self.fireTableRowsInserted(row, row) self.paintItems(messageInfo, entry) self._lock.release() #print "columnCoun:" + str(self.logTable.getColumnCount()) # # extend AbstractTableModel # def paintItems(self, messageInfo, item): ''' print "in paint Items" print "mark color is: (true)" + str(self.markTestedRequestsProxy.isSelected()) print "global handler analyzed: :" + str(self.GLOBAL_HANDLER_ANALYZED) print "item analyzed should be the same ^^:" + str(item._analyzed) ''' if (self.markTestedRequestsProxy.isSelected()) and ( item._analyzed and self.GLOBAL_HANDLER_ANALYZED): messageInfo.setHighlight("green") return if self.markNotTestedRequestsProxy.isSelected() and not ( item._analyzed): messageInfo.setHighlight("red") def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 4 def getColumnName(self, columnIndex): if columnIndex == 0: return "Checked" if columnIndex == 1: return "URL" if columnIndex == 2: return "Method" if columnIndex == 3: return "Time" def getValueAt(self, rowIndex, columnIndex): logEntry = self._log.get(rowIndex) #self.setBackground(Color.GREEN) return self.returnEntry(rowIndex, columnIndex, logEntry) if self.showNewButton.isSelected() and not (logEntry._analyzed): return self.returnEntry(rowIndex, columnIndex, logEntry) elif self.showTestedButton.isSelected() and logEntry._analyzed: return self.returnEntry(rowIndex, columnIndex, logEntry) elif self.showAllButton.isSelected(): return self.returnEntry(rowIndex, columnIndex, logEntry) def returnEntry(self, rowIndex, columnIndex, entry): logEntry = self._log.get(rowIndex) if columnIndex == 0: if logEntry._analyzed: return "True" else: return "False" if columnIndex == 1: return self._helpers.urlDecode(logEntry._url) if columnIndex == 2: return logEntry._method if columnIndex == 3: return logEntry._date # return date return "" # # implement IMessageEditorController # this allows our request/response viewers to obtain details about the messages being displayed # def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): #print 'getRequest called' return self._currentlyDisplayedItem.getRequest() def getResponse(self): #print 'getResponse called: ' print self._currentlyDisplayedItem.getResponse() return self._currentlyDisplayedItem.getResponse() def exportRequest(self, entity, filename): line = str(entity._analyzed) + "," line = line + self._helpers.urlEncode(entity._url).replace( ",", "%2c") + "," # URL is encoded so we should be good line = line + entity._method + "," line = line + entity._date line = line + '\n' #print 'Exporting: "' + line + '"' return line def exportUrlEncode(self, url): return self._helpers.urlEncode(url).replace(",", "%2c") def exportState(self, filename): filename = self.selectPathText.getText() if filename == "": filename = self._callbacks.loadExtensionSetting("exportFile") print 'Empty filename, skipping export' return else: self._callbacks.saveExtensionSetting("exportFile", filename) print 'saving state to: ' + filename savedUrls = [] self._lockFile.acquire() try: with open(filename, 'r') as fr: savedEntries = fr.read().splitlines() savedUrls = [] for savedEntry in savedEntries: savedUrls.append(savedEntry.split(",")[1]) #print "savedUrls len: " + str(len(savedUrls)) #print "savedUrls:" #print savedUrls fr.close() except IOError: print "Autosaving skipped as file doesn't exist yet" with open(filename, 'a+') as f: for item in self._log: if self.exportUrlEncode(item._url) not in savedUrls: line = self.exportRequest(item, "xx") f.write(line) f.close() self._lockFile.release() return def importState(self, filename): filename = self.selectPathText.getText() if filename == "": filename = self._callbacks.loadExtensionSetting("exportFile") print 'Empty filename, skipping import' return else: self._callbacks.saveExtensionSetting("exportFile", filename) print 'loading state from: ' + filename self.STATUS = False self._lockFile.acquire() with open(filename, 'r') as f: proxy = self._callbacks.getProxyHistory() proxyItems = [] for item in proxy: if item.getComment(): if SCOPE_MONITOR_COMMENT in item.getComment(): proxyItems.append(item) print 'proxyItems has: ' + str(len(proxyItems)) # TODO - if no proxy items, sraight to import lines = f.read().splitlines() for line in lines: data = line.split(",") url = data[1] url = self._helpers.urlDecode(url) #print 'Saving: ' + url if not self._callbacks.isInScope(URL(url)): print '-- imported url not in scope, skipping.. ' continue analyzed = False if data[0] == "True": analyzed = True #print '.. simulating url search.. ' requestResponse = None for request in proxyItems: if url == self.getEndpoint(request): #print 'Match found when importing for url: ' + url requestResponse = request break self._log.add( LogEntry("", requestResponse, url, analyzed, data[3], data[2])) self._lockFile.release() print 'finished loading.. ' #print 'size: ' + str(self._log.size()) self.fireTableDataChanged() if self.startButton.getText() == MONITOR_ON_LABEL: self.STATUS = True return def autoSave(self, sc): #print 'autosaving.. lol what' if self.autoSaveOption.isSelected(): print "[" + self.getTime( ) + "] autosaving to " + self._callbacks.loadExtensionSetting( "exportFile") self.exportState("") self.SC.enter(self.AUTOSAVE_TIMEOUT, 1, self.autoSave, (self.SC, )) return def getTime(self): date = datetime.datetime.fromtimestamp( time.time()).strftime('%H:%M:%S') return date
class Process_AmcacheWithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('associateFileEntries', 'true') else: self.local_settings.setSetting('associateFileEntries', 'false') if self.checkbox1.isSelected(): self.local_settings.setSetting('programEntries', 'true') else: self.local_settings.setSetting('programEntries', 'false') if self.checkbox2.isSelected(): self.local_settings.setSetting('unassociatePrograms', 'true') else: self.local_settings.setSetting('unassociatePrograms', 'true') # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Associate File Entries", actionPerformed=self.checkBoxEvent) self.checkbox1 = JCheckBox("Program Entries", actionPerformed=self.checkBoxEvent) self.checkbox2 = JCheckBox("Unassociated Programs", actionPerformed=self.checkBoxEvent) self.panel1.add(self.checkbox) self.panel1.add(self.checkbox1) self.panel1.add(self.checkbox2) self.add(self.panel1) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getSetting('associateFileEntries') == 'true') self.checkbox1.setSelected(self.local_settings.getSetting('programEntries') == 'true') self.checkbox2.setSelected(self.local_settings.getSetting('unassociatePrograms') == 'true') # Return the settings used def getSettings(self): return self.local_settings
class Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # TODO: Update this for your UI def checkBoxEvent(self, event): if self.checkbox.isSelected(): self.local_settings.setSetting('All', 'true') else: self.local_settings.setSetting('All', 'false') if self.checkbox4.isSelected(): self.local_settings.setSetting('Other', 'true') self.local_settings.setSetting('Eventids', self.area.getText()); # self.local_settings.setFlag(False) # self.checkbox.setSelected(self.local_settings.getFlag()) else: self.local_settings.setSetting('Other', 'false') def keyPressed(self, event): self.local_settings.setArea('Eventids', self.area.getText()) # TODO: Update this for your UI def initComponents(self): self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS)) #self.setLayout(GridLayout(0,1)) self.setAlignmentX(JComponent.LEFT_ALIGNMENT) self.panel1 = JPanel() self.panel1.setLayout(BoxLayout(self.panel1, BoxLayout.Y_AXIS)) self.panel1.setAlignmentY(JComponent.LEFT_ALIGNMENT) self.checkbox = JCheckBox("Create Content View of Unique Event Id's", actionPerformed=self.checkBoxEvent) self.checkbox4 = JCheckBox("Other - Input in text area below then check this box", actionPerformed=self.checkBoxEvent) self.text1 = JLabel("*** Only run this once otherwise it adds it to the data again.") self.text2 = JLabel(" ") self.text3 = JLabel("*** Format is a comma delimited text ie: 8001, 8002") self.panel1.add(self.checkbox) self.panel1.add(self.text1) self.panel1.add(self.text2) self.panel1.add(self.checkbox4) self.panel1.add(self.text3) self.add(self.panel1) self.area = JTextArea(5,25) #self.area.addKeyListener(self) self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)) self.pane = JScrollPane() self.pane.getViewport().add(self.area) #self.pane.addKeyListener(self) #self.add(self.area) self.add(self.pane) # TODO: Update this for your UI def customizeComponents(self): self.checkbox.setSelected(self.local_settings.getSetting('All') == 'true') self.checkbox4.setSelected(self.local_settings.getSetting('Other') == 'true') self.area.setText(self.local_settings.getSetting('Eventids')) # Return the settings used def getSettings(self): return self.local_settings
class GUI_Test_SQLSettingsWithUISettingsPanel( IngestModuleIngestJobSettingsPanel): # Note, we can't use a self.settings instance variable. # Rather, self.local_settings is used. # https://wiki.python.org/jython/UserGuide#javabean-properties # Jython Introspector generates a property - 'settings' on the basis # of getSettings() defined in this class. Since only getter function # is present, it creates a read-only 'settings' property. This auto- # generated read-only property overshadows the instance-variable - # 'settings' # We get passed in a previous version of the settings so that we can # prepopulate the UI # TODO: Update this for your UI def __init__(self, settings): self.local_settings = settings self.initComponents() self.customizeComponents() # Check the checkboxs to see what actions need to be taken def checkBoxEvent(self, event): if self.Exec_Program_CB.isSelected(): self.local_settings.setSetting('Exec_Prog_Flag', 'true') self.Program_Executable_TF.setEnabled(True) self.Find_Program_Exec_BTN.setEnabled(True) else: self.local_settings.setSetting('Exec_Prog_Flag', 'false') self.Program_Executable_TF.setText("") self.Program_Executable_TF.setEnabled(False) self.Find_Program_Exec_BTN.setEnabled(False) # Check to see if there are any entries that need to be populated from the database. def check_Database_entries(self): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = os.path.join(head, "GUI_Settings.db3") try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings DB!") try: stmt = dbConn.createStatement() SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' resultSet = stmt.executeQuery(SQL_Statement) while resultSet.next(): if resultSet.getString("Setting_Name") == "Program_Exec_Name": self.Program_Executable_TF.setText( resultSet.getString("Setting_Value")) self.local_settings.setSetting( 'ExecFile', resultSet.getString("Setting_Value")) self.local_settings.setSetting('Exec_Prog_Flag', 'true') self.Exec_Program_CB.setSelected(True) self.Program_Executable_TF.setEnabled(True) self.Find_Program_Exec_BTN.setEnabled(True) self.Error_Message.setText("Settings Read successfully!") except SQLException as e: self.Error_Message.setText("Error Reading Settings Database") stmt.close() dbConn.close() # Save entries from the GUI to the database. def SaveSettings(self, e): head, tail = os.path.split(os.path.abspath(__file__)) settings_db = os.path.join(head, "GUI_Settings.db3") try: Class.forName("org.sqlite.JDBC").newInstance() dbConn = DriverManager.getConnection("jdbc:sqlite:%s" % settings_db) except SQLException as e: self.Error_Message.setText("Error Opening Settings") try: stmt = dbConn.createStatement() SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' + \ self.Program_Executable_TF.getText() + '");' resultSet = stmt.executeQuery(SQL_Statement) self.Error_Message.setText("Settings Saved") except SQLException as e: self.Error_Message.setText("Error Inserting Settings " + str(e)) stmt.close() dbConn.close() # When button to find file is clicked then open dialog to find the file and return it. def onClick(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("SQLite", ["sqlite"]) chooseFile.addChoosableFileFilter(filter) ret = chooseFile.showDialog(self.panel0, "Select SQLite") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setSetting('ExecFile', Canonical_file) self.Program_Executable_TF.setText(Canonical_file) # Create the initial data fields/layout in the UI def initComponents(self): self.panel0 = JPanel() self.rbgPanel0 = ButtonGroup() self.gbPanel0 = GridBagLayout() self.gbcPanel0 = GridBagConstraints() self.panel0.setLayout(self.gbPanel0) self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 1 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Exec_Program_CB, self.gbcPanel0) self.panel0.add(self.Exec_Program_CB) self.Program_Executable_TF = JTextField(20) self.Program_Executable_TF.setEnabled(False) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Program_Executable_TF, self.gbcPanel0) self.panel0.add(self.Program_Executable_TF) self.Find_Program_Exec_BTN = JButton("Find Exec", actionPerformed=self.onClick) self.Find_Program_Exec_BTN.setEnabled(False) self.rbgPanel0.add(self.Find_Program_Exec_BTN) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 3 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN, self.gbcPanel0) self.panel0.add(self.Find_Program_Exec_BTN) self.Blank_1 = JLabel(" ") self.Blank_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 5 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0) self.panel0.add(self.Blank_1) self.Save_Settings_BTN = JButton("Save Settings", actionPerformed=self.SaveSettings) self.Save_Settings_BTN.setEnabled(True) self.rbgPanel0.add(self.Save_Settings_BTN) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 7 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0) self.panel0.add(self.Save_Settings_BTN) self.Blank_2 = JLabel(" ") self.Blank_2.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 9 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0) self.panel0.add(self.Blank_2) self.Label_1 = JLabel("Error Message:") self.Label_1.setEnabled(True) self.gbcPanel0.gridx = 2 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0) self.panel0.add(self.Label_1) self.Error_Message = JLabel("") self.Error_Message.setEnabled(True) self.gbcPanel0.gridx = 6 self.gbcPanel0.gridy = 11 self.gbcPanel0.gridwidth = 1 self.gbcPanel0.gridheight = 1 self.gbcPanel0.fill = GridBagConstraints.BOTH self.gbcPanel0.weightx = 1 self.gbcPanel0.weighty = 0 self.gbcPanel0.anchor = GridBagConstraints.NORTH self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0) self.panel0.add(self.Error_Message) self.add(self.panel0) # Custom load any data field and initialize the values def customizeComponents(self): self.Exec_Program_CB.setSelected( self.local_settings.getSetting('Exec_Prog_Flag') == 'true') self.check_Database_entries() # Return the settings used def getSettings(self): return self.local_settings