class win(JFrame): def __init__(self, title="Consumo Electrico"): JFrame(title) self.setLayout(None) self.setBounds(10, 10, 300, 180) self.show() self.build() def build(self): self.label = JLabel("Cup") self.label.setBounds(120, 10, 45, 15) self.label2 = JLabel("KWh") self.label2.setBounds(20, 10, 45, 15) self.label3 = JLabel() self.label3.setBounds(120, 30, 55, 15) self.textfield = JTextField() self.textfield.setBounds(15, 30, 75, 20) self.textfield.addActionListener(lambda x: self.label3.setText( str(calculate(self.textfield.getText())))) button = JButton("Calcular") button.setBounds(10, 55, 290, 35) button.addActionListener(lambda x: self.label3.setText( str(calculate(self.textfield.getText())))) for var in [ self.label, self.label2, self.label3, self.textfield, button ]: self.add(var)
def getUiComponent(self): panel = JPanel(BorderLayout()) panel.setLocation(100, 100) panel.setLayout(None) lbl1 = JLabel("Insert URL") lbl1.setBounds(60, 20, 100, 40) txt1 = JTextField(100) txt1.setBounds(140, 20, 600, 40) def btn1Click(event): import requests from bs4 import BeautifulSoup url = requests.get("http://" + str(txt1.text)) # a=requests.get(str(txt1.text)) req = url.text links = [] soup = BeautifulSoup(url.text, 'html.parser') for link in soup.find_all('a'): links.append(link.get('href')) links = ((str(links).replace("[", "")).replace("]", "")).replace("u'", "'") txt2.text = links #set info por table2 txt2.editable = False txt2.wrapStyleWord = True txt2.lineWrap = True text2.aligmentx = Component.LEFT_ALIGMENT txt2.size(300, 1) return btn = JButton("Click", actionPerformed=btn1Click) btn.setBounds(400, 80, 60, 30) panel.add(lbl1, BorderLayout.CENTER) panel.add(txt1, BorderLayout.CENTER) panel.add(btn, BorderLayout.CENTER) lbl2 = JLabel("Output URLs") lbl2.setBounds(60, 80, 150, 40) txt2 = JTextArea() txt2.setBounds(140, 120, 600, 600) txt2.setBackground(Color.WHITE) # set table color, if you want panel.add(lbl2, BorderLayout.CENTER) panel.add(txt2, BorderLayout.CENTER) return panel
def showLoginIdPassword(data): global frame frame = JFrame("Show Id Password ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,350) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,350) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("LoginId AND Password") heading.setBounds(200,30,150,40) lbLoginId = JLabel("LoginId") lbPassword = JLabel("password") tfLoginId = JTextField(data[0].encode('ascii')) tfPassword = JTextField(data[1].encode('ascii')) tfLoginId.setEditable(False) tfPassword.setEditable(False) lbLoginId.setBounds(50,100,150,30) lbPassword.setBounds(50,150,150,30) tfLoginId.setBounds(220,100,150,30) tfPassword.setBounds(220,150,150,30) btnOk = JButton("Ok",actionPerformed=clickOk) btnOk.setBounds(250,220,100,30) panel.add(heading) panel.add(lbLoginId) panel.add(lbPassword) panel.add(tfLoginId) panel.add(tfPassword) panel.add(btnOk) frame.add(panel)
def gui(self): # Hilfsfunktion für event # erstellt ein Rezeptobjekt anhand einer URL # schließt die GUI def create(event): url = field.getText() self.recipe = Recipe(url) frame.dispose() print("created recipe for " + self.recipe.get_title()) # der Dialog wartet, bis "continue" gesendet wird self.send("continue") # Frame erstellen frame = JFrame( 'URL eingeben', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(480, 200), ) frame.setLayout(None) # Text im Frame fieldlabel = JLabel() fieldlabel.setText( "<html><font size=+1>Geben Sie die Internetadresse des Rezepts ein</font></html>" ) fieldlabel.setBounds(20, 20, 500, 40) frame.add(fieldlabel) # Textfeld im Frame field = JTextField() field.setText("https://www.chefkoch.de/rezepte/...") field.setBounds(20, 60, 411, 40) frame.add(field) # Button im Frame # ruft Hilfsfunktion create auf button = JButton("Los!", actionPerformed=create) button.setBounds(155, 100, 150, 30) frame.add(button) #Frame anzeigen frame.setVisible(True)
def getCourseName(check): global frame global tfStudentCourseChoice global value value = check frame = JFrame("Course Name ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,250) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,250) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("Get Course Name") heading.setBounds(200,30,150,40) lbStudentCourseChoice = JLabel("Student course name") tfStudentCourseChoice = JTextField() lbStudentCourseChoice.setBounds(50,70,150,30) tfStudentCourseChoice.setBounds(220,70,150,30) btnEnter = JButton("Enter",actionPerformed=clickStudentCourseChoice) btnCancel = JButton("Cancel",actionPerformed=clickBtnCancel) btnEnter.setBounds(350,150,100,30) btnCancel.setBounds(50,150,100,30) panel.add(heading) panel.add(lbStudentCourseChoice) panel.add(tfStudentCourseChoice) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
def build(self): #labels cl = JLabel("Celcius") cl.setBounds(10, 10, 60, 20) fl = JLabel("Farenheit") fl.setBounds(120, 10, 60, 20) kl = JLabel("Kelvin") kl.setBounds(230, 10, 60, 20) #celcius textfield c = JTextField() c.setBounds(10, 40, 60, 20) c.addActionListener(lambda x: log(x)) #farenheit textfield f = JTextField() f.setBounds(120, 40, 60, 20) f.addActionListener(lambda x: log(x)) #kelvin textfield k = JTextField() k.setBounds(230, 40, 60, 20) k.addActionListener(lambda x: log(x)) #buttons cv = JButton("Convert") cv.addActionListener(lambda x: self.convert(x)) cv.setBounds(10, 70, 300 - 10, 30) clean = JButton("Clean") clean.addActionListener(lambda x: self.clean()) clean.setBounds(10, 110, 300 - 10, 30) #add vars to frame list(map(lambda x: self.add(x), [cl, kl, fl, c, f, k, cv, clean])) self.k = k self.c = c self.f = f self.textfields = {self.c, self.f, self.k}
def install(helper): print('install called'); frame = JFrame("Please Input Values") frame.setLocation(100,100) frame.setSize(500,400) frame.setLayout(None) lbl1 = JLabel("Input1: ") lbl1.setBounds(60,20,60,20) txt1 = JTextField(100) txt1.setBounds(130,20,200,20) lbl2 = JLabel("Input2: ") lbl2.setBounds(60,50,100,20) txt2 = JTextField(100) txt2.setBounds(130,50,200,20) lbl3 = JLabel("Input3: ") lbl3.setBounds(60,80,140,20) txt3 = JTextField(100) txt3.setBounds(130,80,200,20) lbl4 = JLabel("Input4: ") lbl4.setBounds(60,110,180,20) txt4 = JTextField(100) txt4.setBounds(130,110,200,20) def getValues(event): print "clicked" ScriptVars.setGlobalVar("Input1",str(txt1.getText())) print(ScriptVars.getGlobalVar("Input1")) ScriptVars.setGlobalVar("Input2",str(txt2.getText())) print(ScriptVars.getGlobalVar("Input2")) ScriptVars.setGlobalVar("Input3",str(txt3.getText())) print(ScriptVars.getGlobalVar("Input3")) ScriptVars.setGlobalVar("Input4",str(txt4.getText())) print(ScriptVars.getGlobalVar("Input4")) btn = JButton("Submit", actionPerformed = getValues) btn.setBounds(160,150,100,20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.add(lbl4) frame.add(txt4) frame.setVisible(True)
def changePasswordForm(check): global frame global tfOldPassword global tfNewPassword global tfConfirmPassword global value value = check frame = JFrame("Change Password") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 350) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 350) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("Change Password") heading.setBounds(200, 30, 150, 40) lbOldPassword = JLabel("Old Password") lbNewPassword = JLabel("New Password") lbConfirmPassword = JLabel("Confirm Password") tfOldPassword = JTextField() tfNewPassword = JTextField() tfConfirmPassword = JTextField() lbOldPassword.setBounds(50, 100, 150, 30) lbNewPassword.setBounds(50, 150, 150, 30) lbConfirmPassword.setBounds(50, 200, 150, 30) tfOldPassword.setBounds(220, 100, 150, 30) tfNewPassword.setBounds(220, 150, 150, 30) tfConfirmPassword.setBounds(220, 200, 150, 30) btnSave = JButton("Save", actionPerformed=clickSave) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnSave.setBounds(350, 280, 100, 30) btnCancel.setBounds(50, 280, 100, 30) panel.add(heading) panel.add(lbOldPassword) panel.add(lbNewPassword) panel.add(lbConfirmPassword) panel.add(tfOldPassword) panel.add(tfNewPassword) panel.add(tfConfirmPassword) panel.add(btnSave) panel.add(btnCancel) frame.add(panel)
def install(helper): print('install called') frame = JFrame("Please Input Values") frame.setLocation(100, 100) frame.setSize(500, 400) frame.setLayout(None) lbl1 = JLabel("Input1: ") lbl1.setBounds(60, 20, 60, 20) txt1 = JTextField(100) txt1.setBounds(130, 20, 200, 20) lbl2 = JLabel("Input2: ") lbl2.setBounds(60, 50, 100, 20) txt2 = JTextField(100) txt2.setBounds(130, 50, 200, 20) lbl3 = JLabel("Input3: ") lbl3.setBounds(60, 80, 140, 20) txt3 = JTextField(100) txt3.setBounds(130, 80, 200, 20) lbl4 = JLabel("Input4: ") lbl4.setBounds(60, 110, 180, 20) txt4 = JTextField(100) txt4.setBounds(130, 110, 200, 20) def getValues(event): print "clicked" ScriptVars.setGlobalVar("Input1", str(txt1.getText())) print(ScriptVars.getGlobalVar("Input1")) ScriptVars.setGlobalVar("Input2", str(txt2.getText())) print(ScriptVars.getGlobalVar("Input2")) ScriptVars.setGlobalVar("Input3", str(txt3.getText())) print(ScriptVars.getGlobalVar("Input3")) ScriptVars.setGlobalVar("Input4", str(txt4.getText())) print(ScriptVars.getGlobalVar("Input4")) btn = JButton("Submit", actionPerformed=getValues) btn.setBounds(160, 150, 100, 20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.add(lbl4) frame.add(txt4) frame.setVisible(True)
def addCourse(): global tfCourseName global tfCourseId global tfCourseFee global frame global btnEnter frame = JFrame("Add Course ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(450, 450) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(450, 450) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("ADD COURSE") heading.setBounds(200, 30, 150, 40) lbCourseName = JLabel("Course Name ") lbCourseId = JLabel("Course Id") lbCourseFee = JLabel(" Course Fee") tfCourseName = JTextField() tfCourseId = JTextField() tfCourseFee = JTextField() lbCourseName.setBounds(70, 120, 130, 30) lbCourseId.setBounds(70, 170, 130, 30) lbCourseFee.setBounds(70, 220, 130, 30) tfCourseName.setBounds(220, 120, 150, 30) tfCourseId.setBounds(220, 170, 150, 30) tfCourseFee.setBounds(220, 220, 150, 30) btnEnter = JButton("Enter", actionPerformed=clickAddCourseFee) btnEnter.setBounds(300, 300, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnCancel.setBounds(70, 300, 100, 40) panel.add(heading) panel.add(lbCourseName) panel.add(lbCourseId) panel.add(lbCourseFee) panel.add(tfCourseFee) panel.add(tfCourseName) panel.add(tfCourseId) panel.add(tfCourseFee) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
def addDetails(self): jf0 = JFrame() jf0.setTitle("Add Issue"); jf0.setLayout(None); txtEnterIssue = JTextField(); txtEnterIssue.setName("Enter Issue Name"); txtEnterIssue.setToolTipText("Enter Issue Name Here"); txtEnterIssue.setBounds(182, 58, 473, 40); jf0.add(txtEnterIssue); txtEnterIssue.setColumns(10); btnNewButton = JButton("Add"); btnNewButton.setBounds(322, 178, 139, 41); jf0.add(btnNewButton); comboBox = JComboBox(); comboBox.setMaximumRowCount(20); comboBox.setEditable(True); comboBox.setToolTipText("Objective Name"); comboBox.setBounds(182, 125, 473, 40); jf0.add(comboBox); lblNewLabel = JLabel("Issue Name Here"); lblNewLabel.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel.setBounds(25, 58, 130, 40); jf0.add(lblNewLabel); lblNewLabel_1 = JLabel("Objective Name"); lblNewLabel_1.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel_1.setBounds(25, 125, 130, 40); jf0.add(lblNewLabel_1); jf0.setVisible(True) jf0.setBounds(400, 300, 700, 300) jf0.EXIT_ON_CLOSE txtEnterIssue.addKeyListener(self)
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IExtensionStateListener, IHttpRequestResponse): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("burp-unauth-checker") #callbacks.issueAlert("burp-unauth-checker Passive Scanner enabled") stdout = PrintWriter(callbacks.getStdout(), True) stderr = PrintWriter(callbacks.getStderr(), True) self._callbacks.registerScannerCheck(self) self._callbacks.registerExtensionStateListener(self) self.authParamsList = self.getAuthParamConfig() self.initUI() self._callbacks.addSuiteTab(self) print("burp-unauth-checker loaded.") print("Author:LSA") print("https://github.com/theLSA/burp-unauth-checker") self.outputTxtArea.setText("") self.excludeAuthParamsList = self.getExcludeAuthParams() print 'authParamsList: ' + str(self.authParamsList) + '\n' if self.excludeAuthParamsList != None: self.authParamsList = list( set(self.authParamsList).difference( set(self.excludeAuthParamsList))) print 'excludeAuthParamsList: ' + str( self.excludeAuthParamsList) + '\n' print "finalAuthParamsList: " + ",".join( self.authParamsList) + "\n" def extensionUnloaded(self): print "burp-unauth-checker Unloaded." return def doPassiveScan(self, baseRequestResponse): islaunchBurpUnauthChecker = int( self.launchBurpUnauthCheckerCheckBox.isSelected()) if (not islaunchBurpUnauthChecker) or ( self.isFilterSuffix(baseRequestResponse)) or ( self.isFilterStatusCode(baseRequestResponse)): return scan_issues = [] newRequestResponse = self.sendUnauthenticatedRequest( baseRequestResponse) #print str(self._helpers.analyzeRequest(baseRequestResponse).getUrl()) + '\n' issue = self.compareResponses(newRequestResponse, baseRequestResponse) scan_issues.append(issue) return scan_issues def consolidateDuplicateIssues(self, isb, isa): return -1 def sendUnauthenticatedRequest(self, requestResponse): newRequest = self.stripAuthenticationCharacteristics(requestResponse) return self._callbacks.makeHttpRequest( requestResponse.getHttpService(), newRequest) def stripAuthenticationCharacteristics(self, requestResponse): self.excludeAuthParamsList = self.getExcludeAuthParams() print 'authParamsList: ' + str(self.authParamsList) + '\n' if self.excludeAuthParamsList != None: self.authParamsList = list( set(self.authParamsList).difference( set(self.excludeAuthParamsList))) #print 'authParamsList: ' + str(self.authParamsList) + '\n' print 'excludeAuthParamsList: ' + str( self.excludeAuthParamsList) + '\n' print "finalAuthParamsList: " + ",".join( self.authParamsList) + "\n" reqHeaders = self._helpers.analyzeRequest(requestResponse).getHeaders() reqBodyOffset = self._helpers.analyzeRequest( requestResponse).getBodyOffset() reqBodyByte = requestResponse.getRequest().tostring()[reqBodyOffset:] newHeaders = [] newAuthHeaderVal = self.replaceHeaderValWithTextField.getText() for header in reqHeaders: headerName = header.split(':')[0] # if headerName.lower() not in self.authParamsList: # newHeaders.append(header) #return self._helpers.buildHttpMessage(newHeaders, None) if headerName.lower() in self.authParamsList: header = headerName + ": " + newAuthHeaderVal newHeaders.append(header) else: newHeaders.append(header) #newRemoveAuthHeaderRequest = self._helpers.buildHttpMessage(newHeaders, None) newRemoveAuthHeaderRequest = self._helpers.buildHttpMessage( newHeaders, reqBodyByte) if self.removeGetPostAuthParamsCheckBox.isSelected(): newRemoveGetPostAuthParamsRequest = self.removeGetPostAuthParams( requestResponse, newRemoveAuthHeaderRequest, self.authParamsList) if newRemoveGetPostAuthParamsRequest: #print newRemoveGetPostAuthParamsRequest return newRemoveGetPostAuthParamsRequest else: return self._helpers.buildHttpMessage(newHeaders, reqBodyByte) else: return self._helpers.buildHttpMessage(newHeaders, reqBodyByte) def compareResponses(self, newRequestResponse, oldRequestResponse): """Compare new rsp and old rsp body contents""" result = None nResponse = newRequestResponse.getResponse() if nResponse is None: return result nResponseInfo = self._helpers.analyzeResponse(nResponse) # Only considering non-cached HTTP responses if nResponseInfo.getStatusCode() == 304: return result nBodyOffset = nResponseInfo.getBodyOffset() nBody = nResponse.tostring()[nBodyOffset:] oResponse = oldRequestResponse.getResponse() oResponseInfo = self._helpers.analyzeResponse(oResponse) oBodyOffset = oResponseInfo.getBodyOffset() oBody = oResponse.tostring()[oBodyOffset:] #print 'oBody:' + str(oBody) + '\n' #print 'nBody:' + str(nBody) + '\n' #self.outputTxtArea.append("[url]%s\n" % self._helpers.analyzeRequest(oldRequestResponse).getUrl()) isShowRspContent = int(self.showRspContentCheckBox.isSelected()) isShowPostBody = int(self.showPostBodyCheckBox.isSelected()) if (str(nBody).split() == str(oBody).split()): self.outputTxtArea.append( "[%s][URL]%s\n" % (self._helpers.analyzeRequest(oldRequestResponse).getMethod(), self._helpers.analyzeRequest(oldRequestResponse).getUrl())) if isShowPostBody: oldReqBodyOffset = self._helpers.analyzeRequest( oldRequestResponse).getBodyOffset() oldReqBodyString = oldRequestResponse.getRequest().tostring( )[oldReqBodyOffset:] self.outputTxtArea.append("%s\n" % oldReqBodyString) if isShowRspContent: self.outputTxtArea.append("[rspContent]%s\n" % str(nBody)) self.outputTxtArea.append( "\n------------------------------------------------------------------------\n" ) issuename = "unauth-endpoint" issuelevel = "Medium" issuedetail = "Unauthorization endpoint." issuebackground = "The endpoint is unauthorizated." issueremediation = "Senstive endpoint must have authorization." issueconfidence = "Firm" result = ScanIssue( oldRequestResponse.getHttpService(), self._helpers.analyzeRequest(oldRequestResponse).getUrl(), issuename, issuelevel, issuedetail, issuebackground, issueremediation, issueconfidence, [oldRequestResponse, newRequestResponse]) print result return result else: print "body difference!\n" def initUI(self): self.tab = swing.JPanel() # UI for Output self.outputLabel = swing.JLabel("unauth api result:") self.outputLabel.setFont(Font("Tahoma", Font.BOLD, 14)) self.outputLabel.setForeground(Color(255, 102, 52)) self.logPane = swing.JScrollPane() self.outputTxtArea = swing.JTextArea() self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12)) self.outputTxtArea.setLineWrap(True) self.logPane.setViewportView(self.outputTxtArea) self.clearBtn = swing.JButton("Clear", actionPerformed=self.clearRst) self.exportBtn = swing.JButton("Export", actionPerformed=self.exportRst) self.parentFrm = swing.JFileChooser() self.showRspContentCheckBox = JCheckBox("show rspContent") self.showPostBodyCheckBox = JCheckBox("show post body") self.launchBurpUnauthCheckerCheckBox = JCheckBox( "launchBurpUnauthChecker") #self.includeAuthParamsLabel = swing.JLabel("includeAuthParams:") self.excludeAuthParamsLabel = swing.JLabel("excludeAuthParams:") self.filterSuffixLabel = swing.JLabel("filterSuffix:") self.removeAuthParamListText = self.authParamsList #print self.removeAuthParamListText self.removeAuthParamListTextField = JTextField(",".join( self.removeAuthParamListText)) self.excludeAuthParamsTextField = JTextField() self.filterSuffixTextField = JTextField(filterSuffixList) self.onlyIncludeStatusCodeTextField = JTextField("200") self.onlyIncludeStatusCodeLabel = JLabel("onlyIncludeStatusCode:") self.saveAuthParamsListButton = swing.JButton( "save", actionPerformed=self.addAndSaveAuthParam) self.alertSaveSuccess = JOptionPane() self.removeGetPostAuthParamsCheckBox = JCheckBox( "replace GET/POST Auth Params with ") self.replaceGetPostAuthParamsWithTextField = JTextField("unauthp") self.replaceHeaderValWithLabel = JLabel("replace header value with ") self.replaceHeaderValWithTextField = JTextField("unauthh") self.tab.setLayout(None) self.tab.add(self.launchBurpUnauthCheckerCheckBox) self.tab.add(self.showRspContentCheckBox) self.tab.add(self.showPostBodyCheckBox) self.tab.add(self.outputLabel) self.tab.add(self.logPane) self.tab.add(self.clearBtn) self.tab.add(self.exportBtn) self.tab.add(self.removeAuthParamListTextField) #self.tab.add(self.includeAuthParamsLabel) self.tab.add(self.excludeAuthParamsLabel) self.tab.add(self.filterSuffixLabel) self.tab.add(self.excludeAuthParamsTextField) self.tab.add(self.filterSuffixTextField) self.tab.add(self.onlyIncludeStatusCodeTextField) self.tab.add(self.onlyIncludeStatusCodeLabel) self.tab.add(self.saveAuthParamsListButton) self.tab.add(self.alertSaveSuccess) self.tab.add(self.removeGetPostAuthParamsCheckBox) self.tab.add(self.replaceGetPostAuthParamsWithTextField) self.tab.add(self.replaceHeaderValWithTextField) self.tab.add(self.replaceHeaderValWithLabel) self.launchBurpUnauthCheckerCheckBox.setBounds(20, 10, 200, 20) self.showRspContentCheckBox.setBounds(20, 40, 150, 30) self.showPostBodyCheckBox.setBounds(20, 75, 150, 30) self.outputLabel.setBounds(400, 200, 150, 50) self.logPane.setBounds(20, 250, 900, 400) self.clearBtn.setBounds(20, 650, 100, 30) self.exportBtn.setBounds(820, 650, 100, 30) self.removeAuthParamListTextField.setBounds(20, 140, 400, 30) #self.includeAuthParamsLabel.setBounds(20,100,100,20) self.excludeAuthParamsLabel.setBounds(580, 100, 150, 20) self.excludeAuthParamsTextField.setBounds(580, 120, 400, 30) self.filterSuffixLabel.setBounds(200, 40, 100, 20) self.filterSuffixTextField.setBounds(200, 60, 500, 30) self.onlyIncludeStatusCodeTextField.setBounds(750, 170, 120, 30) self.onlyIncludeStatusCodeLabel.setBounds(600, 170, 190, 20) self.saveAuthParamsListButton.setBounds(20, 180, 80, 30) self.removeGetPostAuthParamsCheckBox.setBounds(120, 170, 280, 20) self.replaceGetPostAuthParamsWithTextField.setBounds(380, 170, 70, 30) self.replaceHeaderValWithLabel.setBounds(20, 100, 180, 20) self.replaceHeaderValWithTextField.setBounds(190, 100, 70, 30) def getTabCaption(self): return "burp-unauth-checker" def getUiComponent(self): return self.tab def clearRst(self, event): self.outputTxtArea.setText("") def exportRst(self, event): chooseFile = JFileChooser() ret = chooseFile.showDialog(self.logPane, "Choose file") filename = chooseFile.getSelectedFile().getCanonicalPath() print "\n" + "Export to : " + filename open(filename, 'w', 0).write(self.outputTxtArea.text) def getAuthParamConfig(self): authFieldList = [] with open(authParamCfgFile, "r") as fauth: #authFieldList = fauth.readlines() for authParamLine in fauth.readlines(): authFieldList.append(authParamLine.strip()) #print authFieldList return authFieldList def getFilterSuffixList(self): filterSuffixList = [] filterSuffixList = self.filterSuffixTextField.getText().split(",") print filterSuffixList return filterSuffixList def getExcludeAuthParams(self): excludeAuthParamsList = [] excludeAuthParamsList = self.excludeAuthParamsTextField.getText( ).split(",") #print excludeAuthParamsList return excludeAuthParamsList def checkStatusCode(self): filterStatusCodeList = [] filterStatusCodeList = self.onlyIncludeStatusCodeTextField.getText( ).split(",") print "Only check thoes status code: " + ",".join(filterStatusCodeList) return filterStatusCodeList def isFilterSuffix(self, requestResponse): reqUrl = str(self._helpers.analyzeRequest(requestResponse).getUrl()) print reqUrl + '\n' try: reqUrlSuffix = os.path.basename(reqUrl).split(".")[-1].split( "?")[0].lower() except: reqUrlSuffix = "causeExceptionSuffix" if reqUrlSuffix == "": reqUrlSuffix = "spaceSuffix" print reqUrlSuffix if (reqUrlSuffix in self.getFilterSuffixList()) and ( reqUrlSuffix != "causeExceptionSuffix") and (reqUrlSuffix != "spaceSuffix"): print 'filterSuffix: ' + reqUrlSuffix print 'filterUrl: ' + reqUrl return True def isFilterStatusCode(self, requestResponse): baseResponse = requestResponse.getResponse() baseResponseInfo = self._helpers.analyzeResponse(baseResponse) if str(baseResponseInfo.getStatusCode()) not in self.checkStatusCode(): print baseResponseInfo.getStatusCode() return True def addAndSaveAuthParam(self, event): oldAuthParamsList = [] oldAuthParamsList = self.authParamsList newAuthParamsList = [] newAuthParamsList = self.removeAuthParamListTextField.getText().split( ",") addAuthParamsList = list( set(newAuthParamsList).difference(set(oldAuthParamsList))) print addAuthParamsList with open(authParamCfgFile, 'a') as f1: for newAuthParam in addAuthParamsList: f1.write('\n' + newAuthParam) self.authParamsList = self.getAuthParamConfig() self.alertSaveSuccess.showMessageDialog(self.tab, "save success!") def removeGetPostAuthParams(self, requestResponse, newRemoveAuthHeaderRequest, authParamsListNew): paramList = self._helpers.analyzeRequest( requestResponse).getParameters() authParamsList = authParamsListNew newAuthParamValue = self.replaceGetPostAuthParamsWithTextField.getText( ) #print paramList #return paramList newRemoveGetPostAuthParamsRequest = newRemoveAuthHeaderRequest haveRemoveGetPostAuthParams = False #isJsonReq = False for para in paramList: paramType = para.getType() if (paramType == 0) or (paramType == 1): paramKey = para.getName() paramValue = para.getValue() print paramKey + ":" + paramValue if paramKey.lower() in authParamsList: newAuthParam = self._helpers.buildParameter( paramKey, newAuthParamValue, paramType) newRemoveGetPostAuthParamsRequest = self._helpers.updateParameter( newRemoveGetPostAuthParamsRequest, newAuthParam) haveRemoveGetPostAuthParams = True if paramType == 6: paramKey = para.getName() paramValue = para.getValue() print paramKey + ":" + paramValue reqJsonBodyOffset = self._helpers.analyzeRequest( requestResponse).getBodyOffset() reqJsonBodyString = requestResponse.getRequest().tostring( )[reqJsonBodyOffset:] print reqJsonBodyString reqJsonBodyStringDict = json.loads(reqJsonBodyString) #reqJsonBodyStringDict = ast.literal_eval(reqJsonBodyString) for authParamName in authParamsList: if authParamName in reqJsonBodyStringDict.keys(): reqJsonBodyStringDict[ authParamName] = newAuthParamValue ''' ks = reqJsonBodyStringDict.keys() for k in ks: val = reqJsonBodyStringDict.pop(k) if isinstance(val, unicode): val = val.encode('utf8') #elif isinstance(val, dict): # val = encode_dict(val, codec) if isinstance(k, unicode): k = k.encode('utf8') reqJsonBodyStringDict[k] = val #for key in reqJsonBodyStringDict: # key = key.encode('utf8') # reqJsonBodyStringDict[key] = reqJsonBodyStringDict[key].encode('utf8') ''' newReqJsonBodyString = json.dumps(reqJsonBodyStringDict, separators=(',', ':')) jsonReqHeaders = self._helpers.analyzeRequest( newRemoveAuthHeaderRequest).getHeaders() haveRemoveGetPostAuthParams = True #isJsonReq = True #newRemoveGetPostAuthParamsRequest = self._helpers.buildHttpMessage(jsonReqHeaders, str(reqJsonBodyStringDict).replace("': ","':").replace(", '", ",'").replace(", {", ",{")) newRemoveGetPostAuthParamsRequest = self._helpers.buildHttpMessage( jsonReqHeaders, newReqJsonBodyString) if haveRemoveGetPostAuthParams: #requestResponse.setRequest(new_Request) return newRemoveGetPostAuthParamsRequest else: print 'do not haveRemoveGetPostAuthParams\n' return False
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)
def updateTeacherForm(data): global heading global tfTeacherName global tfTeacherPhone global taTeacherAddress global tfTeacherEmail global tfTeacherCourse global tfTeacherPayment global frame global btnEnter frame = JFrame(" Teacher ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 600) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 600) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel(" TEACHER PROFILE") heading.setBounds(200, 30, 150, 40) lbTeacherName = JLabel("Teacher Name ") lbTeacherPhone = JLabel("Phone") lbTeacherEmail = JLabel("Email") lbTeacherAddress = JLabel("Address") lbTeacherCourse = JLabel("Teacher Course ") lbTeacherPayment = JLabel("Teacher Payment") teacherName = data[0].encode('ascii') teacherPhone = data[1].encode('ascii') teacherEmail = data[2].encode('ascii') teacherAddress = data[3].encode('ascii') teacherCourse = data[4].encode('ascii') teacherPayment = data[5] tfTeacherName = JTextField(teacherName) tfTeacherPhone = JTextField(teacherPhone) taTeacherAddress = JTextArea(teacherAddress) tfTeacherEmail = JTextField(teacherEmail) tfTeacherCourse = JTextField(teacherCourse) tfTeacherPayment = JTextField(str(teacherPayment)) tfTeacherCourse.setEditable(False) tfTeacherPayment.setEditable(False) tfTeacherName.setEditable(False) lbTeacherName.setBounds(70, 100, 130, 30) lbTeacherPhone.setBounds(70, 150, 130, 30) lbTeacherEmail.setBounds(70, 200, 130, 30) lbTeacherAddress.setBounds(70, 250, 130, 30) lbTeacherCourse.setBounds(70, 350, 130, 30) lbTeacherPayment.setBounds(70, 400, 130, 30) tfTeacherName.setBounds(220, 100, 130, 30) tfTeacherPhone.setBounds(220, 150, 130, 30) tfTeacherEmail.setBounds(220, 200, 130, 30) taTeacherAddress.setBounds(220, 250, 130, 80) tfTeacherCourse.setBounds(220, 350, 130, 30) tfTeacherPayment.setBounds(220, 400, 130, 30) btnEnter = JButton("Update", actionPerformed=clickUpdateTeacher) btnEnter.setBounds(350, 450, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnCancel.setBounds(100, 450, 100, 40) panel.add(heading) panel.add(lbTeacherName) panel.add(lbTeacherPhone) panel.add(lbTeacherEmail) panel.add(lbTeacherAddress) panel.add(lbTeacherCourse) panel.add(lbTeacherPayment) panel.add(tfTeacherName) panel.add(tfTeacherPhone) panel.add(tfTeacherEmail) panel.add(taTeacherAddress) panel.add(tfTeacherCourse) panel.add(tfTeacherPayment) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
def update_progress(event): # Invoked when task's progress property changes. if event.propertyName == "progress": progressBar.value = event.newValue # Browse original image lbl1 = JLabel("Path to original image") lbl1.setBounds(40,20,200,20) f2_btn_original = JButton("Browse", actionPerformed = f2_clic_browse1) f2_btn_original.setBounds(170,20,100,20) f2_txt1 = JTextField(10) f2_txt1.setBounds(280, 20, 120,20) # Browse label image lbl2 = JLabel("Path to label image") lbl2.setBounds(40,50,200,20) f2_btn_label = JButton("Browse", actionPerformed = f2_clic_browse2) f2_btn_label.setBounds(170,50,100,20) f2_txt2 = JTextField(10) f2_txt2.setBounds(280, 50, 120,20) # Button Previous f2_btn_prev = JButton("Previous", actionPerformed = f2_clic_prev) f2_btn_prev.setBounds(40,120,100,20) # Button Next
class BurpExtender(IBurpExtender, IScannerListener, IContextMenuFactory, ActionListener, ITab, IHttpService, IScanIssue, IBurpExtenderCallbacks): def __init__(self): self.msgrel = False self.project = False self.projectId = None print("[+] Carregando GAT CORE Extension...") def registerExtenderCallbacks(self, callbacks): """ registrar classes """ self._callbacks = callbacks self._helpers = self._callbacks.getHelpers() self._callbacks.setExtensionName("GAT CORE Integration") self.gui_elements = self.build_gui() callbacks.customizeUiComponent(self.gui_elements) callbacks.addSuiteTab(self) self._callbacks.registerContextMenuFactory(self) self._callbacks.registerScannerListener(self) save_setting = self._callbacks.saveExtensionSetting save_setting('project_id', None) self.reload_config() print("[+] GAT CORE Extension carregado!") def newScanIssue(self, issue): print("[+] Issue encontrada (%s)" % issue.getIssueName()) return def actionTarget(self, event): print("*" * 80) self.fileId = [] requestResponses = self.invocation.getSelectedMessages() chosts, ihosts = self.countHostIssues(requestResponses) if self.project <= 1: panelinput = JPanel() panelinput.add(JLabel("Projeto ID: ")) projectq = JTextField(20) panelinput.add(projectq) result = JOptionPane.showOptionDialog( None, panelinput, "Qual projeto enviar Issues?", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, None, ["OK", "Sem projeto"], "OK") if result == -1: print("[-] Cancelado envio!") return if result == JOptionPane.OK_OPTION: self.project_id.setText(projectq.getText()) self.projectId = str(projectq.getText()) if not re.match('([0-9a-f]{24})', self.projectId): self.projectId = None mess = "Projeto Id formato inválido".decode("utf8") JOptionPane.showMessageDialog(None, mess, "Error", JOptionPane.ERROR_MESSAGE) return mess = "Sessão atual".decode("utf8") ever = JOptionPane.showOptionDialog( None, "Solicitar Id de Projeto novamente?", mess, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, None, ["Nunca", "Sim"], "Sim") # let user select parameters for new session if ever == JOptionPane.OK_OPTION: self.project = 2 else: self.project = 1 for reqResp in requestResponses: url = reqResp.getHttpService() requestIssues = self._callbacks.getScanIssues(str(url)) listIssues = [] if requestIssues: if len(requestIssues) > 0: for i in requestIssues: scanissue = i if scanissue.getIssueName() not in ['']: sep = "<br><hr><br>" issue = {} issue['Tool_Type'] = "BURP" IssueType = scanissue.getIssueType() IssueName = scanissue.getIssueName() IssueCrit = scanissue.getSeverity() IssueConf = scanissue.getConfidence() protocol = scanissue.getHttpService().getProtocol() host = scanissue.getHttpService().getHost() IssuePath = i.getUrl().getPath() IssueDesc = scanissue.getIssueDetail() IssueDescBk = scanissue.getIssueBackground() IssueRecom = scanissue.getRemediationDetail() IssueRecomBk = scanissue.getRemediationBackground() if IssueType: issue['IssueType'] = scanissue.getIssueType() else: issue['IssueType'] = 0000 if IssueName: issue['DetailsFinding_Title'] = IssueName issue['Recomenation_Title'] = IssueName else: issue['DetailsFinding_Title'] = "No Issue name" issue['Recomenation_Title'] = "No Issue name" if "False positive" in IssueCrit: sTag = "False positive" IssueCrit = "" elif "Information" in IssueCrit: IssueCrit = "Informative" sTag = "" else: sTag = "" if IssueCrit: issue['Severity'] = IssueCrit else: issue['Severity'] = "Informative" issue['Web_Application_URI'] = "{}://{}".format( protocol, host) if IssuePath: issue['Web_Application_Path'] = IssuePath else: issue['Web_Application_Path'] = "/" if IssueConf: issue['fTag'] = IssueConf else: issue['fTag'] = " " issue['sTag'] = sTag if IssueDescBk is not None: issue['Description'] = IssueDescBk.replace( "\n", "") else: issue['Description'] = "" if IssueDesc is not None: issue['Description'] += "{}{}".format( sep, IssueDesc.replace("\n", "")) if IssueRecomBk is not None: issue['Recommendation'] = IssueRecomBk.replace( "\n", "") else: issue['Recommendation'] = IssueName if IssueRecom is not None: issue['Recommendation'] += "{}{}".format( sep, IssueRecom.replace("\n", "")) listIssues.append(issue) self.generateReportGat(listIssues) # iniciar threads print("[+] Thread(s) Iniciada(s)...") if self.project: print("[+] Enviando Issues para o Project Id: {}".format( self.projectId)) print("[+] Enviando {} host(s), total de {} Issue(s),\n".format( chosts, ihosts)) self.launchThread(self.sendIssues) def actionScanner(self): pass def createMenuItems(self, invocation): self.invocation = invocation context = invocation.getInvocationContext() if context in [invocation.CONTEXT_TARGET_SITE_MAP_TREE]: sendToGAT = JMenuItem("Enviar Issues para GAT CORE") # sendToGAT.setForeground(Color.ORANGE) FONT = sendToGAT.getFont() sendToGAT.setFont( Font(FONT.getFontName(), Font.BOLD, FONT.getSize())) sendToGAT.addActionListener(self.actionTarget) menuItems = ArrayList() menuItems.add(sendToGAT) return menuItems else: # TODO: add support for other tools pass def build_gui(self): """Construct GUI elements.""" Mpanel = JPanel() # Mpanel.setLayout(GridLayout(0, 3)) Mpanel.setLayout(BoxLayout(Mpanel, BoxLayout.X_AXIS)) panel = JPanel() panel.setLayout(None) Mpanel.add(Box.createVerticalGlue()) Mpanel.add(panel) Mpanel.add(Box.createVerticalGlue()) img = os.path.abspath("gat_logo_sticky.png") logo = JLabel(ImageIcon(img)) logo.setBounds(150, 40, 165, 49) save_btn = JButton('Salvar', actionPerformed=self.save_config) save_btn.setBounds(100, 240, 75, 30) save_btn.setPreferredSize(Dimension(75, 30)) limpar_btn = JButton('Limpar ID Projeto', actionPerformed=self.clsProjectId) limpar_btn.setBounds(250, 240, 150, 30) limpar_btn.setPreferredSize(Dimension(150, 30)) label_h = JLabel('API Url:') label_h.setHorizontalAlignment(SwingConstants.RIGHT) label_h.setBounds(0, 120, 95, 30) label_h.setPreferredSize(Dimension(100, 30)) self.host_api = JTextField(50) self.host_api.setBounds(100, 120, 300, 30) self.host_api.setPreferredSize(Dimension(250, 30)) label_a = JLabel('API Token:') label_a.setHorizontalAlignment(SwingConstants.RIGHT) label_a.setBounds(0, 160, 95, 30) label_a.setPreferredSize(Dimension(100, 30)) self.api_token = JTextField(50) self.api_token.setBounds(100, 160, 300, 30) self.api_token.setPreferredSize(Dimension(250, 30)) label_p = JLabel('Project ID:') label_p.setHorizontalAlignment(SwingConstants.RIGHT) label_p.setBounds(0, 200, 95, 30) label_p.setPreferredSize(Dimension(100, 30)) self.project_id = JTextField(50) self.project_id.setForeground(Color.orange) self.project_id.setBackground(Color.gray) self.project_id.setBounds(100, 200, 300, 30) self.project_id.setPreferredSize(Dimension(250, 30)) self.project_id.editable = False panel.add(logo) panel.add(label_h) panel.add(self.host_api) panel.add(label_a) panel.add(self.api_token) panel.add(label_p) panel.add(self.project_id) panel.add(limpar_btn) panel.add(save_btn) return Mpanel def save_config(self, _): """Save settings.""" url = self.host_api.getText() token = self.api_token.getText() if re.match('https?://', url): url = re.sub('https?://', '', url) if url[-1:] == "/": url = url[:-1] if re.match('^(?i)Bearer ', token): token = re.sub('^(?i)Bearer ', '', token) if not re.match( '([a-f\d]{8})-([a-f\d]{4})-([a-f\d]{4})-([a-f\d]{4})-([a-f\d]{12})', token): JOptionPane.showMessageDialog(None, "Formato de TOKEN invalido!", "Error", JOptionPane.ERROR_MESSAGE) return save_setting = self._callbacks.saveExtensionSetting save_setting('host_api', url) save_setting('api_token', token) self.msgrel = True self.reload_config() return def reload_config(self): """Reload settings.""" load_setting = self._callbacks.loadExtensionSetting host_api_url = load_setting('host_api') or '' host_api_token = load_setting('api_token') or '' # project_id = '' self.host_api.setText(host_api_url) self.api_token.setText(host_api_token) # self.project_id.setText(project_id) if self.msgrel: if self.host_api and self.api_token: JOptionPane.showMessageDialog( None, "API token, API url dados salvo\n ", "Informativo", JOptionPane.INFORMATION_MESSAGE) print("[+] API token, API url dados salvo") print("[+] Recarregue: GAT CORE Extension") return try: vapi = self.checkAuth() if vapi.status_code == 200: data = json.loads(vapi.text) print("[ ] Conectado: {}, {}".format(data['name'], data['email'])) # if self.msgrel: JOptionPane.showMessageDialog( None, "Conectado: {}, {}".format(data['name'], data['email']), "Informativo", JOptionPane.INFORMATION_MESSAGE) else: raise Exception("Status_Code({})".format(vapi.status_code)) except Exception as e: print("[-] GAT CORE Settings, erro ao conectar na API.") print("[-] Exception: {}".format(e)) return def getTabCaption(self): """Return the text to be displayed on the tab""" return "GAT CORE Settings" def getUiComponent(self): """Passes the UI to burp""" return self.gui_elements def generateReportGat(self, rows): quote = '"' Id = uuid.uuid4().hex self.fileId.append(Id) path = os.getcwd() folder = "\\exports\\" file_name = "{}{}{}.csv".format(path, folder, Id) with open(file_name, mode='w') as csv_file: fields = [ 'Tool_Type', 'IssueType', 'DetailsFinding_Title', 'Severity', 'Web_Application_URI', 'Web_Application_Path', 'fTag', 'sTag', 'Description', 'Recomenation_Title', 'Recommendation' ] writer = csv.DictWriter(csv_file, fieldnames=fields, quotechar=quote, quoting=csv.QUOTE_NONNUMERIC, lineterminator='\n') writer.writeheader() writer.writerows(rows) csv_file.close() return Id def sendIssues(self): for Id in self.fileId: print("[+] Processando ID: {}".format(Id)) path = os.getcwd() folder = "\\exports\\" file_name = "{}{}{}.csv".format(path, folder, Id) self.launchThread(self.requestAPI, arguments=file_name) def launchThread(self, targetFunction, arguments=None, retur=False): """Launches a thread against a specified target function""" if arguments: t = Thread(name='args', target=targetFunction, args=(arguments, )) else: t = Thread(name='no-args', target=targetFunction) t.setDaemon(True) t.start() if retur: r = t.join() return r def countHostIssues(self, requestResponses): count = 0 icount = 0 for reqResp in requestResponses: url = reqResp.getHttpService() requestIssues = self._callbacks.getScanIssues(str(url)) if requestIssues: if len(requestIssues) > 0: count += 1 for issue in requestIssues: icount += 1 return count, icount def requestAPI(self, filename): load_setting = self._callbacks.loadExtensionSetting api_uri = load_setting('host_api') or '' api_token = load_setting('api_token') or '' projectid = self.projectId name_csv = os.path.basename(filename) if projectid: resource = "/app/vulnerability/upload/api/Burp/{}".format( projectid) else: resource = "/app/vulnerability/upload/api/Burp" # print(resource) protocol = "http" if api_uri == "localhost" else "https" gatPoint = "{}://{}{}".format(protocol, api_uri, resource) try: dataList = [] api_url = URL(gatPoint) boundary = name_csv.replace(".csv", "") headers = ArrayList() headers.add('POST %s HTTP/1.1' % resource) headers.add('Host: %s' % api_uri) headers.add('Authorization: Bearer %s' % api_token) headers.add('Accept: application/json') headers.add( 'Content-type: multipart/form-data; boundary={}'.format( boundary)) dataList.append('--' + boundary) dataList.append( 'Content-Disposition: form-data; name=file; filename={}'. format(name_csv)) dataList.append('Content-Type: text/csv') dataList.append('') with open(filename) as f: dataList.append(f.read()) dataList.append('--' + boundary + '--') dataList.append('') body = '\r\n'.join(dataList) newBody = self._helpers.bytesToString(body) newRequest = self._helpers.buildHttpMessage(headers, newBody) requestInfo = self._helpers.analyzeRequest(newRequest) headers = requestInfo.getHeaders() response = self._callbacks.makeHttpRequest(api_url.getHost(), 443, True, newRequest) response_info = self._helpers.analyzeResponse(response) response_value = self._helpers.bytesToString( response)[response_info.getBodyOffset():].encode("utf-8") except Exception as e: print("[-] Falha arquivo/envio de Issues ID:{} - Error: {}".format( name_csv, e)) if response_info.getStatusCode() == 200: self.removeCSV(filename) print("[+] Success ID: {}".format(name_csv.replace(".csv", ""))) else: print("[-] Falhou o envio do ID: {} - code :{}".format( name_csv.replace(".csv", ""), response_info.getStatusCode())) if response_value: print("Error: {}".format(response_value)) JOptionPane.showMessageDialog(None, "Falhou o envio das Issues", "Error", JOptionPane.ERROR_MESSAGE) self.removeCSV(filename) def checkAuth(self): """ Validar api + token GAT """ load_setting = self._callbacks.loadExtensionSetting api_uri = load_setting('host_api') or '' api_token = load_setting('api_token') or '' resource = "/api/v1/me" protocol = "http" if api_uri == "localhost" else "https" gatPoint = "{}://{}{}".format(protocol, api_uri, resource) api_url = URL(gatPoint) headers = ArrayList() headers.add('GET %s HTTP/1.1' % resource) headers.add('Host: %s' % api_uri) headers.add('Authorization: Bearer %s' % api_token) headers.add('Content-Type: application/json') newRequest = self._helpers.buildHttpMessage(headers, None) requestInfo = self._helpers.analyzeRequest(newRequest) headers = requestInfo.getHeaders() response = self._callbacks.makeHttpRequest(api_url.getHost(), 443, True, newRequest) response_info = self._helpers.analyzeResponse(response) response_value = self._helpers.bytesToString( response)[response_info.getBodyOffset():].encode("utf-8") response = {} response['status_code'] = response_info.getStatusCode() response['text'] = response_value r = DotDict(response) return r def removeCSV(self, path): """ param <path> could either be relative or absolute. """ if os.path.isfile(path) or os.path.islink(path): os.remove(path) else: raise ValueError("file {} is not a file".format(path)) def clsProjectId(self, _): self.project_id.setText(None) self.project = False self.projectId = None JOptionPane.showMessageDialog( None, "Redefinido envio de Issues sem Projeto.", "Informativo", JOptionPane.INFORMATION_MESSAGE)
def instReg(): global frame global tfName global tfPhone global taAddress global tfAdminLoginId global tfAdminPassword frame = JFrame("Registration Form ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,550) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,550) panel.setLocation(0,0) panel.setLayout(None) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("Institute Registration Form ") heading.setBounds(200,30,150,30) lbName = JLabel("Name") lbPhone =JLabel("Phone no ") lbAddress = JLabel("Address") lbAdminLoginId = JLabel("Admin login ") lbAdminPassword =JLabel("Admin Password") font = Font("Courier",Font.PLAIN,16) tfName = JTextField() tfPhone = JTextField() taAddress =JTextArea() tfAdminLoginId = JTextField() tfAdminPassword = JTextField() lbName.setBounds(70,100,150,40) lbPhone.setBounds(70,150,150,40) lbAddress.setBounds(70,200,150,40) lbAdminLoginId.setBounds(70,310,150,40) lbAdminPassword.setBounds(70,360,150,40) tfName = JTextField() tfPhone = JTextField() taAddress = JTextArea() tfAdminLoginId = JTextField() tfAdminPassword = JTextField() tfName.setBounds(250,100,200,40) tfPhone.setBounds(250,150,200,40) taAddress.setBounds(250,200,200,100) tfAdminLoginId.setBounds(250,310,200,40) tfAdminPassword.setBounds(250,360,200,40) tfName.setFont(font) tfPhone.setFont(font) taAddress.setFont(font) tfAdminLoginId.setFont(font) tfAdminPassword.setFont(font) sp = JScrollPane(taAddress) c = frame.getContentPane() btnSave = JButton("Save",actionPerformed=clickAdminReg) btnSave.setBounds(350,420,80,30) #panel.add(lbName) #panel.add(lbPhone) #panel.add(lbAddress) #panel.add(lbAdminLoginId) #panel.add(lbAdminPassword) #panel.add(tfName) #panel.add(tfPhone) #panel.add(c) #panel.add(tfAdminLoginId) #panel.add(tfAdminPassword) #panel.add(btnSave) #panel.add(btnLogin) c.add(lbName) c.add(lbPhone) c.add(lbAddress) c.add(lbAdminLoginId) c.add(lbAdminPassword) c.add(tfName) c.add(tfPhone) c.add(taAddress) c.add(tfAdminLoginId) c.add(tfAdminPassword) c.add(btnSave) frame.add(c)
def addStudent(courseName, courseFee, v): global tfStudentName global tfStudentPhone global tfStudentEmail global taStudentAddress global tfCourseName global tfCourseFee global cbStudentAssignTeacher global frame frame = JFrame("Add Student ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 600) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 600) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("ADD STUDENT") heading.setBounds(200, 30, 150, 40) lbCourseName = JLabel(" Course name") lbCourseFee = JLabel(" Course Fee") lbStudentName = JLabel("Student name ") lbStudentPhone = JLabel("Phone") lbStudentEmail = JLabel("Email Id") lbStudentAddress = JLabel("Address") lbStudentAssignTeacher = JLabel("Student Assign teacher ") tfCourseName = JTextField(courseName) tfCourseFee = JTextField(str(courseFee)) tfStudentName = JTextField() tfStudentPhone = JTextField() tfStudentEmail = JTextField() taStudentAddress = JTextArea() cbStudentAssignTeacher = JComboBox(v) tfCourseName.setEditable(False) tfCourseFee.setEditable(False) lbCourseName.setBounds(70, 100, 130, 30) lbCourseFee.setBounds(70, 150, 130, 30) lbStudentName.setBounds(70, 200, 130, 30) lbStudentPhone.setBounds(70, 250, 130, 30) lbStudentEmail.setBounds(70, 300, 130, 30) lbStudentAddress.setBounds(70, 350, 130, 80) lbStudentAssignTeacher.setBounds(70, 450, 130, 30) tfCourseName.setBounds(220, 100, 130, 30) tfCourseFee.setBounds(220, 150, 130, 30) tfStudentName.setBounds(220, 200, 130, 30) tfStudentPhone.setBounds(220, 250, 130, 30) tfStudentEmail.setBounds(220, 300, 130, 30) taStudentAddress.setBounds(220, 350, 130, 80) cbStudentAssignTeacher.setBounds(220, 450, 130, 30) btnEnter = JButton("ADD", actionPerformed=clickAddStudent) btnEnter.setBounds(350, 510, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickbtnCancelForm) btnCancel.setBounds(50, 510, 100, 40) panel.add(heading) panel.add(lbCourseName) panel.add(lbCourseFee) panel.add(lbStudentName) panel.add(lbStudentPhone) panel.add(lbStudentEmail) panel.add(lbStudentAddress) panel.add(lbStudentAssignTeacher) panel.add(tfCourseName) panel.add(tfCourseFee) panel.add(tfStudentName) panel.add(tfStudentPhone) panel.add(tfStudentEmail) panel.add(taStudentAddress) panel.add(cbStudentAssignTeacher) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
def updateStudent(stObj): global studentId global tfStudentName global tfStudentPhone global tfStudentEmail global taStudentAddress global tfCourseName global cbStudentAssignTeacher global frame frame = JFrame("Update student ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,500) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,500) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) studentId = getattr(stObj,'studentId') studentName= getattr(stObj,'studentName') studentPhone = getattr(stObj,'studentPhone') studentEmail = getattr(stObj,'studentEmail') studentAddress = getattr(stObj,'studentAddress') studentCourse = getattr(stObj,'courseName') teachersName = srv.showStudentChoiceCourse(studentCourse) v = Vector() for d in teachersName: v.add(d[0].encode('ascii')) heading = JLabel("Update TEACHER") heading.setBounds(200,30,150,40) lbStudentName = JLabel("Student name ") lbStudentPhone = JLabel("Phone") lbStudentEmail = JLabel("Email Id") lbStudentAddress = JLabel("Address") lbStudentAssignTeacher = JLabel("Student Assign teacher ") tfStudentName = JTextField(studentName) tfStudentPhone = JTextField(studentPhone) tfStudentEmail = JTextField(studentEmail) taStudentAddress = JTextArea(studentAddress) cbStudentAssignTeacher = JComboBox(v) lbStudentName.setBounds(70,100,130,30) lbStudentPhone.setBounds(70,150,130,30) lbStudentEmail.setBounds(70,200,130,30) lbStudentAddress.setBounds(70,250,130,30) lbStudentAssignTeacher.setBounds(70,350,130,30) tfStudentName.setBounds(220,100,130,30) tfStudentPhone.setBounds(220,150,130,30) tfStudentEmail.setBounds(220,200,130,30) taStudentAddress.setBounds(220,250,130,80) cbStudentAssignTeacher.setBounds(220,350,130,30) btnEnter = JButton("Update",actionPerformed=clickUpdateStudent) btnEnter.setBounds(350,420,100,40) btnCancel = JButton("Cancel",actionPerformed=clickbtnCancel) btnCancel.setBounds(50,420,100,40) panel.add(heading) panel.add(lbStudentName) panel.add(lbStudentPhone) panel.add(lbStudentEmail) panel.add(lbStudentAddress) panel.add(lbStudentAssignTeacher) panel.add(tfStudentName) panel.add(tfStudentPhone) panel.add(tfStudentEmail) panel.add(taStudentAddress) panel.add(cbStudentAssignTeacher) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
def addTeacher(): global heading global tfTeacherName global tfTeacherPhone global taTeacherAddress global tfTeacherEmail global tfTeacherCourse global tfTeacherPayment global frame global btnEnter frame = JFrame("Add Teacher ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 600) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 600) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("ADD TEACHER") heading.setBounds(200, 30, 150, 40) lbTeacherName = JLabel("Teacher Name ") lbTeacherPhone = JLabel("Phone") lbTeacherEmail = JLabel("Email") lbTeacherAddress = JLabel("Address") lbTeacherCourse = JLabel("Teacher Course ") lbTeacherPayment = JLabel("Teacher Payment") tfTeacherName = JTextField() tfTeacherPhone = JTextField() taTeacherAddress = JTextArea() tfTeacherEmail = JTextField() tfTeacherCourse = JTextField() tfTeacherPayment = JTextField() lbTeacherName.setBounds(70, 100, 130, 30) lbTeacherPhone.setBounds(70, 150, 130, 30) lbTeacherEmail.setBounds(70, 200, 130, 30) lbTeacherAddress.setBounds(70, 250, 130, 30) lbTeacherCourse.setBounds(70, 350, 130, 30) lbTeacherPayment.setBounds(70, 400, 130, 30) tfTeacherName.setBounds(220, 100, 130, 30) tfTeacherPhone.setBounds(220, 150, 130, 30) tfTeacherEmail.setBounds(220, 200, 130, 30) taTeacherAddress.setBounds(220, 250, 130, 80) tfTeacherCourse.setBounds(220, 350, 130, 30) tfTeacherPayment.setBounds(220, 400, 130, 30) btnEnter = JButton("ADD", actionPerformed=clickAddTeacher) btnEnter.setBounds(350, 450, 100, 40) panel.add(heading) panel.add(lbTeacherName) panel.add(lbTeacherPhone) panel.add(lbTeacherEmail) panel.add(lbTeacherAddress) panel.add(lbTeacherCourse) panel.add(lbTeacherPayment) panel.add(tfTeacherName) panel.add(tfTeacherPhone) panel.add(tfTeacherEmail) panel.add(taTeacherAddress) panel.add(tfTeacherCourse) panel.add(tfTeacherPayment) panel.add(btnEnter) frame.add(panel)
class BurpExtender(IBurpExtender, IScannerListener, ITab): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self.helpers = callbacks.helpers callbacks.setExtensionName("Orchy-Webhook") self.frame = JPanel() self.frame.setSize(1024, 786) self.frame.setLayout(None) self.plugin_path = os.getcwd() self.db_file_path = os.path.join(os.getcwd(), 'burp_db.json') self.cwe_dict = json.load(open(self.db_file_path, 'r')) self.results = {} self.severity_dict = { 'Low': 1, 'Medium': 2, 'High': 3, 'Information': 0, 'Info': 0, } self.urls = [] self.confidence_dict = {'Certain': 3, 'Firm': 2, 'Tentative': 1} callbacks.registerScannerListener(self) button1 = JButton(ImageIcon( ((ImageIcon(self.plugin_path + "/refresh.jpg")).getImage()).getScaledInstance( 13, 13, SCALE_SMOOTH)), actionPerformed=self.refresh) button1.setBounds(30, 50, 22, 22) lbl0 = JLabel("Orchestron Webhook:") lbl0.setFont(Font("", Font.BOLD, 12)) lbl0.setForeground(Color(0xFF7F50)) lbl0.setBounds(60, 20, 200, 20) lbl1 = JLabel('Host') lbl1.setBounds(60, 50, 100, 20) self.txt1 = JComboBox() self.txt1.setBounds(200, 50, 220, 24) lbl2 = JLabel("Webhook Url") lbl2.setBounds(60, 80, 100, 20) self.txt2 = JTextField('', 300) self.txt2.setBounds(200, 80, 220, 24) lbl3 = JLabel("Authorization Token") lbl3.setBounds(60, 110, 200, 20) self.txt3 = JTextField('', 60) self.txt3.setBounds(200, 110, 220, 24) lbl4 = JLabel("Engagement-ID") lbl4.setBounds(60, 140, 200, 20) self.txt4 = JTextField('', 40) self.txt4.setBounds(200, 140, 220, 24) button2 = JButton('Push Results', actionPerformed=self.push) button2.setBounds(200, 170, 120, 24) self.message = JLabel('') self.message.setBounds(330, 170, 180, 24) self.frame.add(button1) self.frame.add(lbl0) self.frame.add(lbl1) self.frame.add(self.txt1) self.frame.add(lbl2) self.frame.add(self.txt2) self.frame.add(lbl3) self.frame.add(self.txt3) self.frame.add(lbl4) self.frame.add(self.txt4) self.frame.add(button2) self.frame.add(self.message) callbacks.customizeUiComponent(self.frame) callbacks.addSuiteTab(self) def refresh(self, event): self.txt1.removeAllItems() for host in self.results.keys(): self.txt1.addItem(host) self.message.text = '' def newScanIssue(self, issue): callbacks = self._callbacks # print "New Issue Identified:"+issue.getUrl().toString() if callbacks.isInScope(issue.getUrl()) == 1: self.tmp = issue.getUrl() self.scheme = self.tmp.protocol self.port = self.tmp.port self.fqdn = self.tmp.host if self.port == -1: if self.scheme == 'https': self.port = 443 elif self.scheme == 'http': self.port = 80 else: self.scheme = 'http' self.port = 80 self.host = str(self.scheme + '://' + self.fqdn + ':' + str(self.port)) if not self.results: self.results[self.host] = {'scan_dict': {}} for host in self.results.keys(): if host == self.host: if str(issue.getIssueType()) in self.cwe_dict.keys(): name = self.cwe_dict.get(str(issue.getIssueType()), '')[1] cwe_id = self.cwe_dict.get(str(issue.getIssueType()), '')[0] else: name = 'Burp IssueType - {0}'.format( str(issue.getIssueType())) cwe_id = 0 if name in self.results[host]['scan_dict'].keys(): old_evidance = self.results[host]['scan_dict'][ name].get('evidences') for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } old_evidance.append(info_dict) else: severity = self.severity_dict.get( issue.getSeverity(), '') confidence = self.confidence_dict.get( issue.getConfidence(), '') evidences = [] for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } evidences.append(info_dict) self.results[host]['scan_dict'][name] = { 'description': issue.getIssueDetail(), 'remediation': '', 'severity': severity, 'cwe': cwe_id, 'evidences': evidences } else: self.results[self.host] = {'scan_dict': {}} if str(issue.getIssueType()) in self.cwe_dict.keys(): name = self.cwe_dict.get(str(issue.getIssueType()), '')[1] cwe_id = self.cwe_dict.get(str(issue.getIssueType()), '')[0] else: name = 'Burp IssueType - {0}'.format( str(issue.getIssueType())) cwe_id = 0 severity = self.severity_dict.get(issue.getSeverity(), '') confidence = self.confidence_dict.get( issue.getConfidence(), '') evidences = [] for httpmessage in issue.getHttpMessages(): request = (httpmessage.getRequest().tostring() if httpmessage.getRequest() else None) request = b64encode(request.encode('utf-8')) response = (httpmessage.getResponse().tostring() if httpmessage.getResponse() else None) response = b64encode(response.encode('utf-8')) info_dict = { 'url': issue.getUrl().toString(), 'name': issue.getIssueName(), 'request': request, 'response': response } evidences.append(info_dict) self.results[host]['scan_dict'][name] = { 'description': issue.getIssueDetail(), 'remediation': '', 'severity': severity, 'cwe': cwe_id, 'evidences': evidences } def push(self, event): if self.txt1.getSelectedItem(): vulns = {} vulns['tool'] = 'Burp' vulns['vulnerabilities'] = [] for k, v in self.results[ self.txt1.getSelectedItem()]['scan_dict'].items(): vulnerability = { 'name': str(k), 'description': v.get('description', ''), 'remediation': '', 'severity': v.get('severity', None), 'cwe': v.get('cwe', 0), 'evidences': v.get('evidences', None) } vulns['vulnerabilities'].append(vulnerability) if self.txt2.text and self.txt3.text: webhook_url = self.txt2.text auth_token = self.txt3.text engagement_id = '' if self.txt4.text: engagement_id = self.txt4.text req_headers = { 'Authorization': 'Token ' + auth_token, 'X-Engagement-ID': engagement_id } req = requests.post(webhook_url, headers=req_headers, json={'vuls': vulns}) if req.status_code == 200: self.message.text = "Result pushed successfully" with open('./orchy_log.txt', 'a') as orchy_log: orchy_log.write(req.content + '\n') orchy_log.close() else: with open('./orchy_log.txt', 'a') as orchy_log: orchy_log.write(req.content + '\n') orchy_log.close() self.message.text = "Failed" def getTabCaption(self): return 'Orchy-Webhook' def getUiComponent(self): return self.frame
btn8.setBounds(101, 101, 100, 100) btn9 = JButton("9", actionPerformed=clickBtn9) btn9.setBounds(201, 101, 100, 100) btnDivide = JButton("/", actionPerformed=clickBtnDivide) btnDivide.setBounds(301, 101, 100, 80) btnMultiply = JButton("*", actionPerformed=clickBtnMultiply) btnMultiply.setBounds(301, 181, 100, 80) btnSubtract = JButton("-", actionPerformed=clickBtnSubtract) btnSubtract.setBounds(301, 261, 100, 80) btnPlus = JButton("+", actionPerformed=clickBtnPlus) btnPlus.setBounds(301, 341, 100, 80) btnEqual = JButton("=", actionPerformed=clickBtnEqual) btnEqual.setBounds(301, 421, 100, 80) tf = JTextField("") tf.setBounds(0, 0, 400, 100) tf.setHorizontalAlignment(JTextField.RIGHT) font = Font("Courier", Font.BOLD, 30) tf.setFont(font) frame.add(btnDot) frame.add(btnDel) frame.add(btn0) frame.add(btnEqual) frame.add(btn1) frame.add(btn2) frame.add(btn3) frame.add(btn4) frame.add(btn5) frame.add(btn6) frame.add(btn7)
class BurpExtender(IBurpExtender, ITab, IHttpListener): def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("burp-sensitive-param-extractor") self._stdout = PrintWriter(callbacks.getStdout(), True) callbacks.registerHttpListener(self) #callbacks.registerMessageEditorTabFactory(self) print 'burp-sensitive-param-extractor loaded.\nAuthor:LSA\nhttps://github.com/theLSA/burp-sensitive-param-extractor' self.sensitiveParamR = getParamRegular() self._callbacks.customizeUiComponent(self.getUiComponent()) self._callbacks.addSuiteTab(self) #self.endColors = [] self.requestParamDict = {} self.resultSensitiveParamsDict = {} def getTabCaption(self): return 'BSPE' def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if messageIsRequest and toolFlag == 4: self.requestParamDict['urlParams'] = [] self.requestParamDict['BodyParams'] = [] self.requestParamDict['cookieParams'] = [] self.requestParamDict['jsonParams'] = [] cookieParamFlag = 0 service = messageInfo.getHttpService() request = messageInfo.getRequest() analyzeReq = self._helpers.analyzeRequest(service, request) reqUrl = self._helpers.analyzeRequest(messageInfo).getUrl() reqMethod = self._helpers.analyzeRequest(messageInfo).getMethod() reqParams = analyzeReq.getParameters() for param in reqParams: paramType = param.getType() if paramType == 0: #self.outputTxtArea.append("\nurlParams-") paramName = param.getName() paramValue = param.getValue() print 'urlParams:' print paramName + ':' + paramValue #self.outputTxtArea.append("[%s]" % paramName) self.requestParamDict['urlParams'].append( paramName.strip()) if paramType == 1: #self.outputTxtArea.append("\nBodyParams-") paramName = param.getName() paramValue = param.getValue() print 'BodyParams:' print paramName + ':' + paramValue #self.outputTxtArea.append("[%s]\n" % paramName) self.requestParamDict['BodyParams'].append( paramName.strip()) if paramType == 2: #self.outputTxtArea.append("\ncookieParams-") paramName = param.getName() paramValue = param.getValue() print 'CookieParams:' print paramName + ':' + paramValue #self.outputTxtArea.append("[%s]\n" % paramName) self.requestParamDict['cookieParams'].append( paramName.strip()) cookieParamFlag = 1 if paramType == 6: #self.outputTxtArea.append("\njsonParams-") paramName = param.getName() paramValue = param.getValue() print 'JsonParams:' print paramName + ':' + paramValue #self.outputTxtArea.append("[%s]\n" % paramName) self.requestParamDict['jsonParams'].append( paramName.strip()) self.resultSensitiveParamsDict = self.findSensitiveParam( self.requestParamDict) #print self.resultSensitiveParamsDict for rspdKey in self.resultSensitiveParamsDict.keys(): if self.resultSensitiveParamsDict[rspdKey] != []: print "[%s][%s]" % (reqMethod, reqUrl) self.outputTxtArea.append( "\n------------------------------------------------------\n" ) self.outputTxtArea.append("[%s][%s]\n" % (reqMethod, reqUrl)) break for rspdKey in self.resultSensitiveParamsDict.keys(): if self.resultSensitiveParamsDict[rspdKey] != []: self.outputTxtArea.append( "\n" + rspdKey + "--" + str(self.resultSensitiveParamsDict[rspdKey])) self.write2file() #pass else: return def findSensitiveParam(self, requestParamDict): #sensitiveParamR = getParamRegular() resultSensitiveParamsDict = {} resultSensitiveParamsDict['urlParams'] = [] resultSensitiveParamsDict['BodyParams'] = [] resultSensitiveParamsDict['cookieParams'] = [] resultSensitiveParamsDict['jsonParams'] = [] #print requestParamDict for spr in self.sensitiveParamR: for key in requestParamDict.keys(): for reqParam in requestParamDict[key]: if len(spr) == 1: if spr == reqParam.lower(): resultSensitiveParamsDict[key].append(reqParam) else: if spr in reqParam.lower(): print spr + ' in ' + reqParam resultSensitiveParamsDict[key].append(reqParam) #print resultSensitiveParamsDict for key in resultSensitiveParamsDict.keys(): resultSensitiveParamsDict[key] = {}.fromkeys( resultSensitiveParamsDict[key]).keys() #resultSensitiveParamsDict[key] = sorted(resultSensitiveParamsDict[key],key=resultSensitiveParamsDict[key].index) #print resultSensitiveParamsDict return resultSensitiveParamsDict def write2file(self): sensitiveParamsList = getSensitiveParamsFromFile() newSensitiveParamsList = [] #print self.resultSensitiveParamsDict for rspdKey in self.resultSensitiveParamsDict.keys(): if (self.resultSensitiveParamsDict[rspdKey] != []) and (set( self.resultSensitiveParamsDict[rspdKey]).issubset( set(sensitiveParamsList)) == False): newSensitiveParamsList.extend([ newSensitiveParam for newSensitiveParam in self.resultSensitiveParamsDict[rspdKey] if newSensitiveParam not in sensitiveParamsList ]) #print str(newSensitiveParamsList) if newSensitiveParamsList != []: newSensitiveParamsList = {}.fromkeys(newSensitiveParamsList).keys() with open('sensitive-params.txt', 'a') as sps: for nsp in newSensitiveParamsList: #print 'writeNewParams:'+nsp sps.write('\n' + nsp) def addAndSaveNewParamRegular(self, event): NewParamRegular = self.addAndSaveNewParamRegularTextField.getText() if NewParamRegular not in self.sensitiveParamR: self.sensitiveParamR.append(NewParamRegular) with open(paramRegularFile, 'a') as prf: prf.write('\n' + NewParamRegular) self.alertSaveSuccess.showMessageDialog(self.spePanel, "Add and save success!") else: self.alertSaveSuccess.showMessageDialog(self.tab, "paramRegular existed.") self.sensitiveParamsRegularListPanel.setListData(self.sensitiveParamR) self.sensitiveParamsRegularListPanel.revalidate() #self.sensitiveParamR = getParamRegular() def delParamRegular(self, event): #delParamRegularsIndex = self.sensitiveParamsRegularListPanel.selectedIndex #if delParamRegularsIndex >= 0: # print delParamRegularsIndex # print self.sensitiveParamR[delParamRegularsIndex] for sprlp in self.sensitiveParamsRegularListPanel.getSelectedValuesList( ): #print sprlp self.sensitiveParamR.remove(sprlp) #with open(paramRegularFile,'r') as prf1: # lines = prf1.readlines() with open(paramRegularFile, 'w') as prf2: #print self.sensitiveParamsRegularListPanel.getSelectedValuesList() #for line in lines: # if line.strip() in self.sensitiveParamsRegularListPanel.getSelectedValuesList(): # print 'remove:'+line # lines.remove(line) #for spr1 in lines: # #print spr1 # prf2.write(spr1) for spr2i, spr2 in enumerate(self.sensitiveParamR): print spr2i print spr2 if spr2i == len(self.sensitiveParamR) - 1: prf2.write(spr2) else: prf2.write(spr2 + '\n') self.sensitiveParamsRegularListPanel.setListData(self.sensitiveParamR) self.sensitiveParamsRegularListPanel.revalidate() #self.sensitiveParamR = getParamRegular() def clearRst(self, event): self.outputTxtArea.setText("") def exportRst(self, event): chooseFile = JFileChooser() ret = chooseFile.showDialog(self.logPane, "Choose file") filename = chooseFile.getSelectedFile().getCanonicalPath() print "\n" + "Export to : " + filename open(filename, 'w', 0).write(self.outputTxtArea.text) def getUiComponent(self): self.spePanel = JPanel() self.spePanel.setBorder(None) self.spePanel.setLayout(None) self.logPane = JScrollPane() self.outputTxtArea = JTextArea() self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12)) self.outputTxtArea.setLineWrap(True) self.logPane.setViewportView(self.outputTxtArea) self.spePanel.add(self.logPane) self.clearBtn = JButton("Clear", actionPerformed=self.clearRst) self.exportBtn = JButton("Export", actionPerformed=self.exportRst) self.parentFrm = JFileChooser() self.spePanel.add(self.clearBtn) self.spePanel.add(self.exportBtn) self.logPane.setBounds(20, 50, 800, 600) self.clearBtn.setBounds(20, 650, 100, 30) self.exportBtn.setBounds(600, 650, 100, 30) self.sensitiveParamsRegularListPanel = JList(self.sensitiveParamR) self.sensitiveParamsRegularListPanel.setVisibleRowCount( len(self.sensitiveParamR)) #self.spePanel.add(self.sensitiveParamsRegularListPanel) #self.sensitiveParamsRegularListPanel.setBounds(850,50,150,600) self.sensitiveParamsRegularListScrollPanel = JScrollPane() self.sensitiveParamsRegularListScrollPanel.setViewportView( self.sensitiveParamsRegularListPanel) self.spePanel.add(self.sensitiveParamsRegularListScrollPanel) self.sensitiveParamsRegularListScrollPanel.setBounds(850, 50, 150, 600) self.addAndSaveNewParamRegularButton = JButton( 'add&&save', actionPerformed=self.addAndSaveNewParamRegular) self.spePanel.add(self.addAndSaveNewParamRegularButton) self.addAndSaveNewParamRegularButton.setBounds(1000, 50, 150, 30) self.addAndSaveNewParamRegularTextField = JTextField('NewParamRegular') self.spePanel.add(self.addAndSaveNewParamRegularTextField) self.addAndSaveNewParamRegularTextField.setBounds(1150, 50, 100, 30) self.alertSaveSuccess = JOptionPane() self.spePanel.add(self.alertSaveSuccess) self.delParamRegularButton = JButton( "delete", actionPerformed=self.delParamRegular) self.spePanel.add(self.delParamRegularButton) self.delParamRegularButton.setBounds(1000, 90, 100, 30) return self.spePanel
def studentProfileForm(data): global heading global tfStudentName global tfStudentPhone global taStudentAddress global tfStudentEmail global tfCourseName global tfCourseFee global tfStudentAssignTeacher global frame global btnEnter frame = JFrame(" Student ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 620) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 620) panel.setLocation(0, 0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel(" STUDENT PROFILE") heading.setBounds(200, 30, 150, 40) lbStudentName = JLabel("Student Name ") lbStudentPhone = JLabel("Phone") lbStudentEmail = JLabel("Email") lbStudentAddress = JLabel("Address") lbCourseName = JLabel("Course Name ") lbCourseFee = JLabel("Course Fee") lbStudentAssignTeacher = JLabel("Teacher") studentName = data[0].encode('ascii') studentPhone = data[1].encode('ascii') studentEmail = data[2].encode('ascii') studentAddress = data[3].encode('ascii') courseName = data[4].encode('ascii') courseFee = data[5] studentAssignTeacher = data[6].encode('ascii') tfStudentName = JTextField(studentName) tfStudentPhone = JTextField(studentPhone) taStudentAddress = JTextArea(studentAddress) tfStudentEmail = JTextField(studentEmail) tfCourseName = JTextField(courseName) tfCourseFee = JTextField(str(courseFee)) tfStudentAssignTeacher = JTextField(studentAssignTeacher) tfCourseName.setEditable(False) tfCourseFee.setEditable(False) tfStudentAssignTeacher.setEditable(False) tfStudentName.setEditable(False) lbStudentName.setBounds(70, 100, 130, 30) lbStudentPhone.setBounds(70, 150, 130, 30) lbStudentEmail.setBounds(70, 200, 130, 30) lbStudentAddress.setBounds(70, 250, 130, 30) lbCourseName.setBounds(70, 350, 130, 30) lbCourseFee.setBounds(70, 400, 130, 30) lbStudentAssignTeacher.setBounds(70, 450, 130, 30) tfStudentName.setBounds(220, 100, 130, 30) tfStudentPhone.setBounds(220, 150, 130, 30) tfStudentEmail.setBounds(220, 200, 130, 30) taStudentAddress.setBounds(220, 250, 130, 80) tfCourseName.setBounds(220, 350, 130, 30) tfCourseFee.setBounds(220, 400, 130, 30) tfStudentAssignTeacher.setBounds(220, 450, 130, 30) btnEnter = JButton("Update", actionPerformed=clickUpdateStudent) btnEnter.setBounds(350, 530, 100, 40) btnCancel = JButton("Cancel", actionPerformed=clickCancel) btnCancel.setBounds(100, 530, 100, 40) panel.add(heading) panel.add(lbStudentName) panel.add(lbStudentPhone) panel.add(lbStudentEmail) panel.add(lbStudentAddress) panel.add(lbCourseName) panel.add(lbCourseFee) panel.add(lbStudentAssignTeacher) panel.add(tfStudentName) panel.add(tfStudentPhone) panel.add(tfStudentEmail) panel.add(taStudentAddress) panel.add(tfCourseName) panel.add(tfCourseFee) panel.add(tfStudentAssignTeacher) panel.add(btnEnter) panel.add(btnCancel) frame.add(panel)
class GUI(ITab, ActionListener, KeyAdapter): def __init__(self): return def getTabCaption(self): return "BurpExtension" def getUiComponent(self): return self.UI() def UI(self): self.val="" self.tabbedPane = JTabbedPane(JTabbedPane.TOP) self.panel = JPanel() self.tabbedPane.addTab("App Details", None, self.panel, None) # Details of app currently under pentest would be pulled into here through API self.panel_1 = JPanel() self.tabbedPane.addTab("Results", None, self.panel_1, None) # passed results would go inside this and connected to reporting system via API self.panel_2 = JPanel() self.tabbedPane.addTab("Failed Cases", None, self.panel_2, None) #list of failed tests would go inside this self.textField = JTextField() self.textField.setBounds(12, 13, 207, 39) self.panel.add(self.textField) self.textField.setColumns(10) self.comboBox = JComboBox() self.comboBox.setEditable(True) self.comboBox.addItem("Default") self.comboBox.addItem("High") self.comboBox.addItem("Low") self.comboBox.setBounds(46, 65, 130, 28) self.comboBox.addActionListener(self) self.panel.add(self.comboBox) self.btnNewButton = JButton("Submit") self.btnNewButton.setBounds(60, 125, 97, 25) self.panel.add(self.btnNewButton) editorPane = JEditorPane(); editorPane.setBounds(12, 35, 1000, 800); self.panel_2.add(editorPane); self.panel_2.setLayout(BorderLayout()) return self.tabbedPane def getAppRating(self): sys.stdout.write(str(self.val)) return str(self.val) def actionPerformed(self, e): if(e.getSource()==self.comboBox): self.val = self.comboBox.getSelectedItem() else: self.addDetails() def addDetails(self): jf0 = JFrame() jf0.setTitle("Add Issue"); jf0.setLayout(None); txtEnterIssue = JTextField(); txtEnterIssue.setName("Enter Issue Name"); txtEnterIssue.setToolTipText("Enter Issue Name Here"); txtEnterIssue.setBounds(182, 58, 473, 40); jf0.add(txtEnterIssue); txtEnterIssue.setColumns(10); btnNewButton = JButton("Add"); btnNewButton.setBounds(322, 178, 139, 41); jf0.add(btnNewButton); comboBox = JComboBox(); comboBox.setMaximumRowCount(20); comboBox.setEditable(True); comboBox.setToolTipText("Objective Name"); comboBox.setBounds(182, 125, 473, 40); jf0.add(comboBox); lblNewLabel = JLabel("Issue Name Here"); lblNewLabel.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel.setBounds(25, 58, 130, 40); jf0.add(lblNewLabel); lblNewLabel_1 = JLabel("Objective Name"); lblNewLabel_1.setFont(Font("Tahoma", Font.PLAIN, 16)); lblNewLabel_1.setBounds(25, 125, 130, 40); jf0.add(lblNewLabel_1); jf0.setVisible(True) jf0.setBounds(400, 300, 700, 300) jf0.EXIT_ON_CLOSE txtEnterIssue.addKeyListener(self) def keyPressed(self, e): self.search_string.__add__(self.search_string) self.jtf1.setText(self.search_string) sys.stdout.write(self.search_string)
def output(self, value): eingabe = value.getString() if eingabe == "Lexikon": # Falls "Lexikon" an den Clienten übergeben wird, wird die GUI geöffnet, # in der man deutsche Wörter eingeben kann, die einem dann auf Englisch # vorgelesen werden. def change_text(event): text = feld.getText() x = suche(text) self.send(x) frame.visible = False frame = JFrame( 'Woerterbuch', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(380, 350), ) frame.setLayout(None) frame.visible = True hintergrund = ImageIcon("Hintergrund.jpg") hintergrundlabel = JLabel(hintergrund) frame.setContentPane(hintergrundlabel) uebersetzerlabel = JLabel() uebersetzerlabel.setForeground(Color(025, 025, 112)) uebersetzerlabel.setText( "<html><font size=+1>Welches Wort soll ich uebersetzen?</font></html>" ) uebersetzerlabel.setBounds(10, 20, 500, 50) frame.add(uebersetzerlabel) feld = JTextField() feld.setText("") feld.setBounds(20, 80, 300, 25) frame.add(feld) button = JButton('Uebersetzen', actionPerformed=change_text, size=(10, 20)) button.setBounds(20, 110, 300, 30) frame.add(button) if eingabe == "neue Lektion": # Falls dem Clienten "neue Lektion" übergeben wird, öffnet er er die # GUI für das Verwalten der Lektionen frame = JFrame('Lektion erstellen', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(1000, 1000)) frame.setLayout(None) def auflisten_in(ort): font = Font("Verdana", Font.BOLD, 15) liste_mit_Lektionen = [] with open(pfad, "r") as f: for line in f: liste_mit_Lektionen.append(line.strip()) liste_mit_Lektionen.sort() text = "" for lektion in liste_mit_Lektionen: text += lektion text += "\n" ort.setText(text) ort.setFont(font) frame.setLayout(None) uebersichtLabel = JLabel() def uebersetzen(event): frage = feld_frage.getText() x = suche(frage) feld_frage.setText(x) liste = [] with open(pfad, "r") as lektionen: for lektion in lektionen: if "nachgeschlagen" in lektion: liste.append(lektion) if liste: name = liste[-1] words = [] sql = "SELECT deutsch, englisch, symbol FROM " + name zeile = stmt.executeQuery(sql) while zeile.next(): d = zeile.getString("deutsch") e = zeile.getString("englisch") symb = zeile.getString("symbol") words.append((d, e, symb)) if len(words) < 50: sql = "INSERT INTO " + name + " (deutsch, englisch, symbol) VALUES(?,?,?);" pstmt = conn.prepareStatement(sql) pstmt.setString(1, frage) pstmt.setString(2, x) pstmt.setString(3, "X") pstmt.executeUpdate() else: namensteile = name.split("_") nummer = int(namensteile[1].strip()) + 1 name = "nachgeschlagen_" + str(nummer) test = "" with open(pfad, "r") as f: for line in f: test += line if not name in test: with open(pfad, "a") as f: f.write(name + "\n") sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);" stmt.execute(sql) sql = "INSERT INTO " + name + " (deutsch, englisch, symbol) VALUES(?,?,?);" pstmt = conn.prepareStatement(sql) pstmt.setString(1, frage) pstmt.setString(2, x) pstmt.setString(3, "X") pstmt.executeUpdate() else: name = "nachgeschlagen_1" test = "" with open(pfad, "r") as f: for line in f: test += line if not name in test: with open(pfad, "a") as f: f.write(name + "\n") sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);" stmt.execute(sql) sql = "INSERT INTO " + name + " (deutsch, englisch, symbol) VALUES(?,?,?);" pstmt = conn.prepareStatement(sql) pstmt.setString(1, frage) pstmt.setString(2, x) pstmt.setString(3, "X") pstmt.executeUpdate() auflisten_in(uebersicht) def delete(event): name = feld.getText() print name print self.geladen if name == self.geladen: count = 0 while tabelle.getValueAt(count, 0) != None: tabelle.setValueAt(None, count, 0) tabelle.setValueAt(None, count, 1) count += 1 stmt.execute("DROP TABLE " + name + ";") lektionen = [] with open(pfad, "r") as f: for line in f: lektion = line.strip() if not name == lektion: lektionen.append(lektion) with open(pfad, "w") as f: for lektion in lektionen: f.write(lektion + "\n") auflisten_in(uebersicht) def laden(event): name = feld.getText() self.geladen = name sql = "SELECT deutsch, englisch FROM " + name results = stmt.executeQuery(sql) count = 0 while results.next(): d = results.getString("deutsch") e = results.getString("englisch") tabelle.setValueAt(d, count, 0) tabelle.setValueAt(e, count, 1) count += 1 while tabelle.getValueAt(count, 0) != None: tabelle.setValueAt(None, count, 0) tabelle.setValueAt(None, count, 1) count += 1 def erstelle_Lektionstabelle(event): reihen = [] for i in range(0, 50): deutsch = tabelle.getValueAt(i, 0) englisch = tabelle.getValueAt(i, 1) if deutsch != None: symbol = "X" reihen.append([deutsch, englisch, symbol]) else: break z = 0 name = feld.getText() sql = "CREATE TABLE " + name + " (deutsch text, englisch text, symbol text);" try: stmt.execute(sql) except SQLError: stmt.execute("DROP TABLE " + name + ";") stmt.execute(sql) for reihe in reihen: print(reihe) deutsch = reihe[0] englisch = reihe[1] symbol = reihe[2] sql = "INSERT INTO " + name + " (deutsch, englisch, symbol) VALUES(?,?,?);" pstmt = conn.prepareStatement(sql) pstmt.setString(1, deutsch) pstmt.setString(2, englisch) pstmt.setString(3, symbol) pstmt.executeUpdate() test = "" with open(pfad, "r") as f: for line in f: test += line if not name in test: with open(pfad, "a") as f: f.write(name + "\n") self.send(name) frame.setVisible(False) frame = JFrame('Vokabel Listen', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(1000, 1000)) frame.setLayout(None) label_enter = JLabel() label_enter.setText( "<html><font size=+0.5 color = 000000>Bitte vor dem Speichern<br>die Entertaste bedienen</font></html>" ) label_enter.setBounds(20, 720, 250, 50) uebersichtLabel = JLabel() uebersichtLabel.setText( "<html><font size=+1 color=#191970>Bereits vorhandene Lektionen:</font></html>" ) uebersichtLabel.setBounds(450, 230, 250, 50) uebersicht = JTextArea() uebersicht.editable = False uebersicht_scroll = JScrollPane(uebersicht) uebersicht_scroll.viewport.view = uebersicht uebersicht_scroll.setBounds(450, 300, 250, 380) auflisten_in(uebersicht) button = JButton('Lektion speichern/Lektion reseten', actionPerformed=erstelle_Lektionstabelle, size=(10, 20)) button.setBounds(20, 700, 300, 30) button_laden = JButton('vorhandene Lektion laden', actionPerformed=laden, size=(10, 20)) button_laden.setBounds(20, 110, 210, 30) button_delete = JButton("Lektion entfernen", actionPerformed=delete) button_delete.setBounds(20, 140, 210, 30) hintergrund = ImageIcon("Hintergrund.jpg") pnl = JPanel() hintergrundlabel = JLabel(hintergrund) frame.setContentPane(hintergrundlabel) lektionsnamensLabel = JLabel() lektionsnamensLabel.setForeground(Color(025, 025, 112)) lektionsnamensLabel.setText( "<html><font size=+1>Hier bitte Namen der Lektion eingeben<br>(Nur ein Wort lang)</font></html>" ) lektionsnamensLabel.setBounds(10, 20, 500, 50) frame.add(lektionsnamensLabel) feld = JTextField() feld.setText("") feld.setBounds(20, 80, 210, 25) frame.add(feld) column_names = [ "<html><font size=+1 color=#191970><b>Deutsch</b></font></html>", "<html><font size=+1 color=#191970><b>Englisch</b></font></html>" ] table_model = DefaultTableModel(column_names, 50) tabelle = JTable(table_model) lektionsnamensLabel.setForeground(Color(025, 025, 112)) scrollbar = JScrollPane(tabelle) scrollbar.viewport.view = tabelle scrollbar.setVerticalScrollBarPolicy( scrollbar.VERTICAL_SCROLLBAR_ALWAYS) scrollbar.setVisible(True) tabelle.setVisible(True) scrollbar.setBounds(20, 190, 300, 490) feld_frage = JTextField() feld_frage.setText("") feld_frage.setBounds(450, 30, 300, 50) uebersetzerlabel = JLabel() uebersetzerlabel.setForeground(Color(025, 025, 112)) uebersetzerlabel.setText( "<html><font size=+1>Hier kannst Du ein deutsches Wort eintragen,<br>dass ich fuer Dich nachschlage</font></html>" ) uebersetzerlabel.setBounds(450, 80, 500, 50) button_uebersetzen = JButton('Uebersetzen', actionPerformed=uebersetzen, size=(10, 20)) button_uebersetzen.setBounds(450, 130, 300, 30) frame.add(button_uebersetzen) frame.add(uebersetzerlabel) frame.add(feld_frage) frame.add(feld) frame.add(scrollbar) frame.add(button) frame.add(button_laden) frame.setVisible(True) frame.add(uebersicht_scroll) frame.add(uebersichtLabel) frame.add(button_delete) frame.add(label_enter) elif eingabe == "alle Lektionen auflisten": # Hier erstellt der Client eine dynamische Grammatik # mit den vorhandenen Lektionen, die man sich abfragen lassen kann # und gibt diese wieder an DialogOS zurück. # Außerdem wird der Feedback Frame geöffnet. def auflisten_in2(ort): font = Font("Verdana", Font.BOLD, 15) liste_mit_Lektionen = [] with open(pfad, "r") as f: for line in f: liste_mit_Lektionen.append(line.strip()) liste_mit_Lektionen.sort() text = "" for lektion in liste_mit_Lektionen: text += lektion text += "\n" ort.setText(text) ort.setFont(font) frame_feedback.setVisible(True) auflisten_in2(uebersicht2) grammatik = "" grammatik = "root $NamevonLektion;\n" grammatik += "$NamevonLektion = " with open(pfad, "r") as f: z = 0 for line in f: if z == 0: if not "_" in line: grammatik += line else: zeile = line.split("_") grammatik += zeile[0] + " " grammatik += zeile[1].strip() else: if not "_" in line: grammatik += "|" + line else: zeile = line.split("_") grammatik += "|" + zeile[0] + " " grammatik += zeile[1].strip() if line != "\n": z += 1 grammatik += ";" self.send(grammatik) elif "sende" in eingabe: # DialogOS sagt dem Clienten, welche Lektion der User abgefragt # werden möchte. Der Client ließt dann die entsprechende Lektion # aus der Datenbank aus und gibt eine Liste mit 2 Listen zurück. # In der ersten Liste befinden sich die deutschen Bedeutungen, der # noch nicht gewussten Wörter, in der 2. Liste die englsichen Bedeutungen. # Falls alle Wörter bereits gekonnt wurden, wird stattdessen eine entsprechende # Anmerkung an DialogOS geschickt und DialogOS informiert den User darüber. z = 0 if "nachgeschlagen" in eingabe: bestandteile = eingabe.split() name = bestandteile[1] + "_" + bestandteile[2] else: name = eingabe.split()[1] sql = "SELECT deutsch, englisch, symbol FROM " + name vokabelliste = stmt.executeQuery(sql) deutsch = [] englisch = [] symbol = [] while (vokabelliste.next()): deutsch.append(vokabelliste.getString("deutsch")) englisch.append(vokabelliste.getString("englisch")) symbol.append(vokabelliste.getString("symbol")) indices = range(0, len(deutsch)) random.shuffle(indices) vokabeln = [[], []] for index in indices: d = deutsch[index] e = englisch[index] s = symbol[index] if s == "X": vokabeln[0].append(d) vokabeln[1].append(e) if vokabeln[0]: self.send(vokabeln) else: self.send([ "Du kannst diese Lektion schon komplett. Wenn Du sie wieder abgefragt werden willst, resete sie bitte unter Wokabeln verwalten." ]) else: # Dieser Teil des Codes wird während der Abfrage ausgeführt. # Nach jeder neuen Vokabel wird dann in ein Feld im Feedback # Frame die deutsche, die englische Vokabel und ein Symbol angezeigt, # welches einen darüber informiert, ob man die Vokabel wusste, oder nicht. # (O für gewusst und X für nicht gewusst) nametext = eingabe.split(":") name = nametext[0] text = nametext[1] feld_feedback.setText(text) zeilen = text.split("\n") symb = zeilen[-2].split("\t")[-1] d = zeilen[-2].split("\t")[-3] print d sql = "UPDATE " + name + " SET symbol = ? WHERE deutsch = ?" pstmt = conn.prepareStatement(sql) pstmt.setString(1, symb) pstmt.setString(2, d) pstmt.executeUpdate()
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, IProxyListener): """ BurpSuite插件类 """ def __init__(self): self.plugin_name = u'orz Plugin' self.panel = None self.callbacks = None self.DEBUG = True self.context = None self.helpers = None self.log_box_width = 1000 self.log_box_height = 400 self.tools = Tools() self.now_version = VERSION def registerExtenderCallbacks(self, callbacks): # 注册插件 self.callbacks = callbacks self.helpers = callbacks.getHelpers() self.callbacks.setExtensionName(self.plugin_name) # 绘制标签页UI self.tab_ui() self.callbacks.customizeUiComponent(self.panel) self.callbacks.addSuiteTab(self) self.callbacks.registerProxyListener(self) self.callbacks.registerContextMenuFactory(self) print('Plugin load successfully!') self.tools.log('INFO', '插件加载成功 - 当前版本: {}'.format(VERSION)) self.tools.log('INFO', '当前debug模式: {}'.format(self.DEBUG)) # 窗口大小检查线程 log_box_thread = threading.Thread(target=self.reset_log_box_size) log_box_thread.setDaemon(True) log_box_thread.start() return def createMenuItems(self, invocation): # 创建菜单右键菜单选项 self.context = invocation menu_list = JMenu('orz Plugin') if self.context.getToolFlag() == 0x40: menu_list.add( JMenuItem(u'添加IP伪造请求头', actionPerformed=self.update_client_src_ip)) menu_list.add( JMenuItem(u'生成DNSLog Payload', actionPerformed=self.dnslog_payload)) # DEBUG 按钮 menu_list.add( JMenuItem('orz - DEBUG', actionPerformed=self.debug_fun)) return [menu_list] def tab_ui(self): self.panel = JPanel() self.panel.setLayout(None) self.ui_client_dnslog_label_1 = JLabel('-' * 10 + u' IP伪造请求头 & DNSLog 配置 ' + '-' * 155) self.ui_client_dnslog_label_1.setBounds(20, 10, 1000, 28) self.ui_client_ip_label_1 = JLabel(u'伪造IP: ') self.ui_client_ip_label_1.setBounds(20, 40, 70, 30) self.ui_client_ip = JTextField('127.0.0.1') self.ui_client_ip.setBounds(80, 40, 200, 28) self.ui_client_url_label_1 = JLabel(u'dnslog url: ') self.ui_client_url_label_1.setBounds(10, 80, 70, 30) self.ui_client_url = JTextField('http://examlpe.com') self.ui_client_url.setBounds(80, 80, 200, 28) self.ui_button_label = JLabel('-' * 210) self.ui_button_label.setBounds(20, 110, 1000, 28) #self.ui_web_test_button = JButton(u'登录测试', actionPerformed=self.login_test) #self.ui_web_test_button.setBounds(20, 140, 100, 28) self.ui_save_button = JButton(u'保存配置', actionPerformed=self.save_configuration) self.ui_save_button.setBounds(20, 140, 100, 28) self.ui_debug_button = JButton('Debug', actionPerformed=self.debug_fun) self.ui_debug_button.setBounds(135, 140, 100, 28) self.panel.add(self.ui_debug_button) self.ui_log_box = JTextArea('') self.ui_log_box.setLineWrap(True) self.ui_log_box.setEditable(False) self.ui_log_scroll_pane = JScrollPane(self.ui_log_box) self.ui_log_scroll_pane.setBounds(20, 190, self.log_box_width, self.log_box_height) self.panel.add(self.ui_client_dnslog_label_1) self.panel.add(self.ui_client_ip_label_1) self.panel.add(self.ui_client_ip) self.panel.add(self.ui_client_url_label_1) self.panel.add(self.ui_client_url) self.panel.add(self.ui_button_label) #self.panel.add(self.ui_web_test_button) self.panel.add(self.ui_save_button) self.panel.add(self.ui_log_scroll_pane) self.tools.panel = self.panel self.tools.log_box = self.ui_log_box self.tools.log_scroll_pane = self.ui_log_scroll_pane def getTabCaption(self): # 设置标签页名称 return self.plugin_name def getUiComponent(self): # 设置标签页UI return self.panel def processProxyMessage(self, message_is_request, message): """ 处理Proxy请求 url: http://biubiu.com:80/h/p?id=24&a=123 request_methond: POST GET etc cookie: 顾名思义 content_type: 如 application/json; charset=UTF-8 request_header: 包含coolie的头 request_body: 顾名思义 host: 主机名 port: 端口号 protocol: 协议,如http、https url_parameters:url中的参数信息, 格式{'id':23,'a':123} """ if message_is_request and self.DEBUG: request = message.getMessageInfo().getRequest() analyzedRequest = self.helpers.analyzeRequest( message.getMessageInfo().getHttpService(), request) request_headers = analyzedRequest.getHeaders() request_body = request[analyzedRequest.getBodyOffset():].tostring() url = str(analyzedRequest.getUrl()) host = message.getMessageInfo().getHttpService().getHost() port = message.getMessageInfo().getHttpService().getPort() protocol = message.getMessageInfo().getHttpService().getProtocol() request_methond = str(analyzedRequest.getMethod()) parameters = analyzedRequest.getParameters() url_parameters = {} for parameter in parameters: if parameter.getType() == 0: url_parameters[str(parameter.getName())] = str( parameter.getValue()) cookie = "" content_type = "" request_header = {} for header in request_headers[2:]: header = str(header).strip() header_temp = header.split(':') request_header[header_temp[0].strip()] = ':'.join( header_temp[1:]).strip() if header.startswith("Cookie:"): cookie_temp = header.split(':') cookie = ':'.join(cookie_temp[1:]).strip() continue if header.startswith("Content-Type"): content_type = ':'.join(header.split(':')[1:]).strip() # self.tools.log('content_type', content_type) # self.tools.log('request_methond', request_methond) # self.tools.log('url', url) #self.tools.log('request_header', request_header) # self.tools.log('cookie', cookie) self.tools.http_deal(url, request_methond, cookie, content_type, request_header, request_body) # 多线程 # proxy_thread = threading.Thread(target=self.tools.http_deal, args=( # url, request_methond, cookie, content_type, request_header, request_body)) # proxy_thread.setDaemon(True) # proxy_thread.start() # 新增处理线程 def login_test(self, event): # 生产环境Web方式获取Cookie测试 return def save_configuration(self, event): self.tools.client_src_ip = str(self.ui_client_ip.getText()).strip() self.tools.dnslog_url = str(self.ui_client_url.getText()).strip() self.tools.log('INFO', '配置保存成功') def reset_log_box_size(self): while self.tools.runtime(): time.sleep(1) new_width = int(self.panel.rootPane.getSize().width) - 40 new_height = int(self.panel.rootPane.getSize().height) - 290 if new_width != self.log_box_width or new_height != self.log_box_height: self.log_box_width = new_width self.log_box_height = new_height self.ui_log_scroll_pane.setBounds(20, 190, self.log_box_width, self.log_box_height) self.panel.updateUI() def debug_fun(self, event): if self.DEBUG: self.DEBUG = False self.tools.log('INFO', 'set debug = False') else: self.DEBUG = True self.tools.log('INFO', 'set debug = True') def update_web_cookie(self): http_traffic = self.context.getSelectedMessages()[0] traffic_analyze = self.helpers.analyzeRequest(http_traffic) return def web_cookie_web_prod(self, event): self.update_web_cookie() def update_client_src_ip(self, event): add_header = [ 'X-Originating-IP', 'X-Forwarded-For', 'X-Remote-IP', 'X-Remote-Addr', 'X-Client-IP', 'X-Real-IP', 'Proxy-Cllient-IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR' ] http_traffic = self.context.getSelectedMessages()[0] traffic_analyze = self.helpers.analyzeRequest(http_traffic) new_headers = [] tmp_add_header = map(str.lower, add_header) for header in traffic_analyze.getHeaders(): tmp_header = header.split(':')[0].strip().lower() if tmp_header not in tmp_add_header: new_headers.append(header) new_headers += map( lambda x: '{}: {}'.format(x, self.tools.client_src_ip), add_header) new_request = self.helpers.buildHttpMessage( new_headers, http_traffic.getRequest()[traffic_analyze.getBodyOffset():]) http_traffic.setRequest(new_request) def dnslog_payload(self, event): self.tools.msg_box('功能暂未实现,待更新')
def createStudentFeeForm(stFeeObj): global tfStudentId global tfStudentName global tfTotalAmount global tfPaidAmount global tfRemainingAmount global frame frame = JFrame("Student Fee Form ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500,500) frame.setLocation(200,200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500,500) panel.setLocation(0,0) panel.setLayout(None) panel.setVisible(True) panel.setBackground(Color.LIGHT_GRAY) heading = JLabel("STUDENT FEE") heading.setBounds(200,30,150,40) lbStudentId = JLabel(" Student id") lbStudentName = JLabel(" student name") lbTotalAmount = JLabel("Total Amount ") lbPaidAmount = JLabel("Paid Amount") lbRemainingAmount = JLabel("Remaining amount") studentId =getattr(stFeeObj,'studentId') studentName =getattr(stFeeObj,'studentName') totalAmount =getattr(stFeeObj,'totalAmount') paidAmount =getattr(stFeeObj,'paidAmount') remainingAmount =getattr(stFeeObj,'remainingAmount') tfStudentId = JTextField(str(studentId)) tfStudentName = JTextField(str(studentName)) tfTotalAmount = JTextField(str(totalAmount)) tfPaidAmount = JTextField(str(paidAmount)) tfRemainingAmount = JTextField(str(remainingAmount)) tfStudentId.setEditable(False) tfStudentName.setEditable(False) tfTotalAmount.setEditable(False) tfRemainingAmount.setEditable(False) lbStudentId.setBounds(70,100,130,30) lbStudentName.setBounds(70,150,130,30) lbTotalAmount.setBounds(70,200,130,30) lbPaidAmount.setBounds(70,250,130,30) lbRemainingAmount.setBounds(70,300,130,30) tfStudentId.setBounds(220,100,130,30) tfStudentName.setBounds(220,150,130,30) tfTotalAmount.setBounds(220,200,130,30) tfPaidAmount.setBounds(220,250,130,30) tfRemainingAmount.setBounds(220,300,130,30) btnPay = JButton("Paid",actionPerformed=clickPay) btnPay.setBounds(350,410,100,40) btnCancel = JButton("Cancel",actionPerformed=clickbtnCancelForm) btnCancel.setBounds(50,410,100,40) panel.add(heading) panel.add(lbStudentId) panel.add(lbStudentName) panel.add(lbTotalAmount) panel.add(lbPaidAmount) panel.add(lbRemainingAmount) panel.add(tfStudentId) panel.add(tfStudentName) panel.add(tfTotalAmount) panel.add(tfPaidAmount) panel.add(tfRemainingAmount) panel.add(btnPay) panel.add(btnCancel) frame.add(panel)
def loginPage(): global heading global rbAdmin global rbTeacher global rbStudent global frame global tfLoginId global tfPassword frame = JFrame("Login Form ") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(500, 500) frame.setLocation(200, 200) frame.setLayout(None) frame.setVisible(True) panel = JPanel() panel.setSize(500, 500) panel.setLocation(0, 0) panel.setLayout(None) panel.setBackground(Color.BLUE) heading = JLabel("Admin Login") heading.setBounds(200, 50, 150, 30) rbAdmin = JRadioButton("Admin", actionPerformed=clickRadio) rbTeacher = JRadioButton("Teacher", actionPerformed=clickRadio) rbStudent = JRadioButton("Student", actionPerformed=clickRadio) rbAdmin.setBounds(100, 150, 100, 20) rbTeacher.setBounds(200, 150, 100, 20) rbStudent.setBounds(300, 150, 100, 20) btnGroup = ButtonGroup() btnGroup.add(rbAdmin) btnGroup.add(rbTeacher) btnGroup.add(rbStudent) lbLoginId = JLabel("LoginId") lbPassword = JLabel("Password") lbLoginId.setBounds(100, 230, 150, 30) lbPassword.setBounds(100, 300, 150, 30) tfLoginId = JTextField() tfPassword = JTextField() tfLoginId.setBounds(250, 230, 150, 30) tfPassword.setBounds(250, 300, 150, 30) btnLogin = JButton("Login", actionPerformed=clickLogin) btnLogin.setBounds(350, 350, 100, 30) btnReg = JButton("New Institute Registration", actionPerformed=clickReg) btnReg.setBounds(350, 400, 100, 30) panel.add(heading) panel.add(rbAdmin) panel.add(rbTeacher) panel.add(rbStudent) panel.add(lbLoginId) panel.add(lbPassword) panel.add(tfLoginId) panel.add(tfPassword) panel.add(btnLogin) panel.add(btnReg) panel.setVisible(True) frame.add(panel)