class BurpExtender(IBurpExtender, ITab, IScannerCheck, IContextMenuFactory, IParameter, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Session Authentication Tool") self.out = callbacks.getStdout() # definition of suite tab self.tab = JPanel(GridBagLayout()) self.tabledata = MappingTableModel(callbacks) self.table = JTable(self.tabledata) #self.table.getColumnModel().getColumn(0).setPreferredWidth(50); #self.table.getColumnModel().getColumn(1).setPreferredWidth(100); self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 c.gridheight = 6 c.weightx = 0.3 c.weighty = 0.5 self.tab.add(self.tablecont, c) c = GridBagConstraints() c.weightx = 0.1 c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 0 label_id = JLabel("Identifier:") self.tab.add(label_id, c) self.input_id = JTextField(20) self.input_id.setToolTipText( "Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name." ) c.gridy = 1 self.tab.add(self.input_id, c) c.gridy = 2 label_content = JLabel("Content:") self.tab.add(label_content, c) self.input_content = JTextField(20, actionPerformed=self.btn_add_id) self.input_content.setToolTipText( "Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user." ) c.gridy = 3 self.tab.add(self.input_content, c) self.btn_add = JButton("Add/Edit Identity", actionPerformed=self.btn_add_id) c.gridy = 4 self.tab.add(self.btn_add, c) self.btn_del = JButton("Delete Identity", actionPerformed=self.btn_del_id) c.gridy = 5 self.tab.add(self.btn_del, c) callbacks.customizeUiComponent(self.tab) callbacks.customizeUiComponent(self.table) callbacks.customizeUiComponent(self.tablecont) callbacks.customizeUiComponent(self.btn_add) callbacks.customizeUiComponent(self.btn_del) callbacks.customizeUiComponent(label_id) callbacks.customizeUiComponent(self.input_id) callbacks.addSuiteTab(self) callbacks.registerScannerCheck(self) callbacks.registerIntruderPayloadGeneratorFactory(self) callbacks.registerContextMenuFactory(self) def btn_add_id(self, e): ident = self.input_id.text self.input_id.text = "" content = self.input_content.text self.input_content.text = "" self.tabledata.add_mapping(ident, content) self.input_id.requestFocusInWindow() def btn_del_id(self, e): rows = self.table.getSelectedRows().tolist() self.tabledata.del_rows(rows) ### ITab ### def getTabCaption(self): return ("SessionAuth") def getUiComponent(self): return self.tab ### IContextMenuFactory ### def createMenuItems(self, invocation): menuitems = list() msgs = invocation.getSelectedMessages() if msgs != None: if len( msgs ) == 1: # "add as object id/as content to last id" context menu items bounds = invocation.getSelectionBounds() if bounds != None and bounds[0] != bounds[1]: msg = None if invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST: msg = msgs[0].getRequest().tostring() if invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE or invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE: msg = msgs[0].getResponse().tostring() if msg != None: selection = msg[bounds[0]:bounds[1]] shortSelection = selection[:20] if len(selection) > len(shortSelection): shortSelection += "..." menuitems.append( JMenuItem("Add '" + shortSelection + "' as object id", actionPerformed=self.gen_menu_add_id( selection))) if self.tabledata.lastadded != None: menuitems.append( JMenuItem( "Add '" + shortSelection + "' as content to last added id", actionPerformed=self.gen_menu_add_content( selection))) if len(msgs) > 0: # "Send to Intruder" context menu items requestsWithIds = list() for msg in msgs: if isinstance(msg.getRequest(), array) and self.tabledata.containsId( msg.getRequest().tostring()): requestsWithIds.append(msg) if len(requestsWithIds) > 0: menuitems.append( JMenuItem( "Send to Intruder and preconfigure id injection points", actionPerformed=self.gen_menu_send_intruder( requestsWithIds))) return menuitems def gen_menu_add_id(self, ident): def menu_add_id(e): self.tabledata.add_mapping(ident, "") return menu_add_id def gen_menu_add_content(self, content): def menu_add_content(e): self.tabledata.set_lastadded_content(content) return menu_add_content def gen_menu_send_intruder(self, requestResponses): def menu_send_intruder(e): for requestResponse in requestResponses: httpService = requestResponse.getHttpService() request = requestResponse.getRequest() injectionPoints = list() for ident in self.tabledata.getIds(): newInjectionPoints = findAll(request.tostring(), ident) if newInjectionPoints != None: injectionPoints += newInjectionPoints if len(injectionPoints) > 0: self.callbacks.sendToIntruder( httpService.getHost(), httpService.getPort(), httpService.getProtocol() == "https", request, injectionPoints) return menu_send_intruder ### IIntruderPayloadGeneratorFactory ### def getGeneratorName(self): return "SessionAuth Identifiers" def createNewInstance(self, attack): return IdentifiersPayloadGenerator(self.tabledata) ### IScannerCheck ### def doPassiveScan(self, baseRequestResponse): analyzedRequest = self.helpers.analyzeRequest(baseRequestResponse) params = analyzedRequest.getParameters() ids = self.tabledata.getIds() issues = list() for param in params: value = param.getValue() for ident in ids: if value == ident: issues.append( SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundEqual, self.callbacks)) elif value.find(ident) >= 0: issues.append( SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundInside, self.callbacks)) if len(issues) > 0: return issues else: return None def doActiveScan(self, baseRequestResponse, insertionPoint): ids = self.tabledata.getIds() if len(ids ) <= 1: # active check only possible if multiple ids were given return None baseVal = insertionPoint.getBaseValue() url = baseRequestResponse.getUrl() idFound = list() for ident in ids: # find all identifiers in base value if baseVal.find(ident) >= 0: idFound.append(ident) if len(idFound) == 0: # no given identifier found, nothing to do return None baseResponse = baseRequestResponse.getResponse().tostring() baseResponseBody = baseResponse[ self.helpers.analyzeResponse(baseResponse).getBodyOffset():] issues = list() scannedCombos = list() for replaceId in idFound: # scanner checks: replace found id by other given ids for scanId in ids: if replaceId == scanId or set([replaceId, scanId ]) in scannedCombos: continue scannedCombos.append(set([replaceId, scanId])) scanPayload = baseVal.replace(replaceId, scanId) scanRequest = insertionPoint.buildRequest(scanPayload) scanRequestResponse = self.callbacks.makeHttpRequest( baseRequestResponse.getHttpService(), scanRequest) scanResponse = scanRequestResponse.getResponse().tostring() scanResponseBody = scanResponse[self.helpers.analyzeResponse( scanResponse).getBodyOffset():] if baseResponseBody == scanResponseBody: # response hasn't changed - no issue continue # Analyze responses replaceValue = self.tabledata.getValue(replaceId) scanValue = self.tabledata.getValue(scanId) # naming convention: # first word: base || scan (response) # second word: Replace || Scan (value) if replaceValue != "": baseReplaceValueCount = len( baseResponseBody.split(replaceValue)) - 1 scanReplaceValueCount = len( scanResponseBody.split(replaceValue)) - 1 else: baseReplaceValueCount = 0 scanReplaceValueCount = 0 if scanValue != "": baseScanValueCount = len( baseResponseBody.split(scanValue)) - 1 scanScanValueCount = len( scanResponseBody.split(scanValue)) - 1 else: baseScanValueCount = 0 scanScanValueCount = 0 if scanScanValueCount == 0: # Scan identifier content value doesn't appears, but responses differ issueCase = SessionAuthActiveScanIssue.caseScanValueNotFound elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount == baseReplaceValueCount: # Scan identifier replaces all occurrences of the original identifier in the response issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsExactly elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount > 0: # Scan identfiers value appears, replaced ids value disappears issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsFuzzy elif baseReplaceValueCount > scanReplaceValueCount and baseScanValueCount < scanScanValueCount: # Occurence count of replaced id value decreases, scan id value increases issueCase = SessionAuthActiveScanIssue.caseDecreaseIncrease elif baseScanValueCount < scanScanValueCount: # Occurence count of scan id value increases issueCase = SessionAuthActiveScanIssue.caseScanValueIncrease else: # Remainingg cases issueCase = SessionAuthActiveScanIssue.caseOther issues.append( SessionAuthActiveScanIssue(url, baseRequestResponse, insertionPoint, scanPayload, scanRequestResponse, replaceId, replaceValue, scanId, scanValue, issueCase, self.callbacks)) if len(issues) > 0: return issues else: return None def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getIssueDetail() == newIssue.getIssueDetail(): return 1 else: return 0
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IContextMenuFactory, IParameter, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Session Authentication Tool") self.out = callbacks.getStdout() # definition of suite tab self.tab = JPanel(GridBagLayout()) self.tabledata = MappingTableModel(callbacks) self.table = JTable(self.tabledata) #self.table.getColumnModel().getColumn(0).setPreferredWidth(50); #self.table.getColumnModel().getColumn(1).setPreferredWidth(100); self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 c.gridheight = 6 c.weightx = 0.3 c.weighty = 0.5 self.tab.add(self.tablecont, c) c = GridBagConstraints() c.weightx = 0.1 c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 0 label_id = JLabel("Identifier:") self.tab.add(label_id, c) self.input_id = JTextField(20) self.input_id.setToolTipText("Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name.") c.gridy = 1 self.tab.add(self.input_id, c) c.gridy = 2 label_content = JLabel("Content:") self.tab.add(label_content, c) self.input_content = JTextField(20, actionPerformed=self.btn_add_id) self.input_content.setToolTipText("Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user.") c.gridy = 3 self.tab.add(self.input_content, c) self.btn_add = JButton("Add/Edit Identity", actionPerformed=self.btn_add_id) c.gridy = 4 self.tab.add(self.btn_add, c) self.btn_del = JButton("Delete Identity", actionPerformed=self.btn_del_id) c.gridy = 5 self.tab.add(self.btn_del, c) callbacks.customizeUiComponent(self.tab) callbacks.customizeUiComponent(self.table) callbacks.customizeUiComponent(self.tablecont) callbacks.customizeUiComponent(self.btn_add) callbacks.customizeUiComponent(self.btn_del) callbacks.customizeUiComponent(label_id) callbacks.customizeUiComponent(self.input_id) callbacks.addSuiteTab(self) callbacks.registerScannerCheck(self) callbacks.registerIntruderPayloadGeneratorFactory(self) callbacks.registerContextMenuFactory(self) def btn_add_id(self, e): ident = self.input_id.text self.input_id.text = "" content = self.input_content.text self.input_content.text = "" self.tabledata.add_mapping(ident, content) self.input_id.requestFocusInWindow() def btn_del_id(self, e): rows = self.table.getSelectedRows().tolist() self.tabledata.del_rows(rows) ### ITab ### def getTabCaption(self): return("SessionAuth") def getUiComponent(self): return self.tab ### IContextMenuFactory ### def createMenuItems(self, invocation): menuitems = list() msgs = invocation.getSelectedMessages() if msgs != None: if len(msgs) == 1: # "add as object id/as content to last id" context menu items bounds = invocation.getSelectionBounds() if bounds != None and bounds[0] != bounds[1]: msg = None if invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST: msg = msgs[0].getRequest().tostring() if invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE or invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE: msg = msgs[0].getResponse().tostring() if msg != None: selection = msg[bounds[0]:bounds[1]] shortSelection = selection[:20] if len(selection) > len(shortSelection): shortSelection += "..." menuitems.append(JMenuItem("Add '" + shortSelection + "' as object id", actionPerformed=self.gen_menu_add_id(selection))) if self.tabledata.lastadded != None: menuitems.append(JMenuItem("Add '" + shortSelection + "' as content to last added id", actionPerformed=self.gen_menu_add_content(selection))) if len(msgs) > 0: # "Send to Intruder" context menu items requestsWithIds = list() for msg in msgs: if isinstance(msg.getRequest(), array) and self.tabledata.containsId(msg.getRequest().tostring()): requestsWithIds.append(msg) if len(requestsWithIds) > 0: menuitems.append(JMenuItem("Send to Intruder and preconfigure id injection points", actionPerformed=self.gen_menu_send_intruder(requestsWithIds))) return menuitems def gen_menu_add_id(self, ident): def menu_add_id(e): self.tabledata.add_mapping(ident, "") return menu_add_id def gen_menu_add_content(self, content): def menu_add_content(e): self.tabledata.set_lastadded_content(content) return menu_add_content def gen_menu_send_intruder(self, requestResponses): def menu_send_intruder(e): for requestResponse in requestResponses: httpService = requestResponse.getHttpService() request = requestResponse.getRequest() injectionPoints = list() for ident in self.tabledata.getIds(): newInjectionPoints = findAll(request.tostring(), ident) if newInjectionPoints != None: injectionPoints += newInjectionPoints if len(injectionPoints) > 0: self.callbacks.sendToIntruder(httpService.getHost(), httpService.getPort(), httpService.getProtocol() == "https", request, injectionPoints) return menu_send_intruder ### IIntruderPayloadGeneratorFactory ### def getGeneratorName(self): return "SessionAuth Identifiers" def createNewInstance(self, attack): return IdentifiersPayloadGenerator(self.tabledata) ### IScannerCheck ### def doPassiveScan(self, baseRequestResponse): analyzedRequest = self.helpers.analyzeRequest(baseRequestResponse) params = analyzedRequest.getParameters() ids = self.tabledata.getIds() issues = list() for param in params: value = param.getValue() for ident in ids: if value == ident: issues.append(SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundEqual, self.callbacks )) elif value.find(ident) >= 0: issues.append(SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundInside, self.callbacks )) if len(issues) > 0: return issues else: return None def doActiveScan(self, baseRequestResponse, insertionPoint): ids = self.tabledata.getIds() if len(ids) <= 1: # active check only possible if multiple ids were given return None baseVal = insertionPoint.getBaseValue() url = baseRequestResponse.getUrl() idFound = list() for ident in ids: # find all identifiers in base value if baseVal.find(ident) >= 0: idFound.append(ident) if len(idFound) == 0: # no given identifier found, nothing to do return None baseResponse = baseRequestResponse.getResponse().tostring() baseResponseBody = baseResponse[self.helpers.analyzeResponse(baseResponse).getBodyOffset():] issues = list() scannedCombos = list() for replaceId in idFound: # scanner checks: replace found id by other given ids for scanId in ids: if replaceId == scanId or set([replaceId, scanId]) in scannedCombos: continue scannedCombos.append(set([replaceId, scanId])) scanPayload = baseVal.replace(replaceId, scanId) scanRequest = insertionPoint.buildRequest(scanPayload) scanRequestResponse = self.callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), scanRequest) scanResponse = scanRequestResponse.getResponse().tostring() scanResponseBody = scanResponse[self.helpers.analyzeResponse(scanResponse).getBodyOffset():] if baseResponseBody == scanResponseBody: # response hasn't changed - no issue continue # Analyze responses replaceValue = self.tabledata.getValue(replaceId) scanValue = self.tabledata.getValue(scanId) # naming convention: # first word: base || scan (response) # second word: Replace || Scan (value) if replaceValue != "": baseReplaceValueCount = len(baseResponseBody.split(replaceValue)) - 1 scanReplaceValueCount = len(scanResponseBody.split(replaceValue)) - 1 else: baseReplaceValueCount = 0 scanReplaceValueCount = 0 if scanValue != "": baseScanValueCount = len(baseResponseBody.split(scanValue)) - 1 scanScanValueCount = len(scanResponseBody.split(scanValue)) - 1 else: baseScanValueCount = 0 scanScanValueCount = 0 if scanScanValueCount == 0: # Scan identifier content value doesn't appears, but responses differ issueCase = SessionAuthActiveScanIssue.caseScanValueNotFound elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount == baseReplaceValueCount: # Scan identifier replaces all occurrences of the original identifier in the response issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsExactly elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount > 0: # Scan identfiers value appears, replaced ids value disappears issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsFuzzy elif baseReplaceValueCount > scanReplaceValueCount and baseScanValueCount < scanScanValueCount: # Occurence count of replaced id value decreases, scan id value increases issueCase = SessionAuthActiveScanIssue.caseDecreaseIncrease elif baseScanValueCount < scanScanValueCount: # Occurence count of scan id value increases issueCase = SessionAuthActiveScanIssue.caseScanValueIncrease else: # Remainingg cases issueCase = SessionAuthActiveScanIssue.caseOther issues.append(SessionAuthActiveScanIssue( url, baseRequestResponse, insertionPoint, scanPayload, scanRequestResponse, replaceId, replaceValue, scanId, scanValue, issueCase, self.callbacks )) if len(issues) > 0: return issues else: return None def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getIssueDetail() == newIssue.getIssueDetail(): return 1 else: return 0
class BurpExtender(IBurpExtender,ITab,IHttpListener): def registerExtenderCallbacks(self,callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() self.callbacks.setExtensionName("KkMultiProxy") self.PROXY_LIST = [] self.jPanel = JPanel() boxVertical = Box.createVerticalBox() boxHorizontal = Box.createHorizontalBox() boxHorizontal.add(JButton("File",actionPerformed=self.getFile)) self.FileText = JTextField("") boxHorizontal.add(self.FileText) boxVertical.add(boxHorizontal) TableHeader = ('IP','PORT') TableModel = DefaultTableModel(self.PROXY_LIST,TableHeader) self.Table = JTable(TableModel) boxVertical.add(self.Table) boxHorizontal = Box.createHorizontalBox() boxHorizontal.add(JButton("Add",actionPerformed=self.addIP)) boxHorizontal.add(JButton("Delete",actionPerformed=self.deleteIP)) boxHorizontal.add(JButton("Save",actionPerformed=self.saveIP)) boxVertical.add(boxHorizontal) self.jPanel.add(boxVertical) self.callbacks.addSuiteTab(self) self.callbacks.registerHttpListener(self) return def getFile(self,button): dlg = JFileChooser() result = dlg.showOpenDialog(None) if result == JFileChooser.APPROVE_OPTION: f = dlg.getSelectedFile() path = f.getPath() self.FileText.setText(path) try: self.getIPList(path) except: exit(0) def addIP(self,button): #chooser = JFileChooser() #chooser.showOpenDialog(None) demo = DialogDemo(self.Table) def deleteIP(self,button): selectRows = len(self.Table.getSelectedRows()) TableModel = self.Table.getModel() if selectRows: selectedRowIndex = self.Table.getSelectedRow() TableModel.removeRow(selectedRowIndex) def saveIP(self,button): TableModel = self.Table.getModel() rowCount = TableModel.getRowCount() result_str = "" for i in range(rowCount): if i == 0: result_str+=TableModel.getValueAt(i,0)+':'+TableModel.getValueAt(i,1) else: result_str+='|'+TableModel.getValueAt(i,0)+':'+TableModel.getValueAt(i,1) print result_str f = open(self.FileText.getText(),'w+') f.write(result_str) f.close() def getTabCaption(self): return "MultiProxy" def getUiComponent(self): return self.jPanel def processHttpMessage(self,toolFlag,messageIsRequest,messageInfo): if messageIsRequest: httpService = messageInfo.getHttpService() print httpService.getHost() # if the host is HOST_FROM, change it to HOST_TO i = randint(0,len(self.TableDatas)-1) messageInfo.setHttpService(self.helpers.buildHttpService(self.PROXY_LIST[i]['ip'], self.PROXY_LIST[i]['port'], httpService.getProtocol())) print messageInfo.getHttpService().getHost() def getIPList(self,path): f = open(path,'r+') content = f.read() f.close() if content: ip_array = content.split('|') for _ip in ip_array: ip = _ip.split(':')[0] port = _ip.split(':')[1] self.PROXY_LIST.append([ip,port]) print self.PROXY_LIST
class PropertyEditor(WindowAdapter): """ Edits Tabular Properties of a given WindowAdapter """ instances = {} last_location = None locations = {} last_size = None sizes = {} NEW_WINDOW_OFFSET = 32 offset = NEW_WINDOW_OFFSET @staticmethod def get_instance(text="Property Editor", columns=None, data=None, empty=None, add_actions=True, actions=None): """ Singleton Method based on the text property. It tries to generate only one property configuration page per text. :param text: getinstance key :param columns: proparty columns it should be an array alike :param data: it contains the current property rows :param empty: empty row property when adding a new one :param add_actions: include or not new actions :param actions: default set of actions to be appended to Add and Delete Rows :return: a new instance of PropertyEditor or a reused one. """ if not actions: actions = [] if not columns: columns = [] if data == None: data = [] if not empty: empty = [] try: PropertyEditor.instances[text] except KeyError: PropertyEditor.instances[text] = \ PropertyEditor().__private_init__(text, columns, data, empty, add_actions, actions) try: PropertyEditor.instances[text].this.setLocation( PropertyEditor.locations[text]) except KeyError: if PropertyEditor.last_location: PropertyEditor.instances[text].this.setLocation( PropertyEditor.last_location.x + PropertyEditor.offset, PropertyEditor.last_location.y + PropertyEditor.offset) PropertyEditor.offset = PropertyEditor.NEW_WINDOW_OFFSET try: PropertyEditor.instances[text].this.setSize( PropertyEditor.sizes[text]) except KeyError: if PropertyEditor.last_size: PropertyEditor.instances[text].this.setSize( PropertyEditor.last_size) PropertyEditor.last_location = PropertyEditor.instances[ text].this.getLocation() PropertyEditor.last_size = PropertyEditor.instances[ text].this.getSize() ## Hack ON: Bring on Front PropertyEditor.instances[text].this.setAlwaysOnTop(True) PropertyEditor.instances[text].this.setAlwaysOnTop(False) ## Hack OFF return PropertyEditor.instances[text] def __private_init__(self, text="Property Editor", columns=None, data=None, empty=None, add_actions=True, actions=None): if not actions: actions = [] if not columns: columns = [] if data == None: data = [] if not empty: empty = [] self._text = text self.this = JFrame(text) self._table = JTable() self._dtm = DefaultTableModel(0, 0) self._dtm.setColumnIdentifiers(columns) self._table.setModel(self._dtm) self._data = data for d in data: self._dtm.addRow(d) self._pane = JScrollPane(self._table) self.this.add(self._pane) self._empty = empty self.this.addWindowListener(self) self._dtm.addTableModelListener(lambda _: self._update_model()) self.this.setLocation(PropertyEditor.NEW_WINDOW_OFFSET, PropertyEditor.NEW_WINDOW_OFFSET) if add_actions: self._popup = JPopupMenu() self._pane.setComponentPopupMenu(self._popup) inherits_popup_menu(self._pane) self._actions = actions self._actions.append( ExecutorAction('Remove Selected Rows', action=lambda e: self._remove_row())) self._actions.append( ExecutorAction('Add New Row', action=lambda e: self._add_row())) for action in self._actions: self._popup.add(action.menuitem) self.this.setForeground(Color.black) self.this.setBackground(Color.lightGray) self.this.pack() self.this.setVisible(True) self.this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) return self def _add_row(self): """ Add a new row the selection :return: None """ self._dtm.addRow(self._empty) def _remove_row(self): """ Remove all the selected rows from the selection :return: """ rows = self._table.getSelectedRows() for i in range(0, len(rows)): self._dtm.removeRow(rows[i] - i) def windowClosing(self, evt): """ Overrides WindowAdapter method :param evt: unused :return: None """ PropertyEditor.locations[self._text] = self.this.getLocation() PropertyEditor.sizes[self._text] = self.this.getSize() PropertyEditor.last_location = self.this.getLocation() PropertyEditor.last_size = self.this.getSize() PropertyEditor.offset = 0 self.this.setVisible(False) self.this.dispose() del PropertyEditor.instances[self._text] def _update_model(self): """ Update the data content with the updated rows :return: None """ del self._data[:] nRow = self._dtm.getRowCount() nCol = self._dtm.getColumnCount() for i in range(0, nRow): self._data.append([None] * nCol) for j in range(0, nCol): d = str(self._dtm.getValueAt(i, j)).lower() if d == 'none' or d == '': self._data[i][j] = None elif d == 'true' or d == 't': self._data[i][j] = True elif d == 'false' or d == 'f': self._data[i][j] = False else: try: self._data[i][j] = int(self._dtm.getValueAt(i, j)) except ValueError: self._data[i][j] = self._dtm.getValueAt(i, j)
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener): """Dialog with preferences """ def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText( self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText( self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel( self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont( Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText( self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder( ) self.maxErrorsNumberTextField.getDocument().addDocumentListener( ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox( self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText( self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = [ "", self.app.strings.getString("Type"), self.app.strings.getString("Name") ] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText( self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack() def windowClosing(self, windowEvent): self.on_cancelBtn_clicked() def hyperlinkUpdate(self, e): if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED: OpenBrowser.displayUrl(e.getURL().toString()) def itemStateChanged(self, e): """A ttol has been activated/deactivated. Check if at least one tool is on. """ if all(not button.isSelected() for button in self.toolsCBtns): JOptionPane.showMessageDialog( Main.parent, self.app.strings.getString("tools_disabled_warning"), self.app.strings.getString("tools_disabled_warning_title"), JOptionPane.WARNING_MESSAGE) source = e.getItemSelectable() source.setSelected(True) def actionPerformed(self, e=None): """Enable/disable favourite zones panel """ for container in (self.scrollPane, self.buttonsPanel): self.enableComponents(container, self.favZoneStatusCBtn.isSelected()) if self.favZoneStatusCBtn.isSelected(): self.check_removeBtn_status() def enableComponents(self, container, enable): components = container.getComponents() for component in components: component.setEnabled(enable) if isinstance(component, Container): self.enableComponents(component, enable) def on_downloadBtn_clicked(self, e): update_checker.Updater(self.app, "manual") def clean_map(self): """Remove all rectangles and polygons from the map """ self.zonesMap.removeAllMapRectangles() self.zonesMap.removeAllMapPolygons() def update_gui_from_preferences(self): """Update gui status of preferences frame from config file """ #print "\n- updating Preferences gui" onOff = {"on": True, "off": False} #1 Tab #check for update self.updateCBtn.setSelected(onOff[self.app.checkUpdate]) #tools status, enabled or not for toolIndex, tool in enumerate(self.app.realTools): if "tool.%s" % tool.name in self.app.properties.keys(): configstatus = self.app.properties.getProperty("tool.%s" % tool.name) else: configstatus = "on" # new tool self.toolsCBtns[toolIndex].setSelected(onOff[configstatus]) #layers preferences for mode, button in self.layersRBtns.iteritems(): button.setSelected(mode == self.app.layersMode) #max errors number self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber)) #stats panel self.app.dlg.update_favourite_zone_indicator() #2 Tab #favourite area self.update_favourite_area_gui_from_preferences() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: tool.prefsGui.update_gui(tool.prefs) def update_favourite_area_gui_from_preferences(self): #status self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus) #table #store zones to a temporary list, used to store changes #and save them when preferences dialog is closed self.app.tempZones = list(self.app.zones) self.zonesTable.getModel().setNumRows(0) for zone in self.app.tempZones: self.zonesTable.getModel().addRow( [zone.country, zone.icon, zone.name]) if self.app.favZone is not None: selectedRow = self.app.tempZones.index(self.app.favZone) self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow) self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30) self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50) #enable or disable favourite zone buttons self.actionPerformed() ### fav area editing buttons ########################################### def on_removeBtn_clicked(self, e): rowsNum = self.zonesTable.getSelectedRows() rowsNum.reverse() for rowNum in rowsNum: del self.app.tempZones[rowNum] self.zonesTable.getModel().removeRow(rowNum) if len(self.app.tempZones) != 0: if rowNum == 0: self.zonesTable.setRowSelectionInterval(0, 0) else: self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1) self.check_removeBtn_status() def check_removeBtn_status(self): if self.app.tempZones != [] and len( self.zonesTable.getSelectedRows()) != 0: self.removeBtn.setEnabled(True) else: self.removeBtn.setEnabled(False) self.clean_map() def on_newBtn_clicked(self, e): try: self.newZoneDialog except AttributeError: self.newZoneDialog = NewZoneDialog(self.app) bbox = self.app.get_frame_bounds() self.app.newZone = Zone(self.app, self.app.strings.getString("New_zone"), "rectangle", ",".join(["%0.4f" % x for x in bbox]), "") self.newZoneDialog.update_gui_from_preferences() self.newZoneDialog.show() ### Exit from preferences ############################################## def on_cancelBtn_clicked(self, event=None): if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible(): self.newZoneDialog.close_dialog() self.dispose() def on_saveBtn_clicked(self, event): """Read preferences from gui and save them to config.properties file """ #print "\n- saving preferences to config file" onOff = {True: "on", False: "off"} #1 Tab #check for update self.app.properties.setProperty("check_for_update", onOff[self.updateCBtn.isSelected()]) #tools status for toolIndex, tool in enumerate(self.app.realTools): prop = "tool.%s" % tool.name toolCBtn = self.toolsCBtns[toolIndex] self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()]) #layers preferences for mode, button in self.layersRBtns.iteritems(): if button.isSelected(): self.app.properties.setProperty("layers_mode", mode) break #max errors number try: num = Integer.parseInt(self.maxErrorsNumberTextField.getText()) except NumberFormatException: num = "" self.app.properties.setProperty("max_errors_number", str(num)) #2 Tab #Favourite zones changes = { "new": [z for z in self.app.tempZones if not z in self.app.zones], "deleted": [z for z in self.app.zones if not z in self.app.tempZones] } #delete files of removed favourite zones for zone in changes["deleted"]: f = File( File.separator.join([ self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name ])) f.delete() #create files for new favourite zones for zone in changes["new"]: print "\nsave new zone", zone.name fileName = File.separator.join([ self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name ]) f = open(fileName, "w") zoneData = zone.geomString if zone.country != "": zoneData += "|" + zone.country f.write(zoneData.encode("utf-8")) f.close() self.app.zones = self.app.tempZones if len(self.app.zones) == 0: self.app.favZone = None self.app.properties.setProperty("favourite_area.name", "") self.favZoneStatusCBtn.setSelected(False) else: if len(self.zonesTable.getSelectedRows()) == 0: self.app.favZone = self.app.zones[0] else: self.app.favZone = self.app.zones[ self.zonesTable.getSelectedRows()[0]] self.app.properties.setProperty("favourite_area.name", self.app.favZone.name) favZoneStatus = self.favZoneStatusCBtn.isSelected() self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus]) self.app.favouriteZoneStatus = favZoneStatus #stats panel self.app.dlg.update_favourite_zone_indicator() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: for pref, value in tool.prefsGui.read_gui().iteritems(): prefKey = "tool.%s.%s" % (tool.name, pref) self.app.properties.setProperty(prefKey, value) self.app.save_config() self.dispose()
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener): """Dialog with preferences """ def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder() self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = ["", self.app.strings.getString("Type"), self.app.strings.getString("Name")] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack() def windowClosing(self, windowEvent): self.on_cancelBtn_clicked() def hyperlinkUpdate(self, e): if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED: OpenBrowser.displayUrl(e.getURL().toString()) def itemStateChanged(self, e): """A ttol has been activated/deactivated. Check if at least one tool is on. """ if all(not button.isSelected() for button in self.toolsCBtns): JOptionPane.showMessageDialog( Main.parent, self.app.strings.getString("tools_disabled_warning"), self.app.strings.getString("tools_disabled_warning_title"), JOptionPane.WARNING_MESSAGE) source = e.getItemSelectable() source.setSelected(True) def actionPerformed(self, e=None): """Enable/disable favourite zones panel """ for container in (self.scrollPane, self.buttonsPanel): self.enableComponents(container, self.favZoneStatusCBtn.isSelected()) if self.favZoneStatusCBtn.isSelected(): self.check_removeBtn_status() def enableComponents(self, container, enable): components = container.getComponents() for component in components: component.setEnabled(enable) if isinstance(component, Container): self.enableComponents(component, enable) def on_downloadBtn_clicked(self, e): update_checker.Updater(self.app, "manual") def clean_map(self): """Remove all rectangles and polygons from the map """ self.zonesMap.removeAllMapRectangles() self.zonesMap.removeAllMapPolygons() def update_gui_from_preferences(self): """Update gui status of preferences frame from config file """ #print "\n- updating Preferences gui" onOff = {"on": True, "off": False} #1 Tab #check for update self.updateCBtn.setSelected(onOff[self.app.checkUpdate]) #tools status, enabled or not for toolIndex, tool in enumerate(self.app.realTools): if "tool.%s" % tool.name in self.app.properties.keys(): configstatus = self.app.properties.getProperty("tool.%s" % tool.name) else: configstatus = "on" # new tool self.toolsCBtns[toolIndex].setSelected(onOff[configstatus]) #layers preferences for mode, button in self.layersRBtns.iteritems(): button.setSelected(mode == self.app.layersMode) #max errors number self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber)) #stats panel self.app.dlg.update_favourite_zone_indicator() #2 Tab #favourite area self.update_favourite_area_gui_from_preferences() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: tool.prefsGui.update_gui(tool.prefs) def update_favourite_area_gui_from_preferences(self): #status self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus) #table #store zones to a temporary list, used to store changes #and save them when preferences dialog is closed self.app.tempZones = list(self.app.zones) self.zonesTable.getModel().setNumRows(0) for zone in self.app.tempZones: self.zonesTable.getModel().addRow([zone.country, zone.icon, zone.name]) if self.app.favZone is not None: selectedRow = self.app.tempZones.index(self.app.favZone) self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow) self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30) self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50) #enable or disable favourite zone buttons self.actionPerformed() ### fav area editing buttons ########################################### def on_removeBtn_clicked(self, e): rowsNum = self.zonesTable.getSelectedRows() rowsNum.reverse() for rowNum in rowsNum: del self.app.tempZones[rowNum] self.zonesTable.getModel().removeRow(rowNum) if len(self.app.tempZones) != 0: if rowNum == 0: self.zonesTable.setRowSelectionInterval(0, 0) else: self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1) self.check_removeBtn_status() def check_removeBtn_status(self): if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0: self.removeBtn.setEnabled(True) else: self.removeBtn.setEnabled(False) self.clean_map() def on_newBtn_clicked(self, e): try: self.newZoneDialog except AttributeError: self.newZoneDialog = NewZoneDialog(self.app) bbox = self.app.get_frame_bounds() self.app.newZone = Zone(self.app, self.app.strings.getString("New_zone"), "rectangle", ",".join(["%0.4f" % x for x in bbox]), "") self.newZoneDialog.update_gui_from_preferences() self.newZoneDialog.show() ### Exit from preferences ############################################## def on_cancelBtn_clicked(self, event=None): if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible(): self.newZoneDialog.close_dialog() self.dispose() def on_saveBtn_clicked(self, event): """Read preferences from gui and save them to config.properties file """ #print "\n- saving preferences to config file" onOff = {True: "on", False: "off"} #1 Tab #check for update self.app.properties.setProperty("check_for_update", onOff[self.updateCBtn.isSelected()]) #tools status for toolIndex, tool in enumerate(self.app.realTools): prop = "tool.%s" % tool.name toolCBtn = self.toolsCBtns[toolIndex] self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()]) #layers preferences for mode, button in self.layersRBtns.iteritems(): if button.isSelected(): self.app.properties.setProperty("layers_mode", mode) break #max errors number try: num = Integer.parseInt(self.maxErrorsNumberTextField.getText()) except NumberFormatException: num = "" self.app.properties.setProperty("max_errors_number", str(num)) #2 Tab #Favourite zones changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones], "deleted": [z for z in self.app.zones if not z in self.app.tempZones]} #delete files of removed favourite zones for zone in changes["deleted"]: f = File(File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name])) f.delete() #create files for new favourite zones for zone in changes["new"]: print "\nsave new zone", zone.name fileName = File.separator.join([self.app.SCRIPTDIR, "configuration", "favourite_zones", "%s.txt" % zone.name]) f = open(fileName, "w") zoneData = zone.geomString if zone.country != "": zoneData += "|" + zone.country f.write(zoneData.encode("utf-8")) f.close() self.app.zones = self.app.tempZones if len(self.app.zones) == 0: self.app.favZone = None self.app.properties.setProperty("favourite_area.name", "") self.favZoneStatusCBtn.setSelected(False) else: if len(self.zonesTable.getSelectedRows()) == 0: self.app.favZone = self.app.zones[0] else: self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]] self.app.properties.setProperty("favourite_area.name", self.app.favZone.name) favZoneStatus = self.favZoneStatusCBtn.isSelected() self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus]) self.app.favouriteZoneStatus = favZoneStatus #stats panel self.app.dlg.update_favourite_zone_indicator() self.app.dlg.update_statsPanel_status() #3 Tab #tools preferences for tool in self.app.allTools: if hasattr(tool, 'prefs') and tool.prefsGui is not None: for pref, value in tool.prefsGui.read_gui().iteritems(): prefKey = "tool.%s.%s" % (tool.name, pref) self.app.properties.setProperty(prefKey, value) self.app.save_config() self.dispose()
class BurpExtender(IBurpExtender, ITab, IHttpListener): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() self.callbacks.setExtensionName("KkMultiProxy") self.PROXY_LIST = [] self.jPanel = JPanel() boxVertical = Box.createVerticalBox() boxHorizontal = Box.createHorizontalBox() boxHorizontal.add(JButton("File", actionPerformed=self.getFile)) self.FileText = JTextField("") boxHorizontal.add(self.FileText) boxVertical.add(boxHorizontal) TableHeader = ('IP', 'PORT') TableModel = DefaultTableModel(self.PROXY_LIST, TableHeader) self.Table = JTable(TableModel) boxVertical.add(self.Table) boxHorizontal = Box.createHorizontalBox() boxHorizontal.add(JButton("Add", actionPerformed=self.addIP)) boxHorizontal.add(JButton("Delete", actionPerformed=self.deleteIP)) boxHorizontal.add(JButton("Save", actionPerformed=self.saveIP)) boxVertical.add(boxHorizontal) self.jPanel.add(boxVertical) self.callbacks.addSuiteTab(self) self.callbacks.registerHttpListener(self) return def getFile(self, button): dlg = JFileChooser() result = dlg.showOpenDialog(None) if result == JFileChooser.APPROVE_OPTION: f = dlg.getSelectedFile() path = f.getPath() self.FileText.setText(path) try: self.getIPList(path) except: exit(0) def addIP(self, button): #chooser = JFileChooser() #chooser.showOpenDialog(None) demo = DialogDemo(self.Table) def deleteIP(self, button): selectRows = len(self.Table.getSelectedRows()) TableModel = self.Table.getModel() if selectRows: selectedRowIndex = self.Table.getSelectedRow() TableModel.removeRow(selectedRowIndex) def saveIP(self, button): TableModel = self.Table.getModel() rowCount = TableModel.getRowCount() result_str = "" for i in range(rowCount): if i == 0: result_str += TableModel.getValueAt( i, 0) + ':' + TableModel.getValueAt(i, 1) else: result_str += '|' + TableModel.getValueAt( i, 0) + ':' + TableModel.getValueAt(i, 1) print result_str f = open(self.FileText.getText(), 'w+') f.write(result_str) f.close() def getTabCaption(self): return "MultiProxy" def getUiComponent(self): return self.jPanel def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if messageIsRequest: httpService = messageInfo.getHttpService() print httpService.getHost() # if the host is HOST_FROM, change it to HOST_TO i = randint(0, len(self.TableDatas) - 1) messageInfo.setHttpService( self.helpers.buildHttpService(self.PROXY_LIST[i]['ip'], self.PROXY_LIST[i]['port'], httpService.getProtocol())) print messageInfo.getHttpService().getHost() def getIPList(self, path): f = open(path, 'r+') content = f.read() f.close() if content: ip_array = content.split('|') for _ip in ip_array: ip = _ip.split(':')[0] port = _ip.split(':')[1] self.PROXY_LIST.append([ip, port]) print self.PROXY_LIST