def testJProgressBar(self): percentCompleteDummy = DummyObject() progressBar = JProgressBar(0, 10) self.group.bind(progressBar, 'value', self.dummy, 'value') self.group.bind(progressBar, 'percentComplete', percentCompleteDummy, 'value') assert self.dummy.value == 0 assert percentCompleteDummy.value == 0 progressBar.setValue(2) assert self.dummy.value == 2 assert percentCompleteDummy.value == 0.2
class DetermineCookieFrame(JFrame): """ This is the GUI for for the user to control the actions when determining which cookie is the session cookie. """ def __init__(self, callbacks, selected_message): super(DetermineCookieFrame, self).__init__() self.callbacks = callbacks self.selected_message = selected_message self.windowClosing = self.close def loadPanel(self): panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) bottomButtonBarPanel = JPanel() bottomButtonBarPanel.setLayout( BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS)) bottomButtonBarPanel.setAlignmentX(1.0) self.runButton = JButton("Run", actionPerformed=self.start) self.cancelButton = JButton("Close", actionPerformed=self.cancel) bottomButtonBarPanel.add(Box.createHorizontalGlue()) bottomButtonBarPanel.add(self.runButton) bottomButtonBarPanel.add(self.cancelButton) # Dimension(width,height) bottom = JPanel() bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS)) bottom.setAlignmentX(1.0) self.progressBar = JProgressBar() self.progressBar.setIndeterminate(False) self.progressBar.setMaximum(100) self.progressBar.setValue(0) bottom.add(self.progressBar) self.statusTextArea = JTextArea() self.statusTextArea.setEditable(False) scrollPane = JScrollPane(self.statusTextArea) scrollPanel = JPanel() scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS)) scrollPanel.setAlignmentX(1.0) scrollPanel.add(scrollPane) panel.add(scrollPanel) panel.add(bottomButtonBarPanel) panel.add(bottom) self.add(panel) self.setTitle("Determine Session Cookie(s)") self.setSize(450, 300) self.setLocationRelativeTo(None) self.setVisible(True) original_request_bytes = self.selected_message.getRequest() http_service = self.selected_message.getHttpService() helpers = self.callbacks.getHelpers() request_info = helpers.analyzeRequest(http_service, original_request_bytes) parameters = request_info.getParameters() cookie_parameters = [ parameter for parameter in parameters if parameter.getType() == IParameter.PARAM_COOKIE ] num_requests_needed = len(cookie_parameters) + 2 self.statusTextArea.append( "This may require up to " + str(num_requests_needed) + " requests to be made. Hit 'Run' to begin.\n") def start(self, event): global cancelThread cancelThread = False self.runButton.setEnabled(False) self.cancelButton.setText("Cancel") thread = ThreadDetermineCookie(self.callbacks, self.selected_message, self.statusTextArea, self.progressBar) thread.start() def cancel(self, event): self.setVisible(False) self.dispose() def close(self, event): global cancelThread cancelThread = True
class MenueFrame(object): def __init__(self): self.mainDir = "" self.frame = JFrame("Dots Quality Check", size=(250,300)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(0,1)) self.frame.add(self.Panel) self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton('Save',actionPerformed=save) self.saveButton.setEnabled(False) self.Panel.add(self.saveButton) self.cropButton = JButton('Crop values from here', actionPerformed=cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell) self.DiscardButton.setEnabled(True) self.Panel.add(self.DiscardButton) self.quitButton = JButton('Quit script',actionPerformed=quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout wtRButton = JRadioButton("wt", actionCommand="wt") defectRButton = JRadioButton("Defect", actionCommand="defect") annoPanel.add(wtRButton) annoPanel.add(defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(wtRButton) self.aButtonGroup.add(defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self.frame) self.show() def show(self): self.frame.visible = True def getFrame(self): return self.frame def setSaveActive(self): self.saveButton.setEnabled(True) self.show() def setSaveInactive(self): self.saveButton.setEnabled(False) self.show() def setMainDir(self, path): self.mainDir = path self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0])) def getMainDir(self): return self.mainDir def setProgBarMax(self, maximum): self.ProgBar.setMaximum(maximum) def setProgBarVal(self, value): self.ProgBar.setValue(value) def close(): WindowManager.removeWindow(self.frame) self.frame.dispose()
class BottomPanel(JPanel): def __init__(self): self.holdPanel = JPanel() self.topPanel = JPanel() self.bottomPanel = JPanel() self.holdPanel.setBackground(Color.decode('#dddee6')) self.topPanel.setBackground(Color.decode('#dddee6')) self.bottomPanel.setBackground(Color.decode('#dddee6')) self.topPanel.setPreferredSize(Dimension(300, 30)) self.regBar = JProgressBar() self.gatePassBar = JProgressBar() self.regLabel = JLabel('Register : ') self.gatepassLabel = JLabel(' Gate Pass : '******'') self.gatePercentlabel = JLabel('') self.refreshButton = JButton('Refresh', actionPerformed=self.updateProgress) self.regBar.setMinimum(0) self.regBar.setMaximum(100) self.regBar.setStringPainted(True) self.gatePassBar.setMinimum(0) self.gatePassBar.setMaximum(100) self.gatePassBar.setStringPainted(True) self.setLayout(BorderLayout()) self.updateProgress(None) def updateProgress(self, e): progress = client.get_progress() regTotal = progress[0] regRecog = progress[1] gateTotal = progress[2] gateRecog = progress[3] regPercent = int((regRecog * 100) / regTotal) gatePercent = int((gateRecog * 100) / gateTotal) self.regBar.setValue(regPercent) self.gatePassBar.setValue(gatePercent) self.regBar.setString(str(regPercent) + '%') self.gatePassBar.setString(str(gatePercent) + '%') self.regPercentlabel.setText(str(regRecog) + '/' + str(regTotal)) self.gatePercentlabel.setText( str(gateRecog) + '/' + str(gateTotal) + ' ') if regPercent <= 30: regColor = Color.RED elif regPercent > 30 and regPercent < 50: regColor = Color.ORANGE elif regPercent >= 50 and regPercent <= 100: regColor = Color.GREEN if gatePercent <= 30: gateColor = Color.RED elif gatePercent > 30 and gatePercent < 50: gateColor = Color.ORANGE elif gatePercent >= 50 and gatePercent <= 100: gateColor = Color.GREEN self.regBar.setForeground(regColor) self.gatePassBar.setForeground(gateColor) self.holdPanel.add(self.regLabel) self.holdPanel.add(self.regBar) self.holdPanel.add(self.regPercentlabel) self.holdPanel.add(self.gatepassLabel) self.holdPanel.add(self.gatePassBar) self.holdPanel.add(self.gatePercentlabel) self.holdPanel.add(self.refreshButton) self.add(self.holdPanel, BorderLayout.CENTER) self.add(self.topPanel, BorderLayout.PAGE_START) self.add(self.bottomPanel, BorderLayout.PAGE_END) self.validate()
class DetermineCookieFrame(JFrame): """ This is the GUI for for the user to control the actions when determining which cookie is the session cookie. """ def __init__(self, callbacks, selected_message): super(DetermineCookieFrame, self).__init__() self.callbacks = callbacks self.selected_message = selected_message self.windowClosing = self.close def loadPanel(self): panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) bottomButtonBarPanel = JPanel() bottomButtonBarPanel.setLayout(BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS)) bottomButtonBarPanel.setAlignmentX(1.0) self.runButton = JButton("Run", actionPerformed=self.start) self.cancelButton = JButton("Close", actionPerformed=self.cancel) bottomButtonBarPanel.add(Box.createHorizontalGlue()); bottomButtonBarPanel.add(self.runButton) bottomButtonBarPanel.add(self.cancelButton) # Dimension(width,height) bottom = JPanel() bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS)) bottom.setAlignmentX(1.0) self.progressBar = JProgressBar() self.progressBar.setIndeterminate(False) self.progressBar.setMaximum(100) self.progressBar.setValue(0) bottom.add(self.progressBar) self.statusTextArea = JTextArea() self.statusTextArea.setEditable(False) scrollPane = JScrollPane(self.statusTextArea) scrollPanel = JPanel() scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS)) scrollPanel.setAlignmentX(1.0) scrollPanel.add(scrollPane) panel.add(scrollPanel) panel.add(bottomButtonBarPanel) panel.add(bottom) self.add(panel) self.setTitle("Determine Session Cookie(s)") self.setSize(450, 300) self.setLocationRelativeTo(None) self.setVisible(True) original_request_bytes = self.selected_message.getRequest() http_service = self.selected_message.getHttpService() helpers = self.callbacks.getHelpers() request_info = helpers.analyzeRequest(http_service, original_request_bytes) parameters = request_info.getParameters(); cookie_parameters = [parameter for parameter in parameters if parameter.getType() == IParameter.PARAM_COOKIE] num_requests_needed = len(cookie_parameters) + 2 self.statusTextArea.append("This may require up to " + str(num_requests_needed) + " requests to be made. Hit 'Run' to begin.\n") def start(self, event): global cancelThread cancelThread = False self.runButton.setEnabled(False) self.cancelButton.setText("Cancel") thread = ThreadDetermineCookie(self.callbacks, self.selected_message, self.statusTextArea, self.progressBar) thread.start() def cancel(self, event): self.setVisible(False); self.dispose(); def close(self, event): global cancelThread cancelThread = True
class Pipeline(): def __init__(self): #If a swing interface is asked for this will be the JFrame. self.frame = None #Keeps track of the number of queries processed. self.jobCount = 0 #Keeps track of the query currently being processed. self.currentJob = "" #Keeps track of the massage to be displayed. self.message = 0 #Messages to be displayed at each stage in the processing of a single query. self.messages = ["Searching for genes via genemark", "Extending genes found via genemark", "Searching for intergenic genes", "Removing overlapping genes", "Searching for promoters", "Using transterm to find terminators", "Removing transcription signals which conflict with genes", "Using tRNAscan to find transfer RNAs", "Writing Artemis file", "Writing summary .xml, .html, and .xls files"] self.exception = None def initializeDisplay(self, queries, swing): """ queries: A list of the fasts files to be processed. swing: If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout. Initializes the interface for telling the user about progress in the pipeline. Queries is used to count the number of queries the pipeline will process and to size the swing display(if it is used) so that text isn't cutoff at the edge of the window. The swing display is setup if swing is true. """ self.numJobs = len(queries) if swing: self.frame = JFrame("Neofelis") self.frame.addWindowListener(PipelineWindowAdapter(self)) contentPane = JPanel(GridBagLayout()) self.frame.setContentPane(contentPane) self.globalLabel = JLabel(max(queries, key = len)) self.globalProgress = JProgressBar(0, self.numJobs) self.currentLabel = JLabel(max(self.messages, key = len)) self.currentProgress = JProgressBar(0, len(self.messages)) self.doneButton = JButton(DoneAction(self.frame)) self.doneButton.setEnabled(False) constraints = GridBagConstraints() constraints.gridx, constraints.gridy = 0, 0 constraints.gridwidth, constraints.gridheight = 1, 1 constraints.weightx = 1 constraints.fill = GridBagConstraints.HORIZONTAL contentPane.add(self.globalLabel, constraints) constraints.gridy = 1 contentPane.add(self.globalProgress, constraints) constraints.gridy = 2 contentPane.add(self.currentLabel, constraints) constraints.gridy = 3 contentPane.add(self.currentProgress, constraints) constraints.gridy = 4 constraints.weightx = 0 constraints.fill = GridBagConstraints.NONE constraints.anchor = GridBagConstraints.LINE_END contentPane.add(self.doneButton, constraints) self.frame.pack() self.frame.setResizable(False) self.globalLabel.setText(" ") self.currentLabel.setText(" ") self.frame.setLocationRelativeTo(None) self.frame.setVisible(True) def updateProgress(self, job): """ query: Name of the query currently being processed. This function use used for updating the progress shown in the interface. If job is not equal to currentJob then global progress is incremented and shown and the currentProgress is reset and shown. If job is equal to currentJob then the globalProgress does not change and currentProgress is increased. """ if self.exception: raise self.exception if self.frame: if job != self.currentJob: self.currentProgress.setValue(self.currentProgress.getMaximum()) self.globalLabel.setText(job) self.globalProgress.setValue(self.jobCount) print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs) self.jobCount += 1 self.currentJob = job self.message = -1 self.message += 1 print " %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages)) self.currentProgress.setValue(self.message) self.currentLabel.setText(self.messages[self.message]) else: if job != self.currentJob: print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs) self.jobCount += 1 self.currentJob = job self.message = -1 self.message += 1 print " %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages)) def finished(self): """ This function is to be called at the end of the pipeline. Informs the user that the pipeline is finished and if a swing interface is being used the Done button is enabled. """ print "Processing 100.00% done" if self.frame: self.globalLabel.setText("Finished") self.globalProgress.setValue(self.globalProgress.getMaximum()) self.currentLabel.setText(" ") self.currentProgress.setValue(self.currentProgress.getMaximum()) self.doneButton.setEnabled(True) while self.frame.isVisible(): pass def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""): """ blastLocation: Directory blast was installed in. genemarkLocation: Directory genemark was installed in. transtermLocation: Directory transterm was installed in. tRNAscanLocation: Directory tRNAscan was installed in. database: Name of the blast database to use. eValue: The e value used whenever a blast search is done. matrix: The matrix to use when running genemark. If None then genemark is run heuristically. minLength: Minimum length of any genes included in the resulting annotation. scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation queries: A list of faster files to process. swing: If true a swing window will be used to updated the user about the pipeline's progress. email: If this is a non-empty string an email will be sent to the address in the string when the pipeline is done. This will be attempted with the sendmail command on the local computer. The main pipeline function. For every query genemark is used to predict genes, these genes are then extended to any preferable starts. Then the pipeline searches for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes. Then the genes are pruned to remove any undesirable genes found in the intergenic stage. BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any signals which are inside or too far away from any genes. Next, tRNAscan is used to find any transfer RNAs in the genome. Finally, all the remaining genes, promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and .xls files will be generating describing the blast results of the final genes. """ self.initializeDisplay(queries, swing) try: for query in queries: name = os.path.splitext(query)[0] queryDirectory, name = os.path.split(name) genome = utils.loadGenome(query) swapFileName = "query" + str(id(self)) + ".fas" queryFile = open(swapFileName, "w") queryFile.write(">" + name + "\n") for i in range(0, len(genome), 50): queryFile.write(genome[i:min(i+50, len(genome))] + "\n") queryFile.close() self.updateProgress(query) initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self) self.updateProgress(query) extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self) self.updateProgress(query) intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self) genes = {} for k, v in extendedGenes.items() + intergenicGenes.items(): genes[k] = v self.updateProgress(query) scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance) self.updateProgress(query) initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame) self.updateProgress(query) initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation) self.updateProgress(query) filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators) filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals) filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals) self.updateProgress(query) transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName) os.remove(swapFileName) self.updateProgress(query) artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs) self.updateProgress(query) report.report(name, scaffolded, os.path.splitext(query)[0]) if email: if not os.path.isfile("EMAIL_MESSAGE"): message = open("EMAIL_MESSAGE", "w") message.write("Subject: Annotation Complete\nYour genome has been annotated.\n") message.close() sent = False while not sent: message = open("EMAIL_MESSAGE", "r") sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email], stdin = message, stdout = subprocess.PIPE) result = "" nextRead = sendmailProcess.stdout.read() while nextRead: result += nextRead nextRead = sendmailProcess.stdout.read() sent = not result.strip() message.close() self.finished() except PipelineException: return
class Gui(JFrame): ''' classdocs ''' def __init__(self, pP): ''' Constructor ''' self.pP = pP self.annotationType = self.pP.getAnnotationType() self.setTitle("Random Picture Picker") #annotation Panel annoPanel = JPanel() annoPanel.setBorder(BorderFactory.createTitledBorder("Annotations")) annoPLayout = GroupLayout(annoPanel) annoPanel.setLayout(annoPLayout) annoPLayout.setAutoCreateContainerGaps(True) annoPLayout.setAutoCreateGaps(True) # dynamic creation of annotation panel # yesNoIgnore, int, number, list if len(self.pP.getAnnotationType()) == 1: self.annoField = JTextField("", 16) annoPLayout.setHorizontalGroup(annoPLayout.createParallelGroup().addComponent(self.annoField)) annoPLayout.setVerticalGroup(annoPLayout.createSequentialGroup().addComponent(self.annoField)) elif len(self.pP.getAnnotationType()) > 1: choices = pP.getAnnotationType() print "choices", choices choiceBtns = [] self.annoField = ButtonGroup() for c in choices: Btn = JRadioButton(c, actionCommand=c) self.annoField.add(Btn) choiceBtns.append(Btn) h = annoPLayout.createParallelGroup() for b in choiceBtns: h.addComponent(b) annoPLayout.setHorizontalGroup(h) v = annoPLayout.createSequentialGroup() for b in choiceBtns: v.addComponent(b) annoPLayout.setVerticalGroup(v) # Control Panel ctrlPanel = JPanel() ctrlPLayout = GroupLayout(ctrlPanel, autoCreateContainerGaps=True, autoCreateGaps=True) ctrlPanel.setLayout(ctrlPLayout) nextImgButton = JButton("Next >", actionPerformed=self.nextPicture) prevImgButton = JButton("< Prev", actionPerformed=self.pP.prevPicture) quitButton = JButton("Quit", actionPerformed=self.exit) ctrlPLayout.setHorizontalGroup(ctrlPLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addGroup(ctrlPLayout.createSequentialGroup() .addComponent(prevImgButton) .addComponent(nextImgButton)) .addComponent(quitButton)) ctrlPLayout.setVerticalGroup(ctrlPLayout.createSequentialGroup() .addGroup(ctrlPLayout.createParallelGroup() .addComponent(prevImgButton) .addComponent(nextImgButton)) .addComponent(quitButton)) ctrlPLayout.linkSize(SwingConstants.HORIZONTAL, quitButton) statusPanel = JPanel() # contains status information: progress bar self.progressBar = JProgressBar() self.progressBar.setStringPainted(True) self.progressBar.setValue(0) statusPanel.add(self.progressBar) #MainLayout mainLayout = GroupLayout(self.getContentPane()) self.getContentPane().setLayout(mainLayout) mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(annoPanel) .addComponent(ctrlPanel) .addComponent(statusPanel) ) mainLayout.setVerticalGroup(mainLayout.createSequentialGroup() .addComponent(annoPanel) .addComponent(ctrlPanel) .addComponent(statusPanel) ) mainLayout.linkSize(SwingConstants.HORIZONTAL, annoPanel, ctrlPanel, statusPanel) self.pack() self.setVisible(True) self.pP.nextPicture() def nextPicture(self, event): percent = (float(len(self.pP.usedList))/len(self.pP.pictureList))*100 self.progressBar.setValue(int(percent)) self.setAnnotation() self.pP.nextPicture() #try: # self.setAnnotation() # self.pP.nextPicture() #except AttributeError: # print "Please choose something!" def setAnnotationField(self, a): if len(self.pP.getAnnotationType()) > 1: [Rbutton.setSelected(True) for Rbutton in self.annoField.getElements() if Rbutton.getActionCommand()==a] if len(self.pP.getAnnotationType()) == 1: self.annoField.setText(a) #rename this method to something clearer! def setAnnotation(self): if len(self.pP.getAnnotationType()) > 1: annotation = self.annoField.getSelection().getActionCommand() if len(self.pP.getAnnotationType()) == 1: annotation = self.annoField.getText() self.annoField.setText(None) self.pP.getCurrentPicture().annotate(annotation) def getAnnotation(self): return self.annotation def exit(self, event): self.pP.exit() self.dispose()
class JythonGui(ItemListener): def __init__(self, instructionsURI=''): self.instructionsURI = instructionsURI self.logger = logging.getLogger('sasi_runner_gui') self.logger.addHandler(logging.StreamHandler()) def log_fn(msg): self.log_msg(msg) self.logger.addHandler(FnLogHandler(log_fn)) self.logger.setLevel(logging.DEBUG) self.selected_input_file = None self.selected_output_file = None self.frame = JFrame( "SASI Runner", defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE, ) self.frame.size = (650, 600,) self.main_panel = JPanel() self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS) self.frame.add(self.main_panel) self.top_panel = JPanel(SpringLayout()) self.top_panel.alignmentX = Component.CENTER_ALIGNMENT self.main_panel.add(self.top_panel) self.stageCounter = 1 def getStageLabel(txt): label = JLabel("%s. %s" % (self.stageCounter, txt)) self.stageCounter += 1 return label # Instructions link. self.top_panel.add(getStageLabel("Read the instructions:")) instructionsButton = JButton( ('<HTML><FONT color="#000099">' '<U>open instructions</U></FONT><HTML>'), actionPerformed=self.browseInstructions) instructionsButton.setHorizontalAlignment(SwingConstants.LEFT); instructionsButton.setBorderPainted(False); instructionsButton.setOpaque(False); instructionsButton.setBackground(Color.WHITE); instructionsButton.setToolTipText(self.instructionsURI); self.top_panel.add(instructionsButton) # 'Select input' elements. self.top_panel.add(getStageLabel( "Select a SASI .zip file or data folder:")) self.top_panel.add( JButton("Select input...", actionPerformed=self.openInputChooser)) # 'Select output' elements. self.top_panel.add(getStageLabel("Specify an output file:")) self.top_panel.add( JButton("Specify output...", actionPerformed=self.openOutputChooser)) # 'Set result fields' elements. result_fields = [ {'id': 'gear_id', 'label': 'Gear', 'selected': True, 'enabled': False}, {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, {'id': 'energy_id', 'label': 'Energy', 'selected': False}, {'id': 'feature_id', 'label': 'Feature', 'selected': False}, {'id': 'feature_category_id', 'label': 'Feature Category', 'selected': False} ] self.selected_result_fields = {} resolutionLabelPanel = JPanel(GridLayout(0,1)) resolutionLabelPanel.add(getStageLabel("Set result resolution:")) resolutionLabelPanel.add( JLabel(("<html><i>This sets the specificity with which<br>" "results will be grouped. Note that enabling<br>" "more fields can *greatly* increase resulting<br>" "output sizes and run times.</i>"))) #self.top_panel.add(getStageLabel("Set result resolution:")) self.top_panel.add(resolutionLabelPanel) checkPanel = JPanel(GridLayout(0, 1)) self.top_panel.add(checkPanel) self.resultFieldCheckBoxes = {} for result_field in result_fields: self.selected_result_fields.setdefault( result_field['id'], result_field['selected']) checkBox = JCheckBox( result_field['label'], result_field['selected']) checkBox.setEnabled(result_field.get('enabled', True)) checkBox.addItemListener(self) checkPanel.add(checkBox) self.resultFieldCheckBoxes[checkBox] = result_field # 'Run' elements. self.top_panel.add(getStageLabel("Run SASI: (this might take a while)")) self.run_button = JButton("Run...", actionPerformed=self.runSASI) self.top_panel.add(self.run_button) SpringUtilities.makeCompactGrid( self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6) # Progress bar. self.progressBar = JProgressBar(0, 100) self.main_panel.add(self.progressBar) # Log panel. self.log_panel = JPanel() self.log_panel.alignmentX = Component.CENTER_ALIGNMENT self.log_panel.setBorder(EmptyBorder(10,10,10,10)) self.main_panel.add(self.log_panel) self.log_panel.setLayout(BorderLayout()) self.log = JTextArea() self.log.editable = False self.logScrollPane = JScrollPane(self.log) self.logScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) self.logScrollBar = self.logScrollPane.getVerticalScrollBar() self.log_panel.add(self.logScrollPane, BorderLayout.CENTER) # File selectors self.inputChooser = JFileChooser() self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES self.outputChooser = JFileChooser() defaultOutputFile = os.path.join(System.getProperty("user.home"), "sasi_project.zip") self.outputChooser.setSelectedFile(File(defaultOutputFile)); self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY self.frame.setLocationRelativeTo(None) self.frame.visible = True def browseInstructions(self, event): """ Open a browser to the instructions page. """ browseURI(self.instructionsURI) def itemStateChanged(self, event): """ Listen for checkbox changes. """ checkBox = event.getItemSelectable() is_selected = (event.getStateChange() == ItemEvent.SELECTED) result_field = self.resultFieldCheckBoxes[checkBox] self.selected_result_fields[result_field['id']] = is_selected def log_msg(self, msg): """ Print message to log and scroll to bottom. """ self.log.append(msg + "\n") self.log.setCaretPosition(self.log.getDocument().getLength()) def openInputChooser(self, event): ret = self.inputChooser.showOpenDialog(self.frame) if ret == JFileChooser.APPROVE_OPTION: self.selected_input_file = self.inputChooser.selectedFile self.log_msg("Selected '%s' as input." % self.selected_input_file.path) def openOutputChooser(self, event): ret = self.outputChooser.showSaveDialog(self.frame) if ret == JFileChooser.APPROVE_OPTION: selectedPath = self.outputChooser.selectedFile.path if not selectedPath.endswith('.zip'): zipPath = selectedPath + '.zip' self.outputChooser.setSelectedFile(File(zipPath)) self.selected_output_file = self.outputChooser.selectedFile self.log_msg( "Selected '%s' as output." % self.selected_output_file.path) def runSASI(self, event): try: self.validateParameters() except Exception as e: self.log_msg("ERROR: '%s'" % e) # Run task in a separate thread, so that log # messages will be shown as task progresses. def run_task(): self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.") self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db") self.progressBar.setValue(0) self.progressBar.setIndeterminate(True) def get_connection(): engine = create_engine('h2+zxjdbc:////%s' % self.db_file) con = engine.connect() return con try: # Set result fields. result_fields = [] for field_id, is_selected in self.selected_result_fields.items(): if is_selected: result_fields.append(field_id) task = RunSasiTask( input_path=self.selected_input_file.path, output_file=self.selected_output_file.path, logger=self.logger, get_connection=get_connection, config={ 'result_fields': result_fields, 'run_model': { 'run': { 'batch_size': 'auto', } }, 'output': { 'batch_size': 'auto', }, } ) task.call() except Exception as e: self.logger.exception("Could not complete task") self.progressBar.setIndeterminate(False) self.progressBar.setValue(100) try: shutil.rmtree(self.tmp_dir) except: pass Thread(target=run_task).start() def validateParameters(self): return True
class JythonGui(object): def __init__(self, instructionsURI=""): self.instructionsURI = instructionsURI self.logger = logging.getLogger("sasi_gridder_gui") self.logger.addHandler(logging.StreamHandler()) def log_fn(msg): self.log_msg(msg) self.logger.addHandler(FnLogHandler(log_fn)) self.logger.setLevel(logging.DEBUG) self.selected_input_file = None self.selected_output_file = None self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE) self.frame.size = (650, 600) self.main_panel = JPanel() self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS) self.frame.add(self.main_panel) self.top_panel = JPanel(SpringLayout()) self.top_panel.alignmentX = Component.CENTER_ALIGNMENT self.main_panel.add(self.top_panel) self.stageCounter = 1 def getStageLabel(txt): label = JLabel("%s. %s" % (self.stageCounter, txt)) self.stageCounter += 1 return label # Instructions link. self.top_panel.add(getStageLabel("Read the instructions:")) instructionsButton = JButton( ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"), actionPerformed=self.browseInstructions, ) instructionsButton.setHorizontalAlignment(SwingConstants.LEFT) instructionsButton.setBorderPainted(False) instructionsButton.setOpaque(False) instructionsButton.setBackground(Color.WHITE) instructionsButton.setToolTipText(self.instructionsURI) self.top_panel.add(instructionsButton) # Select input elements. self.top_panel.add(getStageLabel("Select an input data folder:")) self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser)) # Select output elements. self.top_panel.add(getStageLabel("Specify an output file:")) self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser)) # Run elements. self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile")) self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder) self.top_panel.add(self.run_button) SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6) # Progress bar. self.progressBar = JProgressBar(0, 100) self.main_panel.add(self.progressBar) # Log panel. self.log_panel = JPanel() self.log_panel.alignmentX = Component.CENTER_ALIGNMENT self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10)) self.main_panel.add(self.log_panel) self.log_panel.setLayout(BorderLayout()) self.log = JTextArea() self.log.editable = False self.logScrollPane = JScrollPane(self.log) self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) self.log_panel.add(self.logScrollPane, BorderLayout.CENTER) # File selectors self.inputChooser = JFileChooser() self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES self.outputChooser = JFileChooser() self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv") self.outputChooser.setSelectedFile(File(defaultOutputFile)) self.frame.setLocationRelativeTo(None) self.frame.visible = True def browseInstructions(self, event): """ Open a browser to the instructions page. """ browseURI(self.instructionsURI) return def log_msg(self, msg): self.log.append(msg + "\n") self.log.setCaretPosition(self.log.getDocument().getLength()) def openInputChooser(self, event): ret = self.inputChooser.showOpenDialog(self.frame) if ret == JFileChooser.APPROVE_OPTION: self.selected_input_file = self.inputChooser.selectedFile self.log_msg("Selected '%s' as input." % self.selected_input_file.path) def openOutputChooser(self, event): ret = self.outputChooser.showSaveDialog(self.frame) if ret == JFileChooser.APPROVE_OPTION: self.selected_output_file = self.outputChooser.selectedFile self.log_msg("Selected '%s' as output." % self.selected_output_file.path) def runSASIGridder(self, event): try: self.validateParameters() except Exception as e: self.log_msg("ERROR: '%s'" % e) # Run task in a separate thread, so that log # messages will be shown as task progresses. def run_task(): self.progressBar.setValue(0) self.progressBar.setIndeterminate(True) try: input_dir = self.selected_input_file.path output_path = self.selected_output_file.path grid_path = os.path.join(input_dir, "grid", "grid.shp") stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp") raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv") gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv") gear_mappings = {} with open(gear_mappings_path, "rb") as f: r = csv.DictReader(f) for mapping in r: gear_mappings[mapping["trip_type"]] = mapping["gear_code"] task = SASIGridderTask( grid_path=grid_path, raw_efforts_path=raw_efforts_path, stat_areas_path=stat_areas_path, output_path=output_path, logger=self.logger, gear_mappings=gear_mappings, effort_limit=None, ) task.call() except Exception as e: self.logger.exception("Could not complete task") self.progressBar.setIndeterminate(False) self.progressBar.setValue(100) Thread(target=run_task).start() def validateParameters(self): return True
class Pipeline(): def __init__(self): #If a swing interface is asked for this will be the JFrame. self.frame = None #Keeps track of the number of queries processed. self.jobCount = 0 #Keeps track of the query currently being processed. self.currentJob = "" #Keeps track of the massage to be displayed. self.message = 0 #Messages to be displayed at each stage in the processing of a single query. self.messages = [ "Searching for genes via genemark", "Extending genes found via genemark", "Searching for intergenic genes", "Removing overlapping genes", "Searching for promoters", "Using transterm to find terminators", "Removing transcription signals which conflict with genes", "Writing Artemis file", "Writing summary file" ] self.exception = None def initializeDisplay(self, queries, swing): """ queries: A list of the fasts files to be processed. swing: If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout. Initializes the interface for telling the user about progress in the pipeline. Queries is used to count the number of queries the pipeline will process and to size the swing display(if it is used) so that text isn't cutoff at the edge of the window. The swing display is setup if swing is true. """ self.numJobs = len(queries) if swing: self.frame = JFrame("Neofelis") self.frame.addWindowListener(PipelineWindowAdapter(self)) contentPane = JPanel(GridBagLayout()) self.frame.setContentPane(contentPane) self.globalLabel = JLabel(max(queries, key=len)) self.globalProgress = JProgressBar(0, self.numJobs) self.currentLabel = JLabel(max(self.messages, key=len)) self.currentProgress = JProgressBar(0, len(self.messages)) self.doneButton = JButton(DoneAction(self.frame)) self.doneButton.setEnabled(False) constraints = GridBagConstraints() constraints.gridx, constraints.gridy = 0, 0 constraints.gridwidth, constraints.gridheight = 1, 1 constraints.weightx = 1 constraints.fill = GridBagConstraints.HORIZONTAL contentPane.add(self.globalLabel, constraints) constraints.gridy = 1 contentPane.add(self.globalProgress, constraints) constraints.gridy = 2 contentPane.add(self.currentLabel, constraints) constraints.gridy = 3 contentPane.add(self.currentProgress, constraints) constraints.gridy = 4 constraints.weightx = 0 constraints.fill = GridBagConstraints.NONE constraints.anchor = GridBagConstraints.LINE_END contentPane.add(self.doneButton, constraints) self.frame.pack() self.frame.setResizable(False) self.globalLabel.setText(" ") self.currentLabel.setText(" ") self.frame.setLocationRelativeTo(None) self.frame.setVisible(True) def updateProgress(self, job): """ query: Name of the query currently being processed. This function use used for updating the progress shown in the interface. If job is not equal to currentJob then global progress is incremented and shown and the currentProgress is reset and shown. If job is equal to currentJob then the globalProgress does not change and currentProgress is incremented. """ if self.exception: raise self.exception if self.frame: if job != self.currentJob: self.currentProgress.setValue( self.currentProgress.getMaximum()) self.globalLabel.setText(job) self.globalProgress.setValue(self.jobCount) print "Processing %s, %.2f%% done" % ( job, 100.0 * self.jobCount / self.numJobs) self.jobCount += 1 self.currentJob = job self.message = -1 self.message += 1 print " %s, %.2f%% done" % (self.messages[self.message], 100.0 * self.message / len(self.messages)) self.currentProgress.setValue(self.message) self.currentLabel.setText(self.messages[self.message]) else: if job != self.currentJob: print "Processing %s, %.2f%% done" % ( job, 100.0 * self.jobCount / self.numJobs) self.jobCount += 1 self.currentJob = job self.message = -1 self.message += 1 print " %s, %.2f%% done" % (self.messages[self.message], 100.0 * self.message / len(self.messages)) def finished(self): """ This function is to be called at the end of the pipeline. Informs the user that the pipeline is finished and if a swing interface is being used the Done button is enabled. """ print "Processing 100.00% done" if self.frame: self.globalLabel.setText("Finished") self.globalProgress.setValue(self.globalProgress.getMaximum()) self.currentLabel.setText(" ") self.currentProgress.setValue(self.currentProgress.getMaximum()) self.doneButton.setEnabled(True) while self.frame.isVisible(): pass def run(self, blastLocation, genemarkLocation, transtermLocation, database, eValue, matrix, minLength, scaffoldingDistance, ldfCutoff, queries, swing=False, email=""): """ blastLocation: Directory blast was installed in. genemarkLocation: Directory genemark was installed in. transtermLocation: Directory transterm was installed in. database: Name of the blast database to use. eValue: The e value used whenever a blast search is done. matrix: The matrix to use when running genemark. If None then genemark is run heuristically. minLength: Minimum length of any genes included in the resulting annotation. scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified ldfCutoff: Minimum LDF allowed for any promoters included in the resulting annotation queries: A list of faster files to process. swing: If true a swing window will be used to updated the user about the pipeline's progress. email: If this is a non-empty string an email will be sent to the address in the string when the pipeline is done. The local machine will be used as an SMTP server and this will not work if it isn't. The main pipeline function. For every query genemark is used to predict genes, these genes are then extended to any preferable starts. Then the pipeline searches for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes. Then the genes are pruned to remove any undesirable genes found in the intergenic stage. BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any signals which are inside or too far away from any genes. Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes. """ self.initializeDisplay(queries, swing) try: for query in queries: name = os.path.splitext(query)[0] queryDirectory, name = os.path.split(name) genome = utils.loadGenome(query) swapFileName = "query" + str(id(self)) + ".fas" queryFile = open(swapFileName, "w") queryFile.write(">" + name + "\n") for i in range(0, len(genome), 50): queryFile.write(genome[i:min(i + 50, len(genome))] + "\n") queryFile.close() self.updateProgress(query) initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self) #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values()) self.updateProgress(query) extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self) #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values()) self.updateProgress(query) intergenicGenes = intergenic.findIntergenics( swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self) #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values()) genes = {} for k, v in extendedGenes.items() + intergenicGenes.items(): genes[k] = v self.updateProgress(query) scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance) self.updateProgress(query) initialPromoters = promoters.findPromoters(swapFileName, name) self.updateProgress(query) initialTerminators = terminators.findTerminators( swapFileName, name, genes.values(), transtermLocation) self.updateProgress(query) filteredSignals = signals.filterSignals( scaffolded.values(), initialPromoters + initialTerminators) filteredPromoters = filter( lambda x: isinstance(x, promoters.Promoter), filteredSignals) filteredTerminators = filter( lambda x: isinstance(x, terminators.Terminator), filteredSignals) self.updateProgress(query) artemis.writeArtemisFile( os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators) self.updateProgress(query) report.report(name, scaffolded, os.path.splitext(query)[0]) if email: message = MIMEText("Your genome has been annotated.") message["Subject"] = "Annotation complete" message["From"] = "Neofelis" message["To"] = email smtp = smtplib.SMTP("tmpl.arizona.edu", 587) smtp.ehlo() smtp.starttls() smtp.ehlo smtp.sendmail("Neofelis", [email], message.as_string()) smtp.close() self.finished() except PipelineException: return
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener): # Define the global variables for the burp plugin EXTENSION_NAME = "UPnP BHunter" ipv4_selected = True services_dict = {} ip_service_dict = {} STOP_THREAD = False #Some SSDP m-search parameters are based upon "UPnP Device Architecture v2.0" SSDP_MULTICAST_IPv4 = ["239.255.255.250"] SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"] SSDP_MULTICAST_PORT = 1900 ST_ALL = "ssdp:all" ST_ROOTDEV = "upnp:rootdevice" PLACEHOLDER = "FUZZ_HERE" SSDP_TIMEOUT = 2 def registerExtenderCallbacks(self, callbacks): # Get a reference to callbacks object self.callbacks = callbacks # Get the useful extension helpers object self.helpers = callbacks.getHelpers() # Set the extension name self.callbacks.setExtensionName(self.EXTENSION_NAME) self.callbacks.registerExtensionStateListener(self) # Draw plugin user interface self.drawPluginUI() self.callbacks.addSuiteTab(self) # Plugin loading message print("[+] Burp plugin UPnP BHunter loaded successfully") return def drawPluginUI(self): # Create the plugin user interface self.pluginTab = JPanel() self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console') self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14)) self.uiTitle.setForeground(Color(250, 100, 0)) self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelA.setMaximumSize(Dimension(2500, 1000)) self.uiPanelA.setDividerSize(2) self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT) self.uiPanelB.setDividerSize(2) self.uiPanelA.setBottomComponent(self.uiPanelB) self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray)) # Create and configure labels and text fields self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations") self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step2 = JLabel( "[2nd STEP] Select a UPnP Service and Action") self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14)) self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it") self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14)) self.labelsubtitle_step1 = JLabel( "Specify the IP version address in scope and start UPnP discovery") self.labelsubtitle_step2 = JLabel( "Select which of the found UPnP services will be probed") self.labelsubtitle_step3 = JLabel( "Review and modify the request, then send it to one of the attack tools" ) self.label_step1 = JLabel("Target IP") self.label_step2 = JLabel("Found UPnp Services") self.labelstatus = JLabel(" Status") self.labelempty_step1 = JLabel(" ") self.labelempty_step2 = JLabel(" ") self.labelupnp = JLabel("UPnP list") self.labelip = JLabel("IP list") self.labelactions = JLabel("Actions") self.labelNoneServiceFound = JLabel(" ") self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12)) self.labelNoneServiceFound.setForeground(Color.red) # Create combobox for IP version selection self.ip_versions = ["IPv4", "IPv6"] self.combo_ipversion = JComboBox(self.ip_versions) self.combo_ipversion.setSelectedIndex(0) self.combo_ipversion.setEnabled(True) # Create and configure progress bar self.progressbar = JProgressBar(0, 100) self.progressbar.setString("Ready") self.progressbar.setStringPainted(True) # Create and configure buttons self.startbutton = JButton("Start Discovery", actionPerformed=self.startHunting) self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll) self.intruderbutton = JButton("Send to Intruder", actionPerformed=self.sendToIntruder) self.repeaterbutton = JButton("Send to Repeater", actionPerformed=self.sendToRepeater) #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater) self.textarea_request = JTextArea(18, 90) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Class neeeded to handle the target combobox in second step panel class TargetComboboxListener(ActionListener): def __init__(self, upnpcombo_targets, upnpcombo_services, ip_service_dict): self.upnpcombo_targets = upnpcombo_targets self.upnpcombo_services = upnpcombo_services self.ip_service_dict = ip_service_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_target = self.upnpcombo_targets.getSelectedItem() if self.ip_service_dict and selected_target: self.upnpcombo_services.removeAllItems() for service_url in self.ip_service_dict[ selected_target]: self.upnpcombo_services.addItem(service_url) self.upnpcombo_services.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the service combobox in second step panel class ServiceComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_service: self.upnpcombo_actions.removeAllItems() actions = self.services[selected_service] for action in actions: self.upnpcombo_actions.addItem(action) self.upnpcombo_actions.setSelectedIndex(0) except BaseException as e: print("[!] Exception selecting service: \"%s\" ") % e # Class neeeded to handle the action combobox in second step panel class ActionComboboxListener(ActionListener): def __init__(self, upnpcombo_services, upnpcombo_actions, textarea_request, services_dict): self.upnpcombo_services = upnpcombo_services self.upnpcombo_actions = upnpcombo_actions self.textarea_request = textarea_request self.services = services_dict def actionPerformed(self, event): try: # Update the location url combobox depending on the IP combobox selected_action = self.upnpcombo_actions.getSelectedItem() selected_service = self.upnpcombo_services.getSelectedItem( ) if self.services and selected_action: self.textarea_request.setText( self.services[selected_service][selected_action]) except BaseException as e: print("[!] Exception selecting action: \"%s\" ") % e self.upnpactions = [" "] self.upnpcombo_actions = JComboBox(self.upnpactions) self.upnpcombo_actions.setSelectedIndex(0) self.upnpcombo_actions.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnpservices = [" "] self.upnpcombo_services = JComboBox(self.upnpservices) self.upnpcombo_services.setSelectedIndex(0) self.upnpcombo_services.setEnabled(False) # Create the combo box, select item at index 0 (first item in list) self.upnptargets = [" "] self.upnpcombo_targets = JComboBox(self.upnptargets) self.upnpcombo_targets.setSelectedIndex(0) self.upnpcombo_targets.setEnabled(False) # Set the action listeners for all the comboboxes self.upnpcombo_targets.addActionListener( TargetComboboxListener(self.upnpcombo_targets, self.upnpcombo_services, self.ip_service_dict)) self.upnpcombo_services.addActionListener( ServiceComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.services_dict)) self.upnpcombo_actions.addActionListener( ActionComboboxListener(self.upnpcombo_services, self.upnpcombo_actions, self.textarea_request, self.services_dict)) # Configuring first step panel self.panel_step1 = JPanel() self.panel_step1.setPreferredSize(Dimension(2250, 100)) self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step1.setLayout(BorderLayout(15, 15)) self.titlepanel_step1 = JPanel() self.titlepanel_step1.setLayout(BorderLayout()) self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH) self.titlepanel_step1.add(self.labelsubtitle_step1) self.targetpanel_step1 = JPanel() self.targetpanel_step1.add(self.label_step1) self.targetpanel_step1.add(self.combo_ipversion) self.targetpanel_step1.add(self.startbutton) self.targetpanel_step1.add(self.clearbutton) self.targetpanel_step1.add(self.labelstatus) self.targetpanel_step1.add(self.progressbar) self.emptypanel_step1 = JPanel() self.emptypanel_step1.setLayout(BorderLayout()) self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST) # Assembling first step panel components self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH) self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST) self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH) self.uiPanelA.setTopComponent(self.panel_step1) # Configure second step panel self.panel_step2 = JPanel() self.panel_step2.setPreferredSize(Dimension(2250, 100)) self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step2.setLayout(BorderLayout(15, 15)) self.titlepanel_step2 = JPanel() self.titlepanel_step2.setLayout(BorderLayout()) self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH) self.titlepanel_step2.add(self.labelsubtitle_step2) self.selectpanel_step2 = JPanel() self.selectpanel_step2.add(self.labelip) self.selectpanel_step2.add(self.upnpcombo_targets) self.selectpanel_step2.add(self.labelupnp) self.selectpanel_step2.add(self.upnpcombo_services) self.selectpanel_step2.add(self.labelactions) self.selectpanel_step2.add(self.upnpcombo_actions) self.emptypanel_step2 = JPanel() self.emptypanel_step2.setLayout(BorderLayout()) self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST) self.emptypanel_step2.add(self.labelNoneServiceFound) # Assembling second step panel components self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH) self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST) self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH) self.uiPanelB.setTopComponent(self.panel_step2) # Configuring third step panel self.panel_step3 = JPanel() self.panel_step3.setPreferredSize(Dimension(2250, 100)) self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10)) self.panel_step3.setLayout(BorderLayout(15, 15)) self.titlepanel_step3 = JPanel() self.titlepanel_step3.setLayout(BorderLayout()) self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH) self.titlepanel_step3.add(self.labelsubtitle_step3) self.underpanel_step3 = JPanel() self.underpanel_step3.setLayout(BorderLayout()) self.underpanel_step3.add((JScrollPane(self.textarea_request)), BorderLayout.NORTH) self.actionpanel_step3 = JPanel() self.actionpanel_step3.add(self.intruderbutton) self.actionpanel_step3.add(self.repeaterbutton) self.extrapanel_step3 = JPanel() self.extrapanel_step3.setLayout(BorderLayout()) self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST) # Assembling thirdd step panel components self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH) self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST) self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH) self.uiPanelB.setBottomComponent(self.panel_step3) # Assembling the group of all panels layout = GroupLayout(self.pluginTab) self.pluginTab.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(10, 10, 10).addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA)).addContainerGap( 26, Short.MAX_VALUE))) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(15, 15, 15).addComponent( self.uiTitle).addGap(15, 15, 15).addComponent( self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20))) def extensionUnloaded(self): # Unload the plugin, and if running stop the background thread if self.upnpcombo_services.isEnabled(): if self.th.isAlive(): print("[+] Stopping thread %s") % self.th.getName() self.STOP_THREAD = True self.th.join() else: print("Thread %s already dead") % self.th.getName() print("[+] Burp plugin UPnP BHunter successfully unloaded") return def getTabCaption(self): return self.EXTENSION_NAME def getUiComponent(self): return self.pluginTab def clearAll(self, e=None): # Reset all data of the plugin self.services_dict.clear() self.progressbar.setString("Ready") self.progressbar.setValue(0) self.upnpcombo_targets.removeAllItems() self.upnpcombo_targets.setEnabled(False) self.upnpcombo_services.removeAllItems() self.upnpcombo_services.setEnabled(False) self.upnpcombo_actions.removeAllItems() self.upnpcombo_actions.setEnabled(False) self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) self.labelNoneServiceFound.setText(" ") self.textarea_request.setText(" ") print("[+] Clearing all data") return def startHunting(self, e=None): # Starting the UPnP hunt def startHunting_run(): # Initialize the internal parameters every time the start-discovery button is clicked self.services_dict.clear() found_loc = [] discovery_files = [] self.labelNoneServiceFound.setText(" ") self.intruderbutton.setEnabled(False) self.repeaterbutton.setEnabled(False) # Then determine if targerting IPv4 or IPv6 adresses if self.combo_ipversion.getSelectedItem() == "IPv4": self.ipv4_selected = True print("[+] Selected IPv4 address scope") else: self.ipv4_selected = False print("[+] Selected IPv6 address scope") # And here finally the hunt could start self.progressbar.setString("Running...") self.progressbar.setValue(20) found_loc = self.discoverUpnpLocations() self.progressbar.setValue(40) discovery_files = self.downloadXMLfiles(found_loc) self.progressbar.setValue(60) self.buildSOAPs(discovery_files) self.progressbar.setValue(80) self.progressbar.setString("Done") self.progressbar.setValue(100) self.updateComboboxList(self.services_dict) # Update the comboboxes list with the discovered UPnPs if (self.services_dict): self.upnpcombo_targets.setEnabled(True) self.upnpcombo_services.setEnabled(True) self.upnpcombo_actions.setEnabled(True) self.intruderbutton.setEnabled(True) self.repeaterbutton.setEnabled(True) if self.STOP_THREAD: return # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI self.th = threading.Thread(target=startHunting_run) #self.th.daemon = True # This does not seem to be useful self.th.setName("th-BHunter") self.th.start() def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port): # Builder of the two ssdp msearch request types msearch_req = "M-SEARCH * HTTP/1.1\r\n" \ "HOST: {0}:{1}\r\n" \ "MAN: \"ssdp:discover\"\r\n" \ "MX: {2}\r\n" \ "ST: {3}\r\n" \ "\r\n" \ .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type) return msearch_req def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port): # Send the ssdp request and retrieve response buf_resp = set() if self.ipv4_selected: print("[+] Creating IPv4 SSDP multicast request") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: print("[+] Creating IPv6 SSDP multicast request") sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setblocking(0) # Sending ssdp requests while len(ssdp_req): # Blocking socket client until the request is completely sent try: sent = sock.sendto(ssdp_req.encode("ASCII"), (ssdp_ip, ssdp_port)) ssdp_req = ssdp_req[sent:] except socket.error, exc: if exc.errno != errno.EAGAIN: print("[E] Got error %s with socket when sending") % exc sock.close() raise exc print("[!] Blocking socket until ", len(ssdp_req), " is sent.") select.select([], [sock], []) continue # Retrieving ssdp responses num_resp = 0 while sock: # Blocking socket until there are ssdp responses to be read or timeout is reached readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT) if not readable: # Timeout reached without receiving any ssdp response if num_resp == 0: print( "[!] Got timeout without receiving any ssdp response.") break else: num_resp = num_resp + 1 # Almost an ssdp response was received if readable[0]: try: data = sock.recv(1024) if data: buf_resp.add(data.decode('ASCII')) except socket.error, exc: print("[E] Got error %s with socket when receiving" ) % exc sock.close() raise exc
def main(): all_files = currentSelectedItems total = len(all_files) jprog = JProgressBar(0, total) jprog.setStringPainted(True) jframe.getContentPane().add(jprog) jframe.getContentPane().add(jbutton) jframe.setVisible(True) try: statusLabel.setText("Selected " + str(total) + " items") discovered = 0 for idx, item in enumerate(all_files): if cancelled: return "User cancelled" jprog.setValue(idx) statusLabel.setText("Processing %d of %d" % (idx, total)) md5 = item.digests.md5 # Item needs an md5 to check against, so move on if there isn't one if not md5: continue response = send_request(md5) if not response: return cm = item.getCustomMetadata() if response == "404": cm.putText("VirusTotal", "Item md5 not matched in database") else: data = json.load(response) malicious = data["data"]["attributes"]["last_analysis_stats"]["malicious"] if malicious > 0: discovered += 1 cm.putInteger("AVs identifying item as malicious", malicious) for scanner, res in data["data"]["attributes"]["last_analysis_results"].iteritems(): if res["result"] is not None: cm.putText("VirusTotal " + scanner, res["result"]) # vHash if SET_VHASH and ("vhash" in data["data"]["attributes"]): cm.putText("vHash", data["data"]["attributes"]["vhash"]) # Import Hash if SET_IMPHASH and ("pe_info" in data["data"]["attributes"]) and \ ("imphash" in data["data"]["attributes"]["pe_info"]): cm.putText("Import Hash", data["data"]["attributes"]["pe_info"]["imphash"]) # Authentihash if SET_AUTHENTIHASH and ("authentihash" in data["data"]["attributes"]): cm.putText("Authentihash", data["data"]["attributes"]["authentihash"]) # Crowd sourced yara results if SET_YARA and ("crowdsourced_yara_results" in data["data"]["attributes"]): yara_matches = [] for yara in data["data"]["attributes"]["crowdsourced_yara_results"]: yara_matches += [yara["rule_name"]] cm.putText("Matched Yara Rules", ", ".join(yara_matches)) # Virus Total defined tags. Often this can be a list that needs to be looped through if SET_TAGS and ("tags" in data["data"]["attributes"]): for tag in data["data"]["attributes"]["tags"]: item.addTag("VirusTotal|" + tag) time.sleep(SLEEP_TIME) jprog.setValue(total) statusLabel.setText("Done") return "VirusTotal Search has finished. %d potentially malicious items found from the %d selected." % (discovered, total) except Exception: import traceback print('generic exception: ' + traceback.format_exc()) return
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame def __init__(self): self.mainDir = "" self.setTitle("Dots Quality Check") self.setSize(250, 300) self.setLocation(20,120) self.addWindowFocusListener(self) self.Panel = JPanel(GridLayout(0,1)) self.add(self.Panel) self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False) self.Panel.add(self.saveButton) self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell) self.Panel.add(self.DiscardButton) self.quitButton = JButton("Quit script",actionPerformed=self.quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout self.wtRButton = JRadioButton("wt", actionCommand="wt") self.wtRButton.addActionListener(self) self.defectRButton = JRadioButton("Defect", actionCommand="defect") self.defectRButton.addActionListener(self) annoPanel.add(self.wtRButton) annoPanel.add(self.defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(self.wtRButton) self.aButtonGroup.add(self.defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self) self.show() # - - - - B U T T O N M E T H O D S - - - - # - - - - - - - - - - - - - - - - - - - - - - - def openRandom(self, event): # when click here: get random cell and meas.measure(csv, tif, savePath) if self.mainDir == "": self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory() self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0])) try: # should be complete disposal! self.cT.closeWindows() finally: inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv")) # glob.glob returns list of paths uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False] if len(uncheckedCells) > 0: self.cell = random.choice(uncheckedCells) #update progressbar self.ProgBar.setMaximum(len(inFiles)-1) self.ProgBar.setValue(len(inFiles)-len(uncheckedCells)) # open imp and resultstable self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF self.RBActionListener.setCell(self.cell) # delete previous Radiobutton annotation self.wtRButton.setSelected(False) self.defectRButton.setSelected(True) else: print "All cells measured!" def save(self, event): savepath = self.cell.getQcCsvPath() anaphase = self.cell.getAnOn() timeInterval = self.cT.getImp().getCalibration().frameInterval annotation = self.getAnnotation() position = str(self.cell.position) cellIndex = str(self.cell.cellNo) if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present. os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present f = open(savepath, "w") # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n") for i in range(self.cT.getLineCount()): frame, distance, a = self.cT.getLine(i).split("\t") corrFrame = str(int(frame)-int(anaphase)) time = "%.f" % (round(timeInterval) * int(corrFrame)) if distance == "NA": ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",") else: ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i] f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol) f.close() print "Successfully saved!" def cropVals(self, event): #"this function deletes all values with frame > current cursor" for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1): frame, distance, AOCol = self.cT.getLine(line).split("\t") self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol) def discardCell(self, event): if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present. os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present. f = open(self.cell.getQcCsvPath() ,"w") # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n") f.close() print "Discarded cell - saved dummy" def quit(self, event): try: self.cT.closeWindows() finally: WindowManager.removeWindow(self) self.dispose() # Methods implementing ActionListener interfaces: def actionPerformed(self, e): # this function is called when RadioButtons are changed self.cell.annotate( e.getSource().getActionCommand() ) self.setSaveActive() def windowGainedFocus(self, e): pass def windowLostFocus(self, e): pass # - - - - - - - - - - - - - # - get and set methods - - # - - - - - - - - - - - - - def getAnnotation(self): return self.aButtonGroup.getSelection().getActionCommand() def getMainDir(self): return self.mainDir def setSaveActive(self): if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None): self.saveButton.setEnabled(True) self.show() def setSaveInactive(self): self.saveButton.setEnabled(False) self.show() def setMainDir(self, path): self.mainDir = path self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))