def _onExport(control, event): component = control.getElement().getRootElement().getComponent() openDialog = JFileChooser() openDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) response = openDialog.showDialog(component, 'Export') if response == JFileChooser.APPROVE_OPTION: sf = openDialog.getSelectedFile() if sf is not None: filename = sf.getPath() if filename is not None and os.path.isdir(filename): response = JOptionPane.showOptionDialog( component, 'Existing content will be overwritten. Proceed?', 'Overwrite existing content', JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, None, ['Overwrite', 'Cancel'], 'Cancel') if response == JFileChooser.APPROVE_OPTION: exc = None try: project.export(filename) except: exc = JythonException.getCurrentException() if exc is not None: BubblePopup.popupInBubbleAdjacentTo( DefaultPerspective.instance(exc), control.getElement(), Anchor.BOTTOM, True, True)
def _show_directory_dialog(): filechooser = JFileChooser("") filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) selected = filechooser.showSaveDialog(None) if selected == JFileChooser.APPROVE_OPTION: file = filechooser.getSelectedFile() return file.getAbsolutePath()
def check_directory(path): if (os.path.lexists(path)): contents = os.listdir(path) if (contents.count("install-birch") == 0): print_console("The selected directory " + path + " does NOT contain a BIRCH installation!") message = "The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update." reload = JOptionPane.showConfirmDialog(None, message, "Input", JOptionPane.YES_NO_OPTION) if (reload == JOptionPane.NO_OPTION): print_console("User aborted install.") commonlib.shutdown() fc = JFileChooser() fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) fc.showOpenDialog(None) path = fc.getSelectedFile().getPath() check_directory(path) else: ARGS.install_dir = path print_console("The selected directory " + path + " contains a BIRCH installation, it will be updated")
def openFolderDialog(dialogTitle): from javax.swing import JFileChooser chooser = JFileChooser() chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) chooser.setDialogTitle(dialogTitle) if chooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION: return str(chooser.getSelectedFile())
def onOpenFolder(self, event): chooseFile = JFileChooser() chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); ret = chooseFile.showDialog(self, "Choose folder") if ret == JFileChooser.APPROVE_OPTION: self.faile= chooseFile.getSelectedFile() self.cbOutDir.addItem(self.faile.getPath()) self.cbOutDir.selectedItem= self.faile.getPath()
def onClick(self, e): fileChooser = JFileChooser() fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = fileChooser.showDialog(self.panel, "Choose folder") if ret == JFileChooser.APPROVE_OPTION: file = fileChooser.getSelectedFile() filename = file.getCanonicalPath() self.localSettings.setFace(filename)
def readFromTheFile(self,event): choseFile = JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); choseFile.setDialogTitle('Select The File Which Will Be Pasted') choseFile.setFileSelectionMode(JFileChooser.FILES_ONLY) returnValue = choseFile.showOpenDialog(None); if(returnValue == JFileChooser.APPROVE_OPTION): selectedFile = choseFile.getSelectedFile() file=open(selectedFile.getAbsolutePath(),"r") editedRequest = self._request[:self._position[0]]+str(file.read())+self._request[self._position[1]:] self._message[0].setRequest(self._helpers.bytesToString(editedRequest))
def openFolderDialog(dialogTitle): from javax.swing import JFileChooser chooser = JFileChooser() chooser.setMultiSelectionEnabled(True) chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) chooser.setDialogTitle(dialogTitle) if chooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION: folderPathStrings = [] for folderPath in chooser.getSelectedFiles(): folderPathStrings.append(str(folderPath)) return folderPathStrings
def chooseFolder(self, e): button = e.getSource() code = button.getActionCommand() fileChooser = JFileChooser() fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY) ret = fileChooser.showDialog(self, "Choose folder") if ret == JFileChooser.APPROVE_OPTION: ff = fileChooser.getSelectedFile() path = ff.getCanonicalPath() self.textInputs[code].text = path
def set_plugin_loc(self, event): """Attempts to load plugins from a specified location""" if self.config['Plugin Folder'] is not None: choose_plugin_location = JFileChooser(self.config['Plugin Folder']) else: choose_plugin_location = JFileChooser() choose_plugin_location.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY) choose_plugin_location.showDialog(self.tab, "Choose Folder") chosen_folder = choose_plugin_location.getSelectedFile() self.config['Plugin Folder'] = chosen_folder.getAbsolutePath() self._load_plugins(self.config['Plugin Folder'])
def actionPerformed(self, actionEvent): chooser = JFileChooser() #chooser.setCurrentDirectory(".") chooser.setDialogTitle("Choose file") chooser.setFileSelectionMode(JFileChooser.FILES_ONLY) chooser.setAcceptAllFileFilterUsed(False) if chooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION: print chooser.getCurrentDirectory() print chooser.getSelectedFile() self.field.setText(str(chooser.getSelectedFile())) else: print "No file selected"
def _onNew(hyperlink, event): component = hyperlink.getElement().getRootElement().getComponent() openDialog = JFileChooser() openDialog.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY ) response = openDialog.showDialog( component, 'Choose path' ) if response == JFileChooser.APPROVE_OPTION: sf = openDialog.getSelectedFile() if sf is not None: filename = sf.getPath() if filename is not None and os.path.isdir( filename ): pathList.append( filename ) self._incr.onChanged()
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 new_home_page(): openDialog = JFileChooser() openDialog.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY ) openDialog.setDialogTitle('Choose directory to search for Mallard .page files') response = openDialog.showDialog( None, 'Choose' ) if response == JFileChooser.APPROVE_OPTION: sf = openDialog.getSelectedFile() if sf is not None: filename = sf.getPath() if filename is not None and os.path.isdir( filename ): return HomePage(filename) return HomePage('.')
def get_source_input(self, event): """Sets the source dir/file for parsing""" source_chooser = JFileChooser() source_chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES) source_chooser.showDialog(self.tab, "Choose Source Location") chosen_source = source_chooser.getSelectedFile() try: self.source_input = chosen_source.getAbsolutePath() except AttributeError: pass if self.source_input is not None: self.update_scroll("[*] Source location: %s" % self.source_input) self.curr_conf.setText(self.source_input)
def showFC(self, event): Type = 'Open,Save,Custom'.split(',') Answer = 'Error,Approve,Cancel'.split(',') fc = JFileChooser() fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) result = fc.showOpenDialog(None) if result == JFileChooser.APPROVE_OPTION: message = 'result = "%s"' % fc.getSelectedFile() self.directory = fc.getSelectedFile() print(self.directory) print(type(self.directory)) else: message = 'Request canceled by user' self.label.setText(message)
def Find_Plaso_Dir(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("All", ["*.*"]) chooseFile.addChoosableFileFilter(filter) chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = chooseFile.showDialog(self.panel0, "Find Plaso Directory") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setSetting('Plaso_Directory', Canonical_file) self.Program_Executable_TF.setText(Canonical_file)
def browse(self, event=None): ''' Open new dialog for the user to select a path as default working dir. ''' default_path = self.wd_field.getText() if not os.path.isdir(default_path): default_path = os.getcwd() fileChooser = JFileChooser(default_path) fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) # Fixed showDialog bug using showOpenDialog instead. The former was # duplicating the last folder name in the path due to a Java bug in # OSX in the implementation of JFileChooser! status = fileChooser.showOpenDialog(self) if status == JFileChooser.APPROVE_OPTION: self.wd_field.setText(fileChooser.getSelectedFile().toString())
def browse(self, event=None): ''' Open new dialog for the user to select a path as default working dir. ''' default_path = self.field.getText() if not os.path.isdir(default_path): default_path = os.getcwd() fileChooser = JFileChooser(default_path) fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) # Fixed showDialog bug using showOpenDialog instead. The former was # duplicating the last folder name in the path due to a Java bug in # OSX in the implementation of JFileChooser! status = fileChooser.showOpenDialog(self) if status == JFileChooser.APPROVE_OPTION: self.field.setText(fileChooser.getSelectedFile().toString())
def Find_Plaso_Dir(self, e): chooseFile = JFileChooser() filter = FileNameExtensionFilter("All", ["*.*"]) chooseFile.addChoosableFileFilter(filter) chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = chooseFile.showDialog(self.panel0, "Find Plaso Directory") if ret == JFileChooser.APPROVE_OPTION: file = chooseFile.getSelectedFile() Canonical_file = file.getCanonicalPath() #text = self.readPath(file) self.local_settings.setPlaso_Directory(Canonical_file) self.Program_Executable_TF.setText(Canonical_file)
def initUI(self): self.panel = JPanel() self.panel.setLayout(BorderLayout()) chooseFile = JFileChooser() chooseFile.setDialogTitle("Select Export Location") chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) ret = chooseFile.showSaveDialog(self.panel) if ret == JFileChooser.APPROVE_OPTION: self.file_name = str(chooseFile.getSelectedFile()) if not chooseFile.getSelectedFile().isDirectory(): mkdirp(self.file_name)
def openGVL(): from javax.swing import JFileChooser GUIUtil=PluginServices.getPluginServices("com.iver.cit.gvsig.cad").getClassLoader().loadClass("com.iver.cit.gvsig.gui.GUIUtil") chooser = JFileChooser() chooser.setFileFilter(GUIUtil().createFileFilter("GVL Legend File",["gvl"])) from java.util.prefs import Preferences lastPath = Preferences.userRoot().node("gvsig.foldering").get("DataFolder", "null") chooser.setCurrentDirectory(File(lastPath)) chooser.setFileSelectionMode(JFileChooser.FILES_ONLY) returnVal = chooser.showOpenDialog(None) if returnVal == chooser.APPROVE_OPTION: gvlPath = chooser.getSelectedFile().getPath() elif returnVal == chooser.CANCEL_OPTION: JOptionPane.showMessageDialog(None, "You have to open a .gvl file. Retry!","Batch Legend",JOptionPane.WARNING_MESSAGE) gvlPath = "" return gvlPath
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 f4_clic_browse1(event): print("Click browse 1") fc = JFileChooser() fc.setCurrentDirectory(gvars['path_JFileChooser']) fc.setDialogTitle('Select Directory for multiple images') fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) result = fc.showOpenDialog( None ) if result == JFileChooser.APPROVE_OPTION : if fc.getSelectedFile().isDirectory(): message = 'Path to original image %s' % fc.getSelectedFile() gvars['path_multiple_image_directory'] = str(fc.getSelectedFile()) f4_txt1.setText(gvars['path_multiple_image_directory']) gvars['path_JFileChooser'] = fc.getSelectedFile() else : message = 'Request canceled by user' print( message )
def initUI(self, hidden, dir_only, title, defaultFile): self.panel = JPanel() self.panel.setLayout(BorderLayout()) chosenFile = JFileChooser() chosenFile.setSelectedFile(File(defaultFile)) chosenFile.setDialogTitle(title) if dir_only: chosenFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) chosenFile.setFileHidingEnabled(hidden) ret = chosenFile.showOpenDialog(self.panel) if ret == JFileChooser.APPROVE_OPTION: if dir_only: if chosenFile.getSelectedFile().isDirectory(): self.file_name = str(chosenFile.getSelectedFile()) else: self.file_name = str(chosenFile.getSelectedFile())
def FolderDialog(title, folder): fc = JFileChooser() fc.setMultiSelectionEnabled(False) fc.setDialogTitle(title) fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setAcceptAllFileFilterUsed(False); if folder ==None: sdir = OpenDialog.getDefaultDirectory() else: sdir = folder if sdir!=None: fdir = File(sdir) if fdir!=None: fc.setCurrentDirectory(fdir) returnVal = fc.showOpenDialog(IJ.getInstance()) if returnVal!=JFileChooser.APPROVE_OPTION: return folder = fc.getSelectedFile(); path = os.path.join(folder.getParent(), folder.getName()) return path
def actionPerformed(self, actionEvent): global yara_rules global yara_path if actionEvent.getSource() is self.menuItem: yara_path = self._yara_exe_txtField.getText() yara_rules = self._yara_rules_files t = Thread(self) t.start() elif actionEvent.getSource() is self._yara_clear_button: # Delete the LogEntry objects from the log row = self._log.size() self._lock.acquire() self._log.clear() # Update the Table self.fireTableRowsDeleted(0, row) # Clear data regarding any selected LogEntry objects from the request / response viewers self._requestViewer.setMessage([], True) self._responseViewer.setMessage([], False) self._currentlyDisplayedItem = None self._lock.release() elif actionEvent.getSource() is self._yara_rules_select_files_button: fileChooser = JFileChooser() yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"]) fileChooser.addChoosableFileFilter(yarFilter) fileChooser.setFileFilter(yarFilter) fileChooser.setMultiSelectionEnabled(True) fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY) ret = fileChooser.showOpenDialog(None) if ret == JFileChooser.APPROVE_OPTION: self._yara_rules_files.clear() for file in fileChooser.getSelectedFiles(): self._yara_rules_files.add(file.getPath()) self._yara_rules_fileList.setListData(self._yara_rules_files) else: stdout.println("Unknown Event Received.")
def check_directory(path): if (os.path.lexists(path)): contents=os.listdir(path) if (contents.count("install-birch")==0): print_console("The selected directory "+path+" does NOT contain a BIRCH installation!") message="The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update." reload = JOptionPane.showConfirmDialog(None,message, "Input",JOptionPane.YES_NO_OPTION); if (reload==JOptionPane.NO_OPTION): print_console("User aborted install.") commonlib.shutdown() fc = JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.showOpenDialog(None); path = fc.getSelectedFile().getPath(); check_directory(path) else: ARGS.install_dir=path print_console("The selected directory "+path+" contains a BIRCH installation, it will be updated")
class BurpExtender(IBurpExtender, ITab, IProxyListener): def exec_module(self, messageIsRequest=0, message=None): module_path = M_PATH if M_PATH else str( self.fc.getSelectedFile()) + "/" sys.meta_path = [ moduleImporter(module_path, messageIsRequest, message) ] modules = [m[1] for m in self.dataModel.getDataVector() if m[0]] #modules = os.listdir(module_path) for module in modules: module_name = module[:-3] if module[-3:] == ".py" else module exec("import " + module_name) return sys.meta_path[0].message def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("Module Importer") self.out = callbacks.getStdout() self.tab = JPanel(GridBagLayout()) self.tableData = [] colNames = ('Enabled', 'Module') self.dataModel = MyTableModel(self.tableData, colNames) self.table = JTable(self.dataModel) self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 4 c.gridheight = 6 c.gridwidth = 6 c.weightx = 0.6 c.weighty = 0.5 self.tab.add(self.tablecont, c) self.fc = JFileChooser() self.fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) label_for_openDirectory = JLabel("Module Importer") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 self.tab.add(label_for_openDirectory, c) label_plugin_desc = JLabel( "This module makes your development of Burp Suite Plugin easier.") label_plugin_desc.setPreferredSize(Dimension(400, 50)) c = GridBagConstraints() c.gridx = 0 c.gridy = 1 self.tab.add(label_plugin_desc, c) label_for_openDirectory = JLabel("Module Path:") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 2 self.tab.add(label_for_openDirectory, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 3 self.input_id = JTextField(40) self.input_id.setEditable(java.lang.Boolean.FALSE) self.tab.add(self.input_id, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 3 self.openButton = JButton("Open Directory", actionPerformed=self.openDialog) self.tab.add(self.openButton, c) if M_PATH: self.set_fixed_module_path() #callbacks.customizeUiComponent(self.tab) #callbacks.customizeUiComponent(self.table) #callbacks.customizeUiComponent(self.tablecont) callbacks.addSuiteTab(self) callbacks.registerProxyListener(self) return def getTabCaption(self): return ("ModuleImporter") def getUiComponent(self): return self.tab def openDialog(self, e): returnVal = self.fc.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: self.dataModel.setRowCount(0) self.input_id.text = str(self.fc.getSelectedFile()) modules = os.listdir(self.input_id.text) for module in modules: M_VALUABLES[module[:-3]] = {} if module.split('.')[-1] == "py": table_list = [java.lang.Boolean.TRUE, module] self.dataModel.insertRow(0, table_list) else: print("Open command cancelled by user.\n") def set_fixed_module_path(self): self.input_id.text = M_PATH modules = os.listdir(self.input_id.text) for module in modules: M_VALUABLES[module[:-3]] = {} if module.split('.')[-1] == "py": table_list = [java.lang.Boolean.TRUE, module] self.dataModel.insertRow(0, table_list) def processProxyMessage(self, messageIsRequest, message): if messageIsRequest: request = message.getMessageInfo().getRequest() readabled = self._helpers.bytesToString(request) modified_string_message = self.exec_module(messageIsRequest, readabled) modified_byte_message = self._helpers.stringToBytes( modified_string_message) message.getMessageInfo().setRequest(modified_byte_message) else: response = message.getMessageInfo().getResponse() readabled = self._helpers.bytesToString(response) modified_string_message = self.exec_module(messageIsRequest, readabled) modified_byte_message = self._helpers.stringToBytes( modified_string_message) message.getMessageInfo().setResponse(modified_byte_message)
class BurpExtender(IBurpExtender, IMessageEditorTabFactory, ITab, IExtensionStateListener): EXTENSION_NAME = "Protobuf Editor" def __init__(self): self.descriptors = OrderedDict() self.chooser = JFileChooser() self.chooser.addChoosableFileFilter(PROTO_FILENAME_EXTENSION_FILTER) self.chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES) self.chooser.setMultiSelectionEnabled(True) def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() self.enabled = False try: process = subprocess.Popen(['protoc', '--version'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() self.enabled = output.startswith('libprotoc') if error: raise RuntimeError(error) except (OSError, RuntimeError) as error: self.callbacks.getStderr().write( "Error calling protoc: %s\n" % (error.message, )) if not self.enabled: return rules = [] saved_rules = callbacks.loadExtensionSetting('rules') if saved_rules: rules = json.loads(base64.b64decode(saved_rules)) # For checkboxes to be rendered in a table model, the # type has to be java.lang.Boolean, not a Python bool. for rule in rules: rule[-1] = Boolean(rule[-1]) self.table = ParameterProcessingRulesTable(self, *rules) callbacks.setExtensionName(self.EXTENSION_NAME) callbacks.registerExtensionStateListener(self) callbacks.registerMessageEditorTabFactory(self) callbacks.addSuiteTab(self) return def createNewInstance(self, controller, editable): return ProtobufEditorTab(self, controller, editable) def getTabCaption(self): return self.EXTENSION_NAME def getUiComponent(self): return self.table def extensionUnloaded(self): if not self.table.rules: return rules = self.table.rules # The default JSONENcoder cannot dump a java.lang.Boolean type, # so convert it to a Python bool. (We'll have to change it back # when loading the rules again. for rule in rules: rule[-1] = bool(rule[-1]) self.callbacks.saveExtensionSetting( 'rules', base64.b64encode(json.dumps(rules))) return
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory): def registerExtenderCallbacks(self, callbacks): # keep a reference to our callbacks object self._callbacks = callbacks # obtain an extension helpers object self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("PT Vulnerabilities Manager") self.config = SafeConfigParser() self.createSection('projects') self.createSection('general') self.config.read('config.ini') self.chooser = JFileChooser() # create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._lock = Lock() self.logTable = Table(self) self.logTable.getColumnModel().getColumn(0).setMaxWidth(35) self.logTable.getColumnModel().getColumn(1).setMinWidth(100) self._requestViewer = self._callbacks.createMessageEditor(self, False) self._responseViewer = self._callbacks.createMessageEditor(self, False) self.initVulnerabilityTab() self.initProjSettingsTab() self.initTabs() self.initCallbacks() if self.projPath.getText() != None: self.loadVulnerabilities(self.projPath.getText()) print "Thank you for installing PT Vulnerabilities Manager v1.0 extension" print "by Barak Tawily\n\n\n" print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition" return def initVulnerabilityTab(self): # ## init vulnerability tab # nameLabel = JLabel("Vulnerability Name:") nameLabel.setBounds(10, 10, 140, 30) self.addButton = JButton("Add",actionPerformed=self.addVuln) self.addButton.setBounds(10, 500, 100, 30) rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln) rmVulnButton.setBounds(465, 500, 100, 30) mitigationLabel = JLabel("Mitigation:") mitigationLabel.setBounds(10, 290, 150, 30) addSSBtn = JButton("Add SS",actionPerformed=self.addSS) addSSBtn.setBounds(750, 40, 110, 30) deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS) deleteSSBtn.setBounds(750, 75, 110, 30) piclistLabel = JLabel("Images list:") piclistLabel.setBounds(580, 10, 140, 30) self.screenshotsList = DefaultListModel() self.ssList = JList(self.screenshotsList) self.ssList.setBounds(580, 40, 150, 250) self.ssList.addListSelectionListener(ssChangedHandler(self)) self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY)) previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)") previewPicLabel.setBounds(580, 290, 500, 30) copyImgMenu = JMenuItem("Copy") copyImgMenu.addActionListener(copyImg(self)) self.imgMenu = JPopupMenu("Popup") self.imgMenu.add(copyImgMenu) self.firstPic = JLabel() self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY)) self.firstPic.setBounds(580, 320, 550, 400) self.firstPic.addMouseListener(imageClicked(self)) self.vulnName = JTextField("") self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self)) self.vulnName.setBounds(140, 10, 422, 30) sevirities = ["Unclassified", "Critical","High","Medium","Low"] self.threatLevel = JComboBox(sevirities); self.threatLevel.setBounds(140, 45, 140, 30) colors = ["Color:", "Green", "Red"] self.colorCombo = JComboBox(colors); self.colorCombo.setBounds(465, 45, 100, 30) self.colorCombo severityLabel = JLabel("Threat Level:") severityLabel.setBounds(10, 45, 100, 30) descriptionLabel = JLabel("Description:") descriptionLabel.setBounds(10, 80, 100, 30) self.descriptionString = JTextArea("", 5, 30) self.descriptionString.setWrapStyleWord(True); self.descriptionString.setLineWrap(True) self.descriptionString.setBounds(10, 110, 555, 175) descriptionStringScroll = JScrollPane(self.descriptionString) descriptionStringScroll.setBounds(10, 110, 555, 175) descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.mitigationStr = JTextArea("", 5, 30) self.mitigationStr.setWrapStyleWord(True); self.mitigationStr.setLineWrap(True) self.mitigationStr.setBounds(10, 320, 555, 175) mitigationStrScroll = JScrollPane(self.mitigationStr) mitigationStrScroll.setBounds(10, 320, 555, 175) mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) self.pnl = JPanel() self.pnl.setBounds(0, 0, 1000, 1000); self.pnl.setLayout(None); self.pnl.add(addSSBtn) self.pnl.add(piclistLabel) self.pnl.add(nameLabel) self.pnl.add(deleteSSBtn) self.pnl.add(rmVulnButton) self.pnl.add(severityLabel) self.pnl.add(mitigationLabel) self.pnl.add(descriptionLabel) self.pnl.add(previewPicLabel) self.pnl.add(mitigationStrScroll) self.pnl.add(descriptionStringScroll) self.pnl.add(self.ssList) self.pnl.add(self.firstPic) self.pnl.add(self.addButton) self.pnl.add(self.vulnName) self.pnl.add(self.threatLevel) self.pnl.add(self.colorCombo) def initProjSettingsTab(self): # init project settings projNameLabel = JLabel("Name:") projNameLabel.setBounds(10, 50, 140, 30) self.projName = JTextField("") self.projName.setBounds(140, 50, 320, 30) self.projName.getDocument().addDocumentListener(projTextChanged(self)) detailsLabel = JLabel("Details:") detailsLabel.setBounds(10, 120, 140, 30) reportLabel = JLabel("Generate Report:") reportLabel.setBounds(10, 375, 140, 30) types = ["DOCX","HTML","XLSX"] self.reportType = JComboBox(types) self.reportType.setBounds(10, 400, 140, 30) generateReportButton = JButton("Generate", actionPerformed=self.generateReport) generateReportButton.setBounds(160, 400, 90, 30) self.projDetails = JTextArea("", 5, 30) self.projDetails.setWrapStyleWord(True); self.projDetails.setLineWrap(True) projDetailsScroll = JScrollPane(self.projDetails) projDetailsScroll.setBounds(10, 150, 450, 175) projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED) projPathLabel = JLabel("Path:") projPathLabel.setBounds(10, 90, 140, 30) self.projPath = JTextField("") self.projPath.setBounds(140, 90, 320, 30) chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath) chooseProjPathButton.setBounds(470, 90, 100, 30) importProjButton = JButton("Import",actionPerformed=self.importProj) importProjButton.setBounds(470, 10, 100, 30) exportProjButton = JButton("Export",actionPerformed=self.exportProj) exportProjButton.setBounds(575, 10, 100, 30) openProjButton = JButton("Open Directory",actionPerformed=self.openProj) openProjButton.setBounds(680, 10, 130, 30) currentProjectLabel = JLabel("Current:") currentProjectLabel.setBounds(10, 10, 140, 30) projects = self.config.options('projects') self.currentProject = JComboBox(projects) self.currentProject.addActionListener(projectChangeHandler(self)) self.currentProject.setBounds(140, 10, 140, 30) self.autoSave = JCheckBox("Auto Save Mode") self.autoSave.setEnabled(False) # implement this feature self.autoSave.setBounds(300, 10, 140, 30) self.autoSave.setToolTipText("Will save any changed value while focus is out") addProjButton = JButton("Add / Update",actionPerformed=self.addProj) addProjButton.setBounds(10, 330, 150, 30) removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj) removeProjButton.setBounds(315, 330, 146, 30) generalOptions = self.config.options('general') if 'default project' in generalOptions: defaultProj = self.config.get('general','default project') self.currentProject.getModel().setSelectedItem(defaultProj) self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem())) self.clearProjTab = True self.projectSettings = JPanel() self.projectSettings.setBounds(0, 0, 1000, 1000) self.projectSettings.setLayout(None) self.projectSettings.add(reportLabel) self.projectSettings.add(detailsLabel) self.projectSettings.add(projPathLabel) self.projectSettings.add(addProjButton) self.projectSettings.add(openProjButton) self.projectSettings.add(projNameLabel) self.projectSettings.add(projDetailsScroll) self.projectSettings.add(importProjButton) self.projectSettings.add(exportProjButton) self.projectSettings.add(removeProjButton) self.projectSettings.add(generateReportButton) self.projectSettings.add(chooseProjPathButton) self.projectSettings.add(currentProjectLabel) self.projectSettings.add(self.projPath) self.projectSettings.add(self.autoSave) self.projectSettings.add(self.projName) self.projectSettings.add(self.reportType) self.projectSettings.add(self.currentProject) def initTabs(self): # ## init autorize tabs # self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) self.scrollPane = JScrollPane(self.logTable) self._splitpane.setLeftComponent(self.scrollPane) colorsMenu = JMenu("Paint") redMenu = JMenuItem("Red") noneMenu = JMenuItem("None") greenMenu = JMenuItem("Green") redMenu.addActionListener(paintChange(self, "Red")) noneMenu.addActionListener(paintChange(self, None)) greenMenu.addActionListener(paintChange(self, "Green")) colorsMenu.add(redMenu) colorsMenu.add(noneMenu) colorsMenu.add(greenMenu) self.menu = JPopupMenu("Popup") self.menu.add(colorsMenu) self.tabs = JTabbedPane() self.tabs.addTab("Request", self._requestViewer.getComponent()) self.tabs.addTab("Response", self._responseViewer.getComponent()) self.tabs.addTab("Vulnerability", self.pnl) self.tabs.addTab("Project Settings", self.projectSettings) self.tabs.setSelectedIndex(2) self._splitpane.setRightComponent(self.tabs) def initCallbacks(self): # ## init callbacks # # customize our UI components self._callbacks.customizeUiComponent(self._splitpane) self._callbacks.customizeUiComponent(self.logTable) self._callbacks.customizeUiComponent(self.scrollPane) self._callbacks.customizeUiComponent(self.tabs) self._callbacks.registerContextMenuFactory(self) # add the custom tab to Burp's UI self._callbacks.addSuiteTab(self) def loadVulnerabilities(self, projPath): self.clearList(None) selected = False for root, dirs, files in os.walk(projPath): # make it go only for dirs for dirName in dirs: xmlPath = projPath+"/"+dirName+"/vulnerability.xml" # xmlPath = xmlPath.replace("/","//") document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() vulnName = nodeList.item(0).getTextContent() severity = nodeList.item(1).getTextContent() description = nodeList.item(2).getTextContent() mitigation = nodeList.item(3).getTextContent() color = nodeList.item(4).getTextContent() test = vulnerability(vulnName,severity,description,mitigation,color) self._lock.acquire() row = self._log.size() self._log.add(test) self.fireTableRowsInserted(row, row) self._lock.release() if vulnName == self.vulnName.getText(): self.logTable.setRowSelectionInterval(row,row) selected = True if selected == False and self._log.size() > 0: self.logTable.setRowSelectionInterval(0, 0) self.loadVulnerability(self._log.get(0)) def createSection(self, sectioName): self.config.read('config.ini') if not (sectioName in self.config.sections()): self.config.add_section(sectioName) cfgfile = open("config.ini",'w') self.config.write(cfgfile) cfgfile.close() def saveCfg(self): f = open('config.ini', 'w') self.config.write(f) f.close() def getXMLDoc(self, xmlPath): try: document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath) return document except: self._extender.popup("XML file not found") return def saveXMLDoc(self, doc, xmlPath): transformerFactory = TransformerFactory.newInstance() transformer = transformerFactory.newTransformer() source = DOMSource(doc) result = StreamResult(File(xmlPath)) transformer.transform(source, result) def generateReport(self,event): if self.reportType.getSelectedItem() == "HTML": path = self.reportToHTML() if self.reportType.getSelectedItem() == "XLSX": path = self.reportToXLS() if self.reportType.getSelectedItem() == "DOCX": path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml') n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION) if n == JOptionPane.YES_OPTION: os.system('"' + path + '"') # Bug! stucking burp until the file get closed def exportProj(self,event): self.chooser.setDialogTitle("Save project") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showSaveDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: dst = str(self.chooser.getSelectedFile()) shutil.make_archive(dst,"zip",self.getCurrentProjPath()) self.popup("Project export successfuly") def importProj(self,event): self.chooser.setDialogTitle("Select project zip to directory") Ffilter = FileNameExtensionFilter("Zip files", ["zip"]) self.chooser.setFileFilter(Ffilter) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: zipPath = str(self.chooser.getSelectedFile()) self.chooser.setDialogTitle("Select project directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" with zipfile.ZipFile(zipPath, "r") as z: z.extractall(projPath) xmlPath = projPath + "/project.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() projName = nodeList.item(0).getTextContent() nodeList.item(1).setTextContent(projPath) self.saveXMLDoc(document, xmlPath) self.config.set('projects', projName, projPath) self.saveCfg() self.reloadProjects() self.currentProject.getModel().setSelectedItem(projName) self.clearVulnerabilityTab() def reportToXLS(self): if not xlsxwriterImported: self.popup("xlsxwriter library is not imported") return workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx') worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': True}) worksheet.write(0, 0, "Vulnerability Name", bold) worksheet.write(0, 1, "Threat Level", bold) worksheet.write(0, 2, "Description", bold) worksheet.write(0, 3, "Mitigation", bold) row = 1 for i in range(0,self._log.size()): worksheet.write(row, 0, self._log.get(i).getName()) worksheet.write(row, 1, self._log.get(i).getSeverity()) worksheet.write(row, 2, self._log.get(i).getDescription()) worksheet.write(row, 3, self._log.get(i).getMitigation()) row = row + 1 # add requests and images as well workbook.close() return self.getCurrentProjPath() + '/PT Manager Report.xlsx' def reportToHTML(self): htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr"> <head> <title>PT Manager Report</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style> body { background-repeat: no-repeat; background-attachment: fixed; font-family: Arial,Tahoma,sens-serif; font-size: 13px; margin: auto; } #warpcenter { width: 900px; margin: 0px auto; } table { border: 2px dashed #000000; } td { border-top: 2px dashed #000000; padding: 10px; } img { border: 0px; } </style> <script language="javascript"> function divHideShow(divToHideOrShow) { var div = document.getElementById(divToHideOrShow); if (div.style.display == "block") { div.style.display = "none"; } else { div.style.display = "block"; } } </script> </head> <body> <div id="warpcenter"> <h1> PT Manager Report </h1> <h2> Project: %s</h1> """ % (self.projName.getText()) for i in range(0,self._log.size()): name = self._log.get(i).getName() request = "None" response = "None" path = self.getVulnReqResPath("request",name) if os.path.exists(path): request = self.newlineToBR(self.getFileContent(path)) path = self.getVulnReqResPath("response",name) if os.path.exists(path): response = self.newlineToBR(self.getFileContent(path)) images = "" for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)): if fileName.endswith(".jpg"): images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName) description = self.newlineToBR(self._log.get(i).getDescription()) mitigation = self.newlineToBR(self._log.get(i).getMitigation()) htmlContent += self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images) htmlContent += "</div></body></html>" f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w') f.writelines(htmlContent) f.close() return self.getCurrentProjPath() + '/PT Manager Report.html' def newlineToBR(self,string): return "<br />".join(string.split("\n")) def getFileContent(self,path): f = open(path, "rb") content = f.read() f.close() return content def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"): return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div> <div id="Table_%s" style="display: none;"> <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;"> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Threat Level: </span> <span style="color:#8b8989">%s</span> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Description</span> <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;"> %s </div> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Mitigration</span> <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Request</span> <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Response</span> <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> <tr> <td> <div style="font-size: 16px;font-weight: bold;"> <span style="color:#000000">Images</span> <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a> </div> <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;"> %s <b> </td> </tr> </table> </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images) def clearVulnerabilityTab(self, rmVuln=True): if rmVuln: self.vulnName.setText("") self.descriptionString.setText("") self.mitigationStr.setText("") self.colorCombo.setSelectedIndex(0) self.threatLevel.setSelectedIndex(0) self.screenshotsList.clear() self.addButton.setText("Add") self.firstPic.setIcon(None) def saveRequestResponse(self, type, requestResponse, vulnName): path = self.getVulnReqResPath(type,vulnName) f = open(path, 'wb') f.write(requestResponse) f.close() def openProj(self, event): os.system('explorer ' + self.projPath.getText()) def getVulnReqResPath(self, requestOrResponse, vulnName): return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName) def htmlEscape(self,data): return data.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') def generateReportFromDocxTemplate(self, zipname, newZipName, filename): newZipName = self.getCurrentProjPath() + "/" + newZipName with zipfile.ZipFile(zipname, 'r') as zin: with zipfile.ZipFile(newZipName, 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): if item.filename != filename: zout.writestr(item, zin.read(item.filename)) else: xml_content = zin.read(item.filename) result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0] newXML = result[0] templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0] newBody = "" for i in range(0,self._log.size()): tmp = templateBody tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName())) tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity())) tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription())) tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation())) newBody = newBody + tmp newXML = newXML + newBody newXML = newXML + result[1] with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(filename, newXML) return newZipName def chooseProjPath(self, event): self.chooser.setDialogTitle("Select target directory") self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) returnVal = self.chooser.showOpenDialog(None) if returnVal == JFileChooser.APPROVE_OPTION: projPath = str(self.chooser.getSelectedFile()) + "/PTManager" os.makedirs(projPath) self.projPath.setText(projPath) def reloadProjects(self): self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects'))) def rmProj(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.projPath.getText()) self.config.remove_option('projects',self.currentProject.getSelectedItem()) self.reloadProjects() self.currentProject.setSelectedIndex(0) self.loadVulnerabilities(self.projPath.getText()) def popup(self,msg): JOptionPane.showMessageDialog(None,msg) def addProj(self, event): projPath = self.projPath.getText() if projPath == None or projPath == "": self.popup("Please select path") return self.config.set('projects', self.projName.getText(), projPath) self.saveCfg() xml = ET.Element('project') name = ET.SubElement(xml, "name") path = ET.SubElement(xml, "path") details = ET.SubElement(xml, "details") autoSaveMode = ET.SubElement(xml, "autoSaveMode") name.text = self.projName.getText() path.text = projPath details.text = self.projDetails.getText() autoSaveMode.text = str(self.autoSave.isSelected()) tree = ET.ElementTree(xml) try: tree.write(self.getCurrentProjPath()+'/project.xml') except: self.popup("Invalid path") return self.reloadProjects() self.clearVulnerabilityTab() self.clearList(None) self.currentProject.getModel().setSelectedItem(self.projName.getText()) def resize(self, image, width, height): bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT) g2d = bi.createGraphics() g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)) g2d.drawImage(image, 0, 0, width, height, None) g2d.dispose() return bi; def clearStr(self, var): return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "") def popUpAreYouSure(self): dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION) if dialogResult == 0: return 0 return 1 def removeSS(self,event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue()) self.ssList.getModel().remove(self.ssList.getSelectedIndex()) self.firstPic.setIcon(ImageIcon(None)) # check if there is images and select the first one # bug in linux def addSS(self,event): clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() try: image = clipboard.getData(DataFlavor.imageFlavor) except: self.popup("Clipboard not contains image") return vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg" fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name file = File(fileName) bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB); g = bufferedImage.createGraphics(); g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None); ImageIO.write(bufferedImage, "jpg", file) self.addVuln(self) self.ssList.setSelectedValue(name,True) def rmVuln(self, event): if self.popUpAreYouSure() == JOptionPane.YES_OPTION: self._requestViewer.setMessage("None", False) self._responseViewer.setMessage("None", False) shutil.rmtree(self.getCurrentVulnPath()) self.clearVulnerabilityTab() self.loadVulnerabilities(self.getCurrentProjPath()) def addVuln(self, event): if self.colorCombo.getSelectedItem() == "Color:": colorTxt = None else: colorTxt = self.colorCombo.getSelectedItem() self._lock.acquire() row = self._log.size() vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt) self._log.add(vulnObject) self.fireTableRowsInserted(row, row) self._lock.release() vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) xml = ET.Element('vulnerability') name = ET.SubElement(xml, "name") severity = ET.SubElement(xml, "severity") description = ET.SubElement(xml, "description") mitigation = ET.SubElement(xml, "mitigation") color = ET.SubElement(xml, "color") name.text = self.vulnName.getText() severity.text = self.threatLevel.getSelectedItem() description.text = self.descriptionString.getText() mitigation.text = self.mitigationStr.getText() color.text = colorTxt tree = ET.ElementTree(xml) tree.write(vulnPath+'/vulnerability.xml') self.loadVulnerabilities(self.getCurrentProjPath()) self.loadVulnerability(vulnObject) def vulnNameChanged(self): if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "": self.addButton.setText("Update") elif self.addButton.getText() != "Add": options = ["Create a new vulnerability", "Change current vulnerability name"] n = JOptionPane.showOptionDialog(None, "Would you like to?", "Vulnerability Name", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, None, options, options[0]); if n == 0: self.clearVulnerabilityTab(False) self.addButton.setText("Add") else: newName = JOptionPane.showInputDialog( None, "Enter new name:", "Vulnerability Name", JOptionPane.PLAIN_MESSAGE, None, None, self.vulnName.getText()) row = self.logTable.getSelectedRow() old = self.logTable.getValueAt(row,1) self.changeVulnName(newName,old) def changeVulnName(self,new,old): newpath = self.getCurrentProjPath() + "/" + new oldpath = self.getCurrentProjPath() + "/" + old os.rename(oldpath,newpath) self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml") def getCurrentVulnPath(self): return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) def getCurrentProjPath(self): return self.projPath.getText() def loadSS(self, imgPath): image = ImageIO.read(File(imgPath)) if image.getWidth() <= 550 and image.getHeight() <= 400: self.firstPic.setIcon(ImageIcon(image)) self.firstPic.setSize(image.getWidth(),image.getHeight()) else: self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400))) self.firstPic.setSize(550,400) def clearProjectTab(self): self.projPath.setText("") self.projDetails.setText("") def clearList(self, event): self._lock.acquire() self._log = ArrayList() row = self._log.size() self.fireTableRowsInserted(row, row) self._lock.release() # # implement IContextMenuFactory # def createMenuItems(self, invocation): responses = invocation.getSelectedMessages(); if responses > 0: ret = LinkedList() requestMenuItem = JMenuItem("Send to PT Manager"); requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request")) ret.add(requestMenuItem); return(ret); return null; # # implement ITab # def getTabCaption(self): return "PT Manager" def getUiComponent(self): return self._splitpane # # extend AbstractTableModel # def getRowCount(self): try: return self._log.size() except: return 0 def getColumnCount(self): return 3 def getColumnName(self, columnIndex): if columnIndex == 0: return "#" if columnIndex == 1: return "Vulnerability Name" if columnIndex == 2: return "Threat Level" return "" def getValueAt(self, rowIndex, columnIndex): vulnObject = self._log.get(rowIndex) if columnIndex == 0: return rowIndex+1 if columnIndex == 1: return vulnObject.getName() if columnIndex == 2: return vulnObject.getSeverity() if columnIndex == 3: return vulnObject.getMitigation() if columnIndex == 4: return vulnObject.getColor() return "" def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"): if xmlPath == "def": xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml" document = self.getXMLDoc(xmlPath) nodeList = document.getDocumentElement().getChildNodes() nodeList.item(fieldNumber).setTextContent(value) self.saveXMLDoc(document, xmlPath) self.loadVulnerabilities(self.getCurrentProjPath()) def loadVulnerability(self, vulnObject): self.addButton.setText("Update") self.vulnName.setText(vulnObject.getName()) self.threatLevel.setSelectedItem(vulnObject.getSeverity()) self.descriptionString.setText(vulnObject.getDescription()) self.mitigationStr.setText(vulnObject.getMitigation()) if vulnObject.getColor() == "" or vulnObject.getColor() == None: self.colorCombo.setSelectedItem("Color:") else: self.colorCombo.setSelectedItem(vulnObject.getColor()) self.screenshotsList.clear() for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())): if fileName.endswith(".jpg"): self.screenshotsList.addElement(fileName) imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName # imgPath = imgPath.replace("/","//") self.loadSS(imgPath) if (self.screenshotsList.getSize() == 0): self.firstPic.setIcon(None) else: self.ssList.setSelectedIndex(0) path = self.getVulnReqResPath("request",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._requestViewer.setMessage(f, False) else: self._requestViewer.setMessage("None", False) path = self.getVulnReqResPath("response",vulnObject.getName()) if os.path.exists(path): f = self.getFileContent(path) self._responseViewer.setMessage(f, False) else: self._responseViewer.setMessage("None", False)
# Author: Michael Sengelmann import ghidra.app.script.GhidraScript state = getState() currentProgram = state.getCurrentProgram() name = currentProgram.getName() location = currentProgram.getExecutablePath() # print("The currently loaded program is: '{}'".format(name)) # print("Its location on disk is: '{}'".format(location)) if (getProgramFile() is None): print("File doesn't exist locally.") from java.io import File from javax.swing import JFileChooser chooser = JFileChooser() chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) chooser.setDialogTitle("Export " + name + " to...") chooser.showDialog(None, None) path = chooser.getSelectedFile().getAbsolutePath() fullpath = path + "/" + name f = File(fullpath) print("Creating " + f.getAbsolutePath()) from ghidra.app.util.exporter import BinaryExporter bexp = BinaryExporter() memory = currentProgram.getMemory() monitor = getMonitor() domainObj = currentProgram bexp.export(f, domainObj, memory, monitor) else: print("File already exists at " + getProgramFile().getAbsolutePath())
import jmri import java import org.apache.commons.csv from javax.swing import JFileChooser, JOptionPane from javax.swing.filechooser import FileNameExtensionFilter dialogTitle = "Class Keys Report" print " {}".format(dialogTitle) keyList = [] # Select a Java program or package directory to be analyzed. fc = JFileChooser(FileUtil.getProgramPath()) fc.setDialogTitle(dialogTitle) fc.setFileFilter(FileNameExtensionFilter("Java Program", ["java"])); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES) ret = fc.showOpenDialog(None) if ret == JFileChooser.APPROVE_OPTION: selectedItem = fc.getSelectedFile().toString() else: print 'No file selected, bye' quit() # RegEx patterns. Capture the first word after the start of the match string. # The first one looks for a word within double quotes. # The second one looks for a plain word. # A word contains a-z, A-Z, 0-9 or underscore characters. reStrKey = re.compile('\W*"(\w+)"\W*[,)]') reVarKey = re.compile('\W*(\w+)\W') ##
filenana, file_extension = os.path.splitext(filename) return file_extension argvs = sys.argv argc = len(argvs) defaultpath = '/' frontoutputpath2 = '/' xmlfil = XMLFilter('kike') print xmlfil.getDescription() chooser = JFileChooser() fakefile = File(defaultpath) chooser.setCurrentDirectory(fakefile) chooser.setDialogTitle("Select xml file") chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES) chooser.setAcceptAllFileFilterUsed(False) InputFolderPath = '' if (chooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION): IJ.log("getCrrentDirectory(): " + chooser.getCurrentDirectory().toString()) InputFolderPath = chooser.getSelectedFile().toString() else: IJ.log("No selection") file = File(InputFolderPath) # We have to feed a logger to the reader. logger = Logger.IJ_LOGGER #------------------- # Instantiate reader #-------------------
import jmri import java import com.csvreader from javax.swing import JFileChooser, JOptionPane from javax.swing.filechooser import FileNameExtensionFilter dialogTitle = "Class Keys Report" print " {}".format(dialogTitle) keyList = [] # Select a Java program or package directory to be analyzed. fc = JFileChooser(FileUtil.getProgramPath()) fc.setDialogTitle(dialogTitle) fc.setFileFilter(FileNameExtensionFilter("Java Program", ["java"])); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES) ret = fc.showOpenDialog(None) if ret == JFileChooser.APPROVE_OPTION: selectedItem = fc.getSelectedFile().toString() else: print 'No file selected, bye' quit() # RegEx patterns. Capture the first word after the start of the match string. # The first one looks for a word within double quotes. # The second one looks for a plain word. # A word contains a-z, A-Z, 0-9 or underscore characters. reStrKey = re.compile('\W*"(\w+)"\W*[,)]') reVarKey = re.compile('\W*(\w+)\W') ##
def FolderChooser(JFrame): chooseFolder = JFileChooser() chooseFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) chooseFolder.showOpenDialog(JFrame) return chooseFolder.selectedFile
def Action(self, invocation): try: http_traffic = invocation.getSelectedMessages() traffic_length = len(http_traffic) counter = 0 self._output_dir = u"/tmp" # choose output directory filechooser = JFileChooser() filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) selected = filechooser.showSaveDialog(self._menu_item) if selected == JFileChooser.APPROVE_OPTION: f = filechooser.getSelectedFile() self._output_dir = f.getAbsolutePath() self._stdout.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") while len(http_traffic) > 0: counter += 1 target_traffic = http_traffic.pop() analyzedRequest = self._helpers.analyzeRequest(target_traffic) analyzedResponse = self._helpers.analyzeResponse( target_traffic.getResponse()) status_code = analyzedResponse.getStatusCode() mime_type = analyzedResponse.getStatedMimeType() url = analyzedRequest.getUrl() body_offset = analyzedResponse.getBodyOffset() # Skip empty response. if len(target_traffic.getResponse()[body_offset:]) <= 0: self._stdout.printf("[%d/%d]\n", counter, traffic_length) self._stdout.println("[-] %s's response is empty.", url) continue # resolve filename from url. file_name = self.extract_filename(url) # check extention. if not self.has_extention(file_name): ex = self.guess_extention(mime_type, target_traffic.getResponse()) file_name = file_name + "." + ex file_path = self._output_dir + u"/" + file_name.encode('utf-8') self._stdout.printf("[%d/%d]\n", counter, traffic_length) self._stdout.printf("url: %s\n", url) self._stdout.printf("status_code: %d\n", status_code) self._stdout.printf("mime_type: %s\n", mime_type) self._stdout.printf("body_offset: %d\n", body_offset) # extract object self.extract_obj(file_path, target_traffic.getResponse(), body_offset) self._stdout.printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n") except Exception as e: self._stderr.println("[!] In Action.") self._stderr.println(e)