Esempio n. 1
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with "+person.name)
        self.display = JTextArea(columns=100,
                                 rows=15,
                                 editable=0,
                                 lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n"+self.person.client.name+": "+text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n"+self.person.name+": "+text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with "+newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
Esempio n. 2
0
 def run_fn(event):
     log_window = JFrame('Galahad Log')
     log_text_area = JTextArea()
     log_text_area.editable = False
     log_window.setSize(400, 500)
     log_window.add(log_text_area)
     log_window.show()
     log_text_area.append('sdfsdfsdfsdfsd %d' % 3)
Esempio n. 3
0
 def run_fn(event):
     log_window = JFrame('Galahad Log')
     log_text_area = JTextArea()
     log_text_area.editable = False
     log_window.setSize(400, 500)
     log_window.add(log_text_area)
     log_window.show()
     log_text_area.append('sdfsdfsdfsdfsd %d' % 3)
Esempio n. 4
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with " + person.name)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n" + self.person.client.name + ": " + text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n" + self.person.name + ": " + text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with " + newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
Esempio n. 5
0
    def initComponents(self):
        textArea = JTextArea(40, 50)
        aboutLabel = JLabel('About us')
        footLabel = JLabel('Thank you for using Smart Park')
        textArea.setLineWrap(True)
        # textArea.setPreferredSize(Dimension( 250,250))

        #WRITING INTO TEXT AREA
        f = open('about.txt', 'r')
        line = f.read()
        textArea.append(line)
        f.close()
        textArea.setEditable(False)

        self.add(aboutLabel, BorderLayout.PAGE_START)
        self.add(JScrollPane(textArea), BorderLayout.CENTER)
        self.add(footLabel, BorderLayout.PAGE_END)
class BurpExtender(IBurpExtender, IContextMenuFactory):
    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        self.printHeader()

        # Set extension name
        callbacks.setExtensionName("Directory Listing Parser for Burp Suite")

        # Callbacks object
        self._callbacks = callbacks

        # Helpers object
        self._helpers = callbacks.getHelpers()

        # Register a factory for custom context menu items
        callbacks.registerContextMenuFactory(self)

        return

    # Create a menu item if the appropriate section of the UI is selected
    def createMenuItems(self, invocation):
        menu = []

        # Which part of the interface the user selects
        ctx = invocation.getInvocationContext()

        # Message Viewer Req/Res, Site Map Table, and Proxy History will show menu item if selected by the user
        if ctx == 2 or ctx == 3 or  ctx == 4 or ctx == 5 or ctx == 6:
            menu.append(JMenuItem("Import Directory Listing", None, actionPerformed=lambda x, inv=invocation: self.openGUI(inv)))

        return menu if menu else None

    # Create and place GUI components on JFrame
    def openGUI(self, invocation):
        try:
            # Get values from request or response the extension is invoked from and prepopulate GUI values
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0]
            originalHttpService = message.getHttpService()
            self.originalMsgProtocol = originalHttpService.getProtocol()
            self.originalMsgHost = originalHttpService.getHost()
            self.originalMsgPort = originalHttpService.getPort()
        except:
            self.originalMsgProtocol = ''
            self.originalMsgHost = ''
            self.originalMsgPort = ''

        try:
            self.cookies = self._callbacks.getCookieJarContents()
            self.cookie = ''
        except:
            pass

        self.SSL = 'http://'
        self.listType = ''
        self.parsedList = []

        # Set up main window (JFrame)
        self.window = JFrame("Directory Listing Parser for Burp Suite", preferredSize=(600, 475), windowClosing=self.closeUI)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        emptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10)
        self.window.contentPane.setBorder(emptyBorder)
        self.window.contentPane.layout = BorderLayout()

        # Main window title placed at the top of the main window with an invisible bottom border
        titlePanel = JPanel()
        titleBorder = BorderFactory.createEmptyBorder(0, 0, 10, 0)
        title = JLabel("Directory Listing Parser for Burp Suite", JLabel.CENTER)
        title.setBorder(titleBorder)
        title.setFont(Font("Default", Font.PLAIN, 18))
        titlePanel.add(title)
        self.window.contentPane.add("North", titlePanel)

        # Left panel for user input, consisting of hostname, directory prefix, ssl, port, type of listing, and file
        self.leftPanel = JPanel()
        self.leftPanel.layout = GridLayout(14, 1, 3, 3)
        hostnameLabel = JLabel("Hostname:")

        if self.originalMsgHost:
            self.hostnameTextField = JTextField(self.originalMsgHost.rstrip())
        else:
            self.hostnameTextField = JTextField('Hostname')

        dirPrefixLabel = JLabel("Full Directory Prefix (Windows):")
        self.dirPrefixField = JTextField('C:\\var\www\\')
        
        sslLabel = JLabel("SSL:")
        self.radioBtnSslEnabled = JRadioButton('Enabled (https)', actionPerformed=self.radioSsl)
        self.radioBtnSslDisabled = JRadioButton('Disabled (http)', actionPerformed=self.radioSsl)
        sslButtonGroup = ButtonGroup()
        sslButtonGroup.add(self.radioBtnSslEnabled)
        sslButtonGroup.add(self.radioBtnSslDisabled)
        
        if self.originalMsgProtocol == "https":
            self.radioBtnSslEnabled.setSelected(True)
        else:
            self.radioBtnSslDisabled.setSelected(True)
        
        portLabel = JLabel("Port:")

        if self.originalMsgPort:
            self.portTextField = JTextField(str(self.originalMsgPort).rstrip())
        else:
            self.portTextField = JTextField('80')

        osLabel = JLabel("Type of File Listing:")
        self.types = ('Windows \'dir /s\'', 'Linux \'ls -lR\'', 'Linux \'ls -R\'')
        self.comboListingType = JComboBox(self.types)
        uploadLabel = JLabel("Directory Listing File:")
        self.uploadTextField = JTextField('')
        uploadButton = JButton('Choose File', actionPerformed=self.chooseFile)

        self.leftPanel.add(hostnameLabel)
        self.leftPanel.add(self.hostnameTextField)
        self.leftPanel.add(dirPrefixLabel)
        self.leftPanel.add(self.dirPrefixField)
        self.leftPanel.add(sslLabel)
        self.leftPanel.add(self.radioBtnSslEnabled)
        self.leftPanel.add(self.radioBtnSslDisabled)
        self.leftPanel.add(portLabel)
        self.leftPanel.add(self.portTextField)
        self.leftPanel.add(osLabel)
        self.leftPanel.add(self.comboListingType)
        self.leftPanel.add(uploadLabel)
        self.leftPanel.add(self.uploadTextField)
        self.leftPanel.add(uploadButton)

        # Right panel consisting of a text area for the URL list
        self.UrlPanelLabel = JLabel("URL List:")
        self.textArea = JTextArea()
        self.textArea.setEditable(True)
        self.textArea.setFont(Font("Default", Font.PLAIN, 14))
        if self.cookies:
            self.textArea.append('Cookies Found:\n')
            for cookie in self.cookies:
                if cookie.getDomain() in self.originalMsgHost:
                    self.cookie += cookie.getName() + '=' + cookie.getValue() + '; '
                    self.textArea.append(cookie.getName() + '=' + cookie.getValue() + '\n')
        scrollArea = JScrollPane(self.textArea)
        scrollArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        scrollArea.setPreferredSize(Dimension(400, 200))
        self.rightPanel = JPanel()
        self.rightPanel.setLayout(BorderLayout(3, 3))
        self.rightPanel.add(self.UrlPanelLabel, BorderLayout.NORTH)
        self.rightPanel.add(scrollArea, BorderLayout.CENTER)
        
        # Panel for the generate URL list and import URL list buttons
        generatePanel = JPanel()
        generatePanel.layout = BorderLayout(3, 3)
        generateButton = JButton('Generate URL List', actionPerformed=self.generateUrlList)
        importButton = JButton('Import URL List to Burp Site Map', actionPerformed=self.confirmImport)
        generatePanel.add("North", generateButton)
        generatePanel.add("South", importButton)
        self.rightPanel.add("South", generatePanel)

        # Add the two main panels to the left and right sides
        self.window.contentPane.add("East", self.rightPanel)
        self.window.contentPane.add("West", self.leftPanel)

        # Create a panel to be used for the file chooser window
        self.uploadPanel = JPanel()
        
        self.window.pack()
        self.window.show()

    # JFileChooser and showDialog for the user to specify their directory listing input file
    def chooseFile(self, event):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("c files", ["c"])
        chooseFile.addChoosableFileFilter(filter)
        chooseFile.showDialog(self.uploadPanel, "Choose File")
        chosenFile = chooseFile.getSelectedFile()
        self.uploadTextField.text = str(chosenFile)

    # Set whether https is enabled.  Default is disabled (http)
    def radioSsl(self, event):
        if self.radioBtnSslEnabled.isSelected():
            self.SSL = 'https://'
        else:
            self.SSL = 'http://'

    # Create a parser object and pass the user's specified options.  Retrieve the results and print them to a text area
    def generateUrlList(self, event):
        fileListingType = self.comboListingType.selectedIndex
        self.listType = self.types[fileListingType]
        urlsMade = 0
        if os.path.isfile(self.uploadTextField.text):
            parser = ListingParser()
            parser.parse(self.hostnameTextField.getText(), self.dirPrefixField.getText().rstrip(), self.SSL, self.portTextField.getText(), self.listType, self.uploadTextField.getText())
            self.parsedList = parser.returnList()
            self.textArea.setText('')
            for item in self.parsedList:
                self.textArea.append(item + '\n')

            urlsMade = str(len(self.parsedList))
            if self.parsedList and urlsMade:
                self.textArea.append('\n' + 'Total Directories Found: ' + str(parser.directoryCount))
                self.textArea.append('\n' + 'Total URLs Created: ' + urlsMade)
            else:
                self.textArea.append('Error occurred during parsing.\n')
                self.textArea.append('Please make sure the directory listing is a valid format and all input is correct.\n')
                self.textArea.append('E-mail [email protected] with errors or for further help.')
        else:
            JOptionPane.showMessageDialog(None, 'ERROR: File is not valid file or not found!')

    def closeUI(self, event):
        self.window.setVisible(False)
        self.window.dispose()

    # This is initiated by the user selecting the 'import to burp' button.  Checks each generated URL for a valid response and adds it to the site map
    def importList(self):
        if self.parsedList:
            urlsAdded = 0
            # Loop through each URL and check the response.  If the response code is less than 404, add to site map
            for item in self.parsedList:
                # Pass exception if urlopen returns an http error if the URL is not reachable
                try:
                    code = urlopen(item).code
                    if code < 404:
                        javaURL = URL(item)
                        newRequest = self._helpers.buildHttpRequest(javaURL)
                        stringNewRequest = self._helpers.bytesToString(newRequest).rstrip()
                        if self.cookie:
                            stringNewRequest += '\nCookie: ' + self.cookie.rstrip('; ') + '\r\n\r\n'
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), stringNewRequest)
                        else:
                            requestResponse = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(javaURL.getHost()), int(javaURL.getPort()), javaURL.getProtocol() == "https"), newRequest)
                        self._callbacks.addToSiteMap(requestResponse)
                        urlsAdded += 1
                except Exception, e:
                    print e
                    pass
            JOptionPane.showMessageDialog(None, str(urlsAdded) + " URL(s) added to Burp site map.")
        else:
Esempio n. 7
0
class HL7GUIFrame(JFrame):
   outputTextField = None


   def __init__(self):
       super(HL7GUIFrame, self).__init__()

       self.initUI()

   def initUI(self):

       global outputTextField
       self.panel = JPanel()
       self.panel.setLayout(BorderLayout())

       toolbar = JToolBar()
       openb = JButton("Choose input file", actionPerformed=self.onClick)
       outputLabel = JLabel("   Enter output file name:  ")
       outputTextField = JTextField("hl7OutputReport.txt", 5)
       print outputTextField.getText()


     


       toolbar.add(openb)
       toolbar.add(outputLabel)
       toolbar.add(outputTextField)
      

       self.area = JTextArea()
       self.area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.area.setText("Select your HL7 ORU messages text file to be converted to tab-delimited flat \nfile with select HL7 fields.\n")
       self.area.append("You can enter the path + file name for your output file or it will default to the current \nfile name in the text field above in your current working directory.")

       pane = JScrollPane()
       pane.getViewport().add(self.area)

       self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
       self.panel.add(pane)
       self.add(self.panel)

       self.add(toolbar, BorderLayout.NORTH)


       self.setTitle("HL7 ORU Results Reporter")
       self.setSize(600, 300)
       self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
       self.setLocationRelativeTo(None)
       self.setVisible(True)
       return outputTextField.getText()


   def onClick(self, e):

       print outputTextField.getText()
       chooseFile = JFileChooser()
       filter = ExampleFileFilter()
       filter.addExtension("txt")
       filter.setDescription("txt HL7 input files")
       chooseFile.setFileFilter(filter)
       

       ##ret = chooseFile.showDialog(self.panel, "Choose file")
       ret = chooseFile.showOpenDialog(self.panel)

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           text = self.readFile(file)
           self.area.append(text)
           outputFile = outputTextField.getText()
           p1 = HL7RepClass.ParseORUClass(file.getCanonicalPath(), outputFile)
           p1.parseORU()
           print "\noutfile = ", outputFile

   def readFile(self, file):
       filename = file.getCanonicalPath()
       print "filename is now ", filename
       f = open(filename, "r")
       
       text = f.read()
     
       return text
class BurpExtender(IBurpExtender, ITab):

    def registerExtenderCallbacks(self, callbacks):

        self._cb = callbacks
        self._hp = callbacks.getHelpers()

        self._cb.setExtensionName('MiniProgram Decrypto')
        print 'successful!'

        self.mainPanel = JPanel()

        

        self.sessionKey = JLabel("sessionKey:")
        self.sessionKey.setHorizontalAlignment(SwingConstants.LEFT);
        
        self.iv = JLabel("iv:")
        self.tfsessionKey = JTextField(50)
        
        self.tfiv = JTextField(50)
        
        self.textAreaPlaintext = JTextArea(30, 40)
        self.textAreaPlaintext.setLineWrap(True)
        self.textAreaPlaintext2 = JTextArea(30, 40)
        self.textAreaPlaintext2.setLineWrap(True)
        self.DecryptoBtn = JButton('Decrypto >', actionPerformed=self.decrypto_onClick)
        self.CryptoBtn = JButton('< Crypto', actionPerformed=self.encrypto_onClick)
        
        self.mainPanel.add(self.sessionKey)
        self.mainPanel.add(self.tfsessionKey)
        self.mainPanel.add(self.iv)
        self.mainPanel.add(self.tfiv)
        
        self.mainPanel.add(self.textAreaPlaintext)
        self.mainPanel.add(self.CryptoBtn)
        self.mainPanel.add(self.DecryptoBtn)
        

        self.mainPanel.add(self.textAreaPlaintext2)

        self._cb.customizeUiComponent(self.mainPanel)
        self._cb.addSuiteTab(self)

    def decrypto_onClick(self, event):
        self.textAreaPlaintext2.setText("")
        session_key = self.tfsessionKey.getText()
        iv = self.tfiv.getText()
        payload = self.textAreaPlaintext.getText().rstrip()
        
        str = self.decrypto(payload, session_key, iv)
        
        self.textAreaPlaintext2.append(str)

    def encrypto_onClick(self, event):
        self.textAreaPlaintext.setText("")
        session_key = self.tfsessionKey.getText()
        iv = self.tfiv.getText()
        payload = self.textAreaPlaintext2.getText().rstrip()
        
        str = self.encrypto(payload, session_key, iv)
        
        self.textAreaPlaintext.append(String(str))


    def getTabCaption(self):
    	return 'MiniProgram Decrypto'

    def getUiComponent(self):
        return self.mainPanel


    def encrypto(self, payload, key, iv):
		aesKey = SecretKeySpec(base64.b64decode(key), "AES")
		aesIV = IvParameterSpec(base64.b64decode(iv))
		cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
		cipher.init(Cipher.ENCRYPT_MODE, aesKey, aesIV)
		encrypted = cipher.doFinal(payload)
		return Base64.getEncoder().encode(encrypted)


    def decrypto(self, payload, key, iv):
		decoded = base64.b64decode(payload)
		
		aesKey = SecretKeySpec(base64.b64decode(key), "AES")
		
		aesIV = IvParameterSpec(base64.b64decode(iv))
		
		cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC")
		cipher.init(Cipher.DECRYPT_MODE, aesKey, aesIV)
		return String(cipher.doFinal(decoded)) 
Esempio n. 9
0
    class ConsoleController:
        def __init__(self, parent):
            self._parent = parent
            self._sessions = self._parent.sessions()
            self._request = None #TODO I'll need a request in order to connect to something
            self._position = None #TODO I'll need a position, something to change in the header to insert the command
            self._pwd = None
            self._commandHistory = []
            self._historyIndex = 0
            self._tabComplete = []

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            # input
            self._consolePwd = JTextField()
            self._consolePwd.setEditable(False)
            self._consolePwd.setText("Not initialized")
            self._consoleInput = JTextField()
            #Remove 'tab' low-level tab-function of jumping to other component, so I can use it
            self._consoleInput.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET)
            self._consoleInput.addActionListener(self.EnterPress())
            self._consoleInput.addKeyListener(self.KeyPress())
            self._inputPanel = JPanel(BorderLayout())
            self._inputPanel.add(self._consolePwd, BorderLayout.WEST)
            self._inputPanel.add(self._consoleInput, BorderLayout.CENTER)
            # output
            self._consoleOutput = JTextArea()
            self._consoleOutput.setEditable(False)
            self._consoleOutput.setForeground(Color.WHITE)
            self._consoleOutput.setBackground(Color.BLACK)
            self._consoleOutput.setFont(self._consoleOutput.getFont().deriveFont(12.0))

            self._scrollPaneConsoleOutput = JScrollPane(self._consoleOutput)

            # Add to main panel and return the main panel
            self._mainPanel.add(self._scrollPaneConsoleOutput, BorderLayout.CENTER)
            self._mainPanel.add(self._inputPanel, BorderLayout.SOUTH)
            return self._mainPanel

        def sendCommand(self, requestId, cmd, directTo):
            Utils.out("ConsoleController > sendCommand > 'cmd'")
            Utils.out(cmd)
            if cmd == 'clear':
                self.resetOutput()
                self._commandHistory.append(cmd)
                self.resetHistoryIndex()
                self.clearCmd()
                return
            cmdModified = cmd
            requestHttpMethod = self._parent.getRequestHttpService(requestId)
            #If I use virtual persistence and there's already a pwd set
            if Utils.shellController._virtualPersistence and self.pwd():
                #Then always prepend 'cd <pwd>' to any command executed. In reality we
                # always enter in the same directory, but because this shell keeps track
                # of where the user thinks he is, and always goes to that directory first
                # the illusion of a persistence is created
                cmdVirtual = "cd " + self.pwd()
                cmdModified = cmdVirtual + "; " + cmd
            requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified)
            Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start()
            self._commandHistory.append(cmd)
            self.resetHistoryIndex()
            self.clearCmd()

            if Utils.shellController._virtualPersistence:
                if cmd.startswith('cd '):
                    Utils.out("ConsoleController > sendCommand: detected 'cd '")
                    #ask for pwd
                    cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start()
                if Utils.shellController._tabCompletion:
                    #ask 'ls -1a' for tab-completion
                    # The first command, pwd is set here, but cmdVirtual ain't. But this
                    # also means we are at the entry directory anyway, so we can just ask ls
                    # and get the correct tab completion anyway
                    try:
                        cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX)
                    except:
                        cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
            else:
                if Utils.shellController._tabCompletion:
                    cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()

            #either way execute the requested command

        def startSession(self):
            #TODO when starting a session I want to test for a number of things:
            # if I can reform the request to a post request and still have it work
            # if base 64 is available
            # if bash is available
            self.setPwd(None)
            if Utils.shellController._virtualPersistence and Utils.shellController._outputIsolator:
                Utils.out("startSession > virtualPersistence enabled > Requesting pwd")
                self.sendCommand(self._parent.currentRequestId(), Commands.pwd(Commands.OS_LINUX), 'pwd')

        def appendOutput(self, text, printCommand=True):
            try:
                if printCommand:
                    self.printCommand(self._commandHistory[-1])
            except:
                pass

            self._consoleOutput.append("\n" + text)
            #auto scroll down if needed
            self._consoleOutput.setCaretPosition(self._consoleOutput.getDocument().getLength())

        def resetOutput(self):
            Utils.setConsole('')

        def printCommand(self, cmd):
            self._consoleOutput.append("\n" + self._pwd + "# " + cmd)

        def printCurrentCommand(self):
            self.printCommand(self.cmd())

        def setPwd(self, pwd):
            self._pwd = pwd
            if pwd is None:
                self._consolePwd.setText('')
            else:
                self._consolePwd.setText(pwd)
            Utils.consoleController._mainPanel.revalidate()

        def pwd(self):
            return self._pwd

        def cmdHistoryCount(self):
            return len(self._commandHistory) #TODO - 1

        def setCmd(self, cmd):
            self._consoleInput.setText(cmd)

        def cmd (self):
            return self._consoleInput.getText()

        def clearCmd(self):
            self._consoleInput.setText('')

        def resetHistoryIndex(self):
            self._historyIndex = self.cmdHistoryCount()

        def previousCommand(self):
            if self._historyIndex > 0:
                self._historyIndex -= 1
                self.setCmd(self._commandHistory[self._historyIndex])

        def nextCommand(self):
            if self._historyIndex < self.cmdHistoryCount():
                self._historyIndex += 1
                self.setCmd(self._commandHistory[self._historyIndex])
            else:
                self.clearCmd()
                self.resetHistoryIndex()

        def setTabComplete(self, text):
            self._tabComplete = text.splitlines()

        def findTabComplete(self, beginCharacters=''):
            suggestions = []
            if beginCharacters:
                for suggestion in self._tabComplete:
                    Utils.debug("suggestion", suggestion)
                    Utils.debug("text", beginCharacters)
                    if suggestion[0:len(beginCharacters)] == beginCharacters:
                        suggestions.append(suggestion)
            else:
                suggestions = self._tabComplete
            return suggestions

        def tabComplete(self):
            currentCommand = self.cmd()
            Utils.debug("currentCommand", currentCommand)
            if currentCommand:
                commandArray = currentCommand.split(' ')
                lastword = commandArray.pop()
                Utils.debug("lastword", lastword)
                suggestions = self.findTabComplete(lastword)
                if suggestions:
                    if len(suggestions) > 1:
                        self.printCurrentCommand()
                        for suggestion in suggestions:
                            self.appendOutput(suggestion, False)
                    if len(suggestions) == 1:
                        self.setCmd(' '.join(commandArray) + ' ' + suggestions.pop())
            else:
                suggestions = self.findTabComplete()
                if len(suggestions) > 1:
                    self.printCurrentCommand()
                    for suggestion in suggestions:
                        self.appendOutput(suggestion, False)

        class EnterPress(ActionListener): #TODO remove: AbstractAction
            def actionPerformed(self, e):
                Utils.consoleController.sendCommand(Utils.shellController.currentRequestId(), Utils.consoleInput.getText(), 'console')

            def keyPressed(self, e):
                Utils.out("key pressed")

        class KeyPress(KeyListener):
            def keyTyped(self, e):
                pass

            def keyReleased(self, e):
                if e.getKeyCode() == e.VK_DOWN:
                    Utils.consoleController.nextCommand()
                    Utils.out("released down")
                if e.getKeyCode() == e.VK_UP:
                    Utils.consoleController.previousCommand()
                    Utils.out("released up")

                if e.getKeyCode() == e.VK_TAB:
                    Utils.out("pressed tab")
                    Utils.consoleController.tabComplete()

            def keyPressed(self, e):
                pass
Esempio n. 10
0
class tag(ITab):
    def __init__(self, callbacks, name):
        self._callbacks = callbacks
        self.name = name

    def getTabCaption(self):
        return self.name

    def getUiComponent(self):
        return self.tabs

    def setFontItalic(self, label):
        label.setFont(
            Font(label.getFont().getName(), Font.ITALIC,
                 label.getFont().getSize()))

    def setFontBold(self, label):
        label.setFont(Font('Serif', Font.BOLD, label.getFont().getSize()))

    # 配置界面添加
    def tagLoad(self):
        # 创建窗口 开始
        self.tabs = JTabbedPane()

        self.settings = JPanel(GridBagLayout())
        self.forward_requests_settings = JPanel(GridBagLayout())
        self.white_list_domain_settings = JPanel(GridBagLayout())

        c = GridBagConstraints()

        # 界面选项卡1-标签加载
        self.tag_1(c)
        self.tag_2(c)

        # 界面选项卡2-标签加载
        self.tag_3(c)
        self.tag_4(c)

        # 界面选项卡3-标签加载
        self.tag_5(c)

        # 添加选项卡
        self.tabs.addTab(u'基本设置', self.settings)
        self.tabs.addTab(u'http请求转发设置', self.forward_requests_settings)
        self.tabs.addTab(u'白名单域名设置', self.white_list_domain_settings)

        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.addSuiteTab(self)

    # 选项卡1-标签1-ui
    def tag_1(self, c):
        # 创建 检查框
        self.is_start_box = JCheckBox(u'是否启动插件',
                                      ForwardRequestsConfig.IS_START)
        self.setFontBold(self.is_start_box)
        self.is_start_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.is_start_box, c)

        # 在窗口添加一句话
        is_start_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_start_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(is_start_box_lbl, c)

    # 选项卡1-标签1-值
    def isStartBox(self):
        return self.is_start_box.isSelected()

    # 选项卡1-标签2-ui
    def tag_2(self, c):
        # 创建 检查框
        self.url_repeated_box = JCheckBox(
            u'是否启动url重复验证', ForwardRequestsConfig.URL_REPEATED_VERIFY)
        self.setFontBold(self.url_repeated_box)
        self.url_repeated_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(self.url_repeated_box, c)

        # 在窗口添加一句话
        url_repeated_box_lbl = JLabel(u'打勾-开启验证, 不打勾-关闭验证')
        self.setFontItalic(url_repeated_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.settings.add(url_repeated_box_lbl, c)

    # 选项卡1-标签2-值
    def urlRepeatedBox(self):
        return self.url_repeated_box.isSelected()

    # 选项卡2-标签1-ui
    def tag_3(self, c):
        # 创建 检查框
        self.is_proxy_forward_requests_box = JCheckBox(
            u'是否启动Proxy模块请求转发(推荐打勾)',
            ForwardRequestsConfig.IS_START_PROXY_FORWARD_REQUESTS)
        self.setFontBold(self.is_proxy_forward_requests_box)
        self.is_proxy_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.forward_requests_settings.add(self.is_proxy_forward_requests_box,
                                           c)

        # 在窗口添加一句话
        is_proxy_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_proxy_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.forward_requests_settings.add(is_proxy_forward_requests_box_lbl,
                                           c)

    # 选项卡2-标签2-ui
    def tag_4(self, c):
        # 创建 检查框
        self.is_repeater_forward_requests_box = JCheckBox(
            u'是否启动Repeater模块请求转发',
            ForwardRequestsConfig.IS_START_REPEATER_FORWARD_REQUESTS)
        self.setFontBold(self.is_repeater_forward_requests_box)
        self.is_repeater_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.forward_requests_settings.add(
            self.is_repeater_forward_requests_box, c)

        # 在窗口添加一句话
        is_repeater_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_repeater_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.forward_requests_settings.add(
            is_repeater_forward_requests_box_lbl, c)

    # 获取允许转发的burp模块列表
    def getWhiteListModule(self):
        white_list_module = []

        if self.is_proxy_forward_requests_box.isSelected():
            white_list_module.append(4)
        if self.is_repeater_forward_requests_box.isSelected():
            white_list_module.append(64)

        return white_list_module

    # 选项卡3-标签1-ui
    def tag_5(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

        # 输入框
        self.white_list_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.white_list_domain_settings.add(self.white_list_text_field, c)

        lblParamsNote = JLabel(u"白名单域名列表")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.white_list_domain_settings.add(lblParamsNote, c)

        # 添加 文本框
        self.white_list_text_area = JTextArea()
        self.white_list_text_area.setColumns(20)
        self.white_list_text_area.setRows(10)
        self.white_list_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.white_list_mouse_listener = TextAreaMouseListener(
            self.white_list_text_area)
        self.white_list_text_area.addMouseListener(
            self.white_list_mouse_listener)

        # 向文本框添加数据
        for name in white_list_names:
            self.white_list_text_area.append(name + '\n' + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.white_list_text_area)
        self.white_list_domain_settings.add(sp, c)

        # 添加 删除 重置
        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.white_list_text_field,
                                  self.white_list_text_area,
                                  self.white_list_mouse_listener,
                                  white_list_names)

        # 添加按钮
        self.white_list_add_button = JButton(
            u'添加', actionPerformed=handlers.handler_add)
        _c.gridy = 1
        buttonsPanel.add(self.white_list_add_button, _c)

        # 删除按钮
        self.white_list_rm_button = JButton(
            u'删除', actionPerformed=handlers.handler_rm)
        _c.gridy = 2
        buttonsPanel.add(self.white_list_rm_button, _c)

        # 重置按钮
        self.white_list_restore_button = JButton(
            u'重置', actionPerformed=handlers.handler_restore)
        _c.gridy = 3
        buttonsPanel.add(self.white_list_restore_button, _c)

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.white_list_domain_settings.add(buttonsPanel, c)

    # 获取白名单域名列表
    def getWhiteList(self):
        return self.text_area_to_list(self.white_list_text_area)

    # 获取指定text数据
    def text_area_to_list(self, text_area):
        l = []
        text_list = text_area.getText().strip().split('\n')
        for data in text_list:
            if data == '':
                continue
            data = data.replace("\n", '')
            data = data.replace("\r", '')
            data = data.strip(' ')
            l.append(data)
        return l
Esempio n. 11
0
class GroupConversationWindow(GroupConversation):
    """A GUI window of a conversation witha  group of people"""
    def __init__(self, group, chatui):
        GroupConversation.__init__(self, group, chatui)
        self.mainframe = JFrame(self.group.name)
        self.headers = ["Member"]
        self.memberdata = UneditableTableModel([], self.headers)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def showGroupMessage(self, sender, text, metadata=None):
        self.displayText(sender + ": " + text)

    def setGroupMembers(self, members):
        GroupConversation.setGroupMembers(self, members)
        self.updatelist()

    def setTopic(self, topic, author):
        topictext = "Topic: " + topic + ", set by " + author
        self.mainframe.setTitle(self.group.name + ": " + topictext)
        self.displayText(topictext)

    def memberJoined(self, member):
        GroupConversation.memberJoined(self, member)
        self.updatelist()

    def memberChangedNick(self, oldnick, newnick):
        GroupConversation.memberChangedNick(self, oldnick, newnick)
        self.updatelist()

    def memberLeft(self, member):
        GroupConversation.memberLeft(self, member)
        self.updatelist()

    #GUI code
    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        memberpane = JTable(self.memberdata)
        memberframe = JScrollPane(memberpane)

        chat = JPanel(doublebuffered)
        chat.setLayout(BoxLayout(chat, BoxLayout.Y_AXIS))
        chat.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        chat.add(self.typepad)
        chat.add(buttons)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.X_AXIS))
        mainpane.add(chat)
        mainpane.add(memberframe)

    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    def updatelist(self):
        self.memberdata.setDataVector([self.members], self.headers)

    #actionListener
    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            GroupConversation.sendText(self, text)

    def hidewindow(self, ae):
        self.hide()
Esempio n. 12
0
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "JSON&HTTPP by [Vulkey_Chen]\nBlog: gh0st.cn\nTeam: MSTSEC"
        self._cb = callbacks
        self._hp = callbacks.getHelpers()
        self._cb.setExtensionName("JSON&HTTPP")
        self.mainPanel = JPanel()
        self.mainPanel.setLayout(BorderLayout())

        self.jsonTextArea = JTextArea(20, 0)
        self.jsonTextArea.setLineWrap(True)

        self.dictTextArea = JTextArea()
        self.dictTextArea.setLineWrap(True)

        self.keyTextArea = JTextArea()
        self.keyTextArea.setLineWrap(True)

        self.valueTextArea = JTextArea()
        self.valueTextArea.setLineWrap(True)

        self.resultPanel = JPanel()
        # self.resultPanel.setLayout(BorderLayout())
        self.resultPanel.layout = GridLayout(1, 3)

        self.jsonTextWrapper = JPanel()
        self.jsonTextWrapper.setLayout(BorderLayout())
        self.jsonTextWrapper.border = BorderFactory.createTitledBorder("Input")
        self.dictTextWrapper = JPanel()
        self.dictTextWrapper.setLayout(BorderLayout())
        self.dictTextWrapper.border = BorderFactory.createTitledBorder(
            "Output")
        self.keyTextWrapper = JPanel()
        self.keyTextWrapper.setLayout(BorderLayout())
        self.keyTextWrapper.border = BorderFactory.createTitledBorder("Keys")
        self.valueTextWrapper = JPanel()
        self.valueTextWrapper.setLayout(BorderLayout())
        self.valueTextWrapper.border = BorderFactory.createTitledBorder(
            "Values")

        self.jsonScrollPane = JScrollPane(self.jsonTextArea)
        self.dictScrollPane = JScrollPane(self.dictTextArea)
        self.valueScrollPane = JScrollPane(self.valueTextArea)
        self.keyScrollPane = JScrollPane(self.keyTextArea)

        self.jsonTextWrapper.add(self.jsonScrollPane, BorderLayout.CENTER)
        self.dictTextWrapper.add(self.dictScrollPane, BorderLayout.CENTER)
        self.keyTextWrapper.add(self.keyScrollPane, BorderLayout.CENTER)
        self.valueTextWrapper.add(self.valueScrollPane, BorderLayout.CENTER)

        self.resultPanel.add(self.dictTextWrapper, BorderLayout.WEST)
        self.resultPanel.add(self.keyTextWrapper, BorderLayout.CENTER)
        self.resultPanel.add(self.valueTextWrapper, BorderLayout.EAST)

        self.mainPanel.add(self.jsonTextWrapper, BorderLayout.NORTH)
        self.mainPanel.add(self.resultPanel, BorderLayout.CENTER)

        self.beautifyButton_1 = JButton("JSON2HTTPP",
                                        actionPerformed=self.onClick1)
        self.beautifyButton_2 = JButton("HTTPP2JSON",
                                        actionPerformed=self.onClick2)
        self.clearButton = JButton("CLEAR", actionPerformed=self.onClear)

        self.buttons = JPanel()
        self.buttons.add(self.beautifyButton_1, BorderLayout.CENTER)
        self.buttons.add(self.beautifyButton_2, BorderLayout.CENTER)
        self.buttons.add(self.clearButton, BorderLayout.CENTER)

        self.mainPanel.add(self.buttons, BorderLayout.SOUTH)

        self._cb.customizeUiComponent(self.mainPanel)
        self._cb.addSuiteTab(self)

    def onClick1(self, event):
        _jsontext = self.jsonTextArea.getText().strip()
        try:
            _jsontext = json.loads(
                re.search(r"\({.*?}\)",
                          _jsontext).group().replace("(", "").replace(")", ""))
        except:
            _jsontext = json.loads(_jsontext)
        self._result = []
        # resultDict format: ["aa=bb","cc=ddd"]
        resultDict = self.json2dict(_jsontext)
        self.dictTextArea.append("\n".join(resultDict))
        keyList = set()
        valueList = set()
        for result in resultDict:
            key, value = result.split("=")[0], result.split("=")[1]
            if len(key) > 0:
                keyList.add(key)
            if len(value) > 0:
                valueList.add(value)
        self.keyTextArea.append("\n".join(keyList))
        self.valueTextArea.append("\n".join(valueList))

        self.dictTextArea.append("\n")
        self.keyTextArea.append("\n")
        self.valueTextArea.append("\n")

    def onClick2(self, event):
        _jsontext = self.jsonTextArea.getText().strip()
        _res = []
        keyList = set()
        valueList = set()
        for i in _jsontext.split("&"):
            args = i.split("=")
            for x in args:
                _res.append(x)
            if len(args[0]) > 0:
                keyList.add(args[0])
            if len(args[1]) > 0:
                valueList.add(args[1])
        self.dictTextArea.append(json.dumps(dict(zip(_res[0::2], _res[1::2]))))
        self.keyTextArea.append("\n".join(keyList))
        self.valueTextArea.append("\n".join(valueList))

        self.dictTextArea.append("\n")
        self.keyTextArea.append("\n")
        self.valueTextArea.append("\n")

    def onClear(self, event):
        self.dictTextArea.setText("")
        self.keyTextArea.setText("")
        self.valueTextArea.setText("")

    def json2dict(self, _jsontext):
        keyValue = ""
        if isinstance(_jsontext, dict):
            for key in _jsontext.keys():
                keyValue = _jsontext.get(key)
                if isinstance(keyValue, dict):
                    self.json2dict(keyValue)
                elif isinstance(keyValue, list):
                    for json_array in keyValue:
                        self.json2dict(json_array)
                else:
                    if type(keyValue) is int or type(keyValue) == long or type(
                            keyValue) == str:
                        self._result.append(str(key) + "=" + str(keyValue))
                    elif type(keyValue) is bool:
                        self._result.append(
                            str(key) + "=" + str(int(keyValue)))
                    elif type(keyValue) == type(None):
                        self._result.append(str(key) + "=" + "")
                    else:
                        self._result.append(str(key) + "=" + keyValue)
        elif isinstance(_jsontext, list):
            for _jsontext_array in _jsontext:
                self.json2dict(_jsontext_array)
        return self._result

    def getTabCaption(self):
        return "JSON&HTTPP"

    def getUiComponent(self):
        return self.mainPanel
Esempio n. 13
0
class BurpExtender(IBurpExtender, ITab, IHttpListener, IContextMenuFactory, IMessageEditorController, AbstractTableModel):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        print("[*] Loading Jaeles beta v0.1")
        # 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("Jaeles")

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        # logTable = Table(self)
        # scrollPane = JScrollPane(logTable)

        # _toppane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        _mainpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        _mainpane.setResizeWeight(0.5)
        # _mainpane = JPanel()

        _toppane = JPanel()

        # top pane
        self.banner = JLabel("Jaeles - The Swiss Army knife for automated Web Application Testing. ")
        self.banner.setBounds(50, 30, 200, 400)

        self.banner2 = JLabel("Official Documentation: https://jaeles-project.github.io/")
        self.banner2.setBounds(100, 50, 200, 400)
        _toppane.add(self.banner)
        _toppane.add(self.banner2)

        # _botpane = JPanel()
        _botpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # bot pane
        self.HostLabel = JLabel("Jaeles Endpoint: ")
        self.HostLabel.setBounds(100, 150, 200, 400)

        self.Jaeles_endpoint = 'http://127.0.0.1:5000/api/parse'
        self.jwt = 'Jaeles token_here'
        # just prevent plugin error when you doesn't have server running
        try:
            self.initial()
            jwt, endpoint = self.get_config()
            if endpoint:
                self.Jaeles_endpoint = endpoint        
            if jwt:
                self.jwt = jwt
        except:
            pass

        endpoint_pane = JPanel()

        # end point to submit request
        self.EndpointText = JTextArea(self.Jaeles_endpoint, 3, 100)

        self.jwtLabel = JLabel("Jaeles JWT token: ")
        self.jwtLabel.setBounds(100, 300, 250, 450)

        self.jwtText = JTextArea(self.jwt, 3, 100, lineWrap=True)

        buttons = JPanel()
        self.buttonLabel = JLabel("Actions: ")
        self.buttonLabel.setBounds(150, 200, 200, 400)
        self._saveButton = JButton("Save", actionPerformed=self.saveToken)
        self._loadButton = JButton(
            "Test Connection", actionPerformed=self.butClick)
        self._reloadButton = JButton("Reload", actionPerformed=self.butClick)

        oob_control = JPanel()
        self.oobLabel = JLabel("OOB: ")
        self.oobLabel.setBounds(150, 200, 200, 400)
        self._saveoob = JButton("Save OOB", actionPerformed=self.saveToken)
        self._pollingBox = JCheckBox("Polling")
        self._pollingBox.setBounds(290, 25, 300, 30)
        oob_control.add(self.oobLabel)
        oob_control.add(self._saveoob)
        oob_control.add(self._pollingBox)

        # _botpane.add(self.banner)
        # endpoint_pane.add(self.blankLabel)
        endpoint_pane.add(self.HostLabel)
        endpoint_pane.add(self.EndpointText)
        endpoint_pane.add(self.jwtLabel)
        endpoint_pane.add(self.jwtText)

        buttons.add(self.buttonLabel)
        buttons.add(self._saveButton)
        buttons.add(self._loadButton)
        buttons.add(self._reloadButton)

        _botpane.setLeftComponent(oob_control)
        _botpane.setLeftComponent(endpoint_pane)
        _botpane.setRightComponent(buttons)
        _botpane.setResizeWeight(0.7)

        # set
        _mainpane.setLeftComponent(_toppane)
        _mainpane.setRightComponent(_botpane)

        self._splitpane.setLeftComponent(_mainpane)

        ###########
        # tabs with request/response viewers
        tabs = JTabbedPane()

        self.log_area = JTextArea("", 5, 30)
        # self._requestViewer = callbacks.createMessageEditor(self, False)

        tabs.addTab("Log", self.log_area)
        # tabs.addTab("Config", self._requestViewer.getComponent())

        self._splitpane.setRightComponent(tabs)
        self._splitpane.setResizeWeight(0.5)

        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(tabs)

        callbacks.registerContextMenuFactory(self)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # register ourselves as an HTTP listener
        # callbacks.registerHttpListener(self)
        self.print_log("[*] Jaeles Loaded ...")
        return

    #
    # implement ITab
    #

    ##
    def saveToken(self, e):
        token = self.jwtText.getText().strip()
        endpoint = self.EndpointText.getText().strip()
        self.Jaeles_endpoint = endpoint
        self.jwt = token
        self.set_config(token, endpoint)

    def butClick(self, e):
        button_name = e.getActionCommand()

        if button_name == 'Reload':
            # self.initial()
            username, password = self.get_cred()
            self.login(username, password)
            jwt, endpoint = self.get_config()
            self.Jaeles_endpoint = endpoint
            self.jwt = jwt
            self.print_log("[+] Reload Config")

        elif button_name == 'Test Connection':
            connection = self.test_connection()
            if connection:
                self.print_log("[+] Ready to send request to {0}".format(self.Jaeles_endpoint))
            else:
                self.print_log("[-] Fail to authen with API server at {0}".format(self.Jaeles_endpoint))

    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages()
        if responses > 0:
            ret = LinkedList()
            requestMenuItem = JMenuItem("[*] Send request to Jaeles Endpoint")
            requestMenuItem.addActionListener(
                handleMenuItems(self, responses, "request"))
            ret.add(requestMenuItem)
            return ret
        return None

    def highlightTab(self):
        currentPane = self._splitpane
        previousPane = currentPane
        while currentPane and not isinstance(currentPane, JTabbedPane):
            previousPane = currentPane
            currentPane = currentPane.getParent()
        if currentPane:
            index = currentPane.indexOfComponent(previousPane)
            currentPane.setBackgroundAt(index, Color(0xff6633))

            class setColorBackActionListener(ActionListener):
                def actionPerformed(self, e):
                    currentPane.setBackgroundAt(index, Color.BLACK)

            timer = Timer(5000, setColorBackActionListener())
            timer.setRepeats(False)
            timer.start()

    def getTabCaption(self):
        return "Jaeles"

    def getUiComponent(self):
        return self._splitpane

    #
    # implement Polling Collaborator
    # this allows our request/response viewers to obtain details about the messages being displayed
    #
    # def jaeles_collab(self, collab):
    #     oob = collab.generatePayload(True)

    #     # oob2 = collab.generatePayload(True)
    #     # print(oob2)
    #     self.print_log("[+] Gen oob host: {0}".format(oob))
    #     # print(oob)
    #     # os.system('curl {0}'.format(oob))

    #
    # implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #
    def sendRequestToJaeles(self, messageInfos):
        for messageInfo in messageInfos:
            data_json = self.req_parsing(messageInfo)

            if data_json:
                self.print_log("Import to external Jaeles ...")
                self.import_to_Jaeles(data_json)
            else:
                self.print_log("No response on selected request")
            self.print_log("-"*30)

    # start of my function
    def req_parsing(self, messageInfo):
        data_json = {}
        data_json['req_scheme'] = str(messageInfo.getProtocol())  # return http
        data_json['req_host'] = str(messageInfo.getHost())
        data_json['req_port'] = str(messageInfo.getPort())
        data_json['url'] = str(messageInfo.getUrl())

        # full request
        full_req = self._helpers.bytesToString(messageInfo.getRequest())
        data_json['req'] = self.just_base64(str(full_req))

        if messageInfo.getResponse():
            full_res = self._helpers.bytesToString(messageInfo.getResponse())
        else:
            full_res = None
        if not full_res:
            data_json['res'] = ""
            return data_json

        data_json['res'] = self.just_base64(str(full_res.encode('utf-8')))
        return data_json

    # send data to Jaeles API Endpoint
    def import_to_Jaeles(self, data_json):
        req = urllib2.Request(self.Jaeles_endpoint)
        req.add_header('Content-Type', 'application/json')
        req.add_header('Authorization', self.jwt)
        response = urllib2.urlopen(req, json.dumps(data_json))
        if str(response.code) == "200":
            self.print_log("[+] Start scan {0}".format(data_json['url']))
        else:
            self.print_log("[-] Fail Send request to {0}".format(self.Jaeles_endpoint))

    # check if token is available or not
    def initial(self):
        connection = self.test_connection()
        if connection:
            return True
        username, password = self.get_cred()
        valid_cred = self.login(username, password)
        if valid_cred:
            return True
        return False

    # do login
    def login(self, username, password):
        req = urllib2.Request(self.Jaeles_endpoint.replace("/api/parse","/auth/login"))
        req.add_header('Content-Type', 'application/json')
        response = urllib2.urlopen(req, json.dumps({"username": username, "password": password}))

        if str(response.code) == "200":
            data = json.loads(response.read())
            token = "Jaeles " + data.get("token")
            self.set_config(token, self.Jaeles_endpoint, username, password)
            print("[+] Authentication success on {0}".format(self.Jaeles_endpoint))
            return True
        else:
            print("[-] Can't authen on {0}".format(self.Jaeles_endpoint))
            return False

    # check connection
    def test_connection(self):
        req = urllib2.Request(self.Jaeles_endpoint.replace("/parse", "/ping"))
        req.add_header('Content-Type', 'application/json')
        req.add_header('Authorization', self.jwt)
        try:
            response = urllib2.urlopen(req)
            if str(response.code) == "200":
                return True
        except:
            pass
        return False

    # get default credentials
    def get_cred(self):
        config_path = self.get_config_path()
        if os.path.isfile(config_path):
            with open(config_path, 'r') as f:
                data = json.load(f)
            print('[+] Load credentials from {0}'.format(config_path))
            return data.get('username', False), data.get('password', False)
        else:
            print('[-] No config file to load.')
            return False, False

    # get token and endpoint
    def get_config(self):
        config_path = self.get_config_path()
        if os.path.isfile(config_path):
            with open(config_path, 'r') as f:
                data = json.load(f)
            print('[+] Load JWT from {0}'.format(config_path))
            return data.get('JWT', False), data.get('endpoint', False)
        else:
            print('[-] No config file to load.')
            return False, False

    # save jwt token and endpoint to ~/.jaeles/burp.json
    def set_config(self, token, endpoint, username='', password=''):
        data = {
            'JWT': token,
            'endpoint': endpoint,
            'username': username,
            'password': password,
        }
        config_path = self.get_config_path()
        jaeles_path = os.path.dirname(config_path)

        if jaeles_path and not os.path.exists(jaeles_path):
            os.makedirs(jaeles_path)
        with open(config_path, 'w+') as f:
            json.dump(data, f)

        print('[+] Store JWT in {0}'.format(config_path))
        return True

    def just_base64(self, text):
        if not text:
            return ""
        return str(base64.b64encode(str(text)))

    def get_config_path(self):
        home = os.path.expanduser('~{0}'.format(getpass.getuser()))
        jaeles_path = os.path.join(home, '.jaeles')

        config_path = os.path.join(jaeles_path, 'burp.json')
        return config_path

    def print_log(self, text):
        if type(text) != str:
            text = str(text)
        self.log_area.append(text)
        self.log_area.append("\n")

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()
Esempio n. 14
0
    def __init__(self, parent, title, modal, app):
        from javax.swing import JTextArea

        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        #Icon
        icon = ImageIcon(File.separator.join([app.SCRIPTDIR,
                                              "images",
                                              "icons",
                                              "logo.png"]))
        iconLbl = JLabel(icon)
        iconLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT)

        #Name
        titleLbl = JLabel("Quality Assurance Tools script")
        titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT)

        #Version
        p = JPanel()
        versionPanel = JPanel(GridLayout(2, 2))
        versionPanel.add(JLabel("script: "))
        versionPanel.add(JLabel(app.SCRIPTVERSION))
        versionPanel.add(JLabel("tools: "))
        self.toolsVersionLbl = JLabel(app.TOOLSVERSION)
        versionPanel.add(self.toolsVersionLbl)
        versionPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        p.add(versionPanel)

        #Wiki
        wikiLblPanel = JPanel(FlowLayout(FlowLayout.CENTER))
        wikiLbl = UrlLabel(app.SCRIPTWEBSITE, "Wiki", 2)
        wikiLblPanel.add(wikiLbl)
        wikiLblPanel.setAlignmentX(JLabel.CENTER_ALIGNMENT)

        #Author, contributors and credits
        creditsTextArea = JTextArea(15, 35, editable=False)
        creditsTextArea.setBackground(None)
        contribFile = open(File.separator.join([app.SCRIPTDIR, "CONTRIBUTORS"]), "r")
        contribText = contribFile.read()
        contribFile.close()
        creditsTextArea.append(contribText)
        creditsTextArea.setCaretPosition(0)
        creditScrollPane = JScrollPane(creditsTextArea)

        #OK button
        okBtn = JButton("OK",
                        ImageProvider.get("ok"),
                        actionPerformed=self.on_okBtn_clicked)
        okBtn.setAlignmentX(JButton.CENTER_ALIGNMENT)

        #Layout
        self.add(Box.createRigidArea(Dimension(0, 7)))
        self.add(iconLbl)
        self.add(Box.createRigidArea(Dimension(0, 7)))
        self.add(titleLbl)
        self.add(Box.createRigidArea(Dimension(0, 7)))
        self.add(p)
        self.add(wikiLblPanel)
        self.add(Box.createRigidArea(Dimension(0, 7)))
        self.add(creditScrollPane)
        self.add(Box.createRigidArea(Dimension(0, 7)))
        self.add(okBtn)

        self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.pack()
class JythonGui(object):
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)
        return

    def log_msg(self, msg):
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg("Selected '%s' as output." % self.selected_output_file.path)

    def runSASIGridder(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            try:
                input_dir = self.selected_input_file.path
                output_path = self.selected_output_file.path

                grid_path = os.path.join(input_dir, "grid", "grid.shp")

                stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp")

                raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv")

                gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv")

                gear_mappings = {}
                with open(gear_mappings_path, "rb") as f:
                    r = csv.DictReader(f)
                    for mapping in r:
                        gear_mappings[mapping["trip_type"]] = mapping["gear_code"]

                task = SASIGridderTask(
                    grid_path=grid_path,
                    raw_efforts_path=raw_efforts_path,
                    stat_areas_path=stat_areas_path,
                    output_path=output_path,
                    logger=self.logger,
                    gear_mappings=gear_mappings,
                    effort_limit=None,
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
class JythonGui(ItemListener):
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)

    def itemStateChanged(self, event):
        """ Listen for checkbox changes. """
        checkBox = event.getItemSelectable()
        is_selected = (event.getStateChange() == ItemEvent.SELECTED)
        result_field = self.resultFieldCheckBoxes[checkBox]
        self.selected_result_fields[result_field['id']] = is_selected

    def log_msg(self, msg):
        """ Print message to log and scroll to bottom. """
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            selectedPath = self.outputChooser.selectedFile.path
            if not selectedPath.endswith('.zip'):
                zipPath = selectedPath + '.zip'
                self.outputChooser.setSelectedFile(File(zipPath))
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg(
                "Selected '%s' as output." % self.selected_output_file.path)

    def runSASI(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():
            self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.")
            self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db")

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            def get_connection():
                engine = create_engine('h2+zxjdbc:////%s' % self.db_file)
                con = engine.connect()
                return con

            try:
                # Set result fields.
                result_fields = []
                for field_id, is_selected in self.selected_result_fields.items():
                    if is_selected: result_fields.append(field_id)

                task = RunSasiTask(
                    input_path=self.selected_input_file.path,
                    output_file=self.selected_output_file.path,
                    logger=self.logger,
                    get_connection=get_connection,
                    config={
                        'result_fields': result_fields,
                        'run_model': {
                            'run': {
                                'batch_size': 'auto',
                            }
                        },
                        'output': {
                            'batch_size': 'auto',
                        },
                    }
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

            try:
                shutil.rmtree(self.tmp_dir)
            except:
                pass

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
Esempio n. 17
0
class GroupConversationWindow(GroupConversation):
    """A GUI window of a conversation witha  group of people"""
    def __init__(self, group, chatui):
        GroupConversation.__init__(self, group, chatui)
        self.mainframe = JFrame(self.group.name)
        self.headers = ["Member"]
        self.memberdata = UneditableTableModel([], self.headers)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def showGroupMessage(self, sender, text, metadata=None):
        self.displayText(sender + ": " + text)

    def setGroupMembers(self, members):
        GroupConversation.setGroupMembers(self, members)
        self.updatelist()

    def setTopic(self, topic, author):
        topictext = "Topic: " + topic + ", set by " + author
        self.mainframe.setTitle(self.group.name + ": " + topictext)
        self.displayText(topictext)

    def memberJoined(self, member):
        GroupConversation.memberJoined(self, member)
        self.updatelist()

    def memberChangedNick(self, oldnick, newnick):
        GroupConversation.memberChangedNick(self, oldnick, newnick)
        self.updatelist()

    def memberLeft(self, member):
        GroupConversation.memberLeft(self, member)
        self.updatelist()

    #GUI code
    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        memberpane = JTable(self.memberdata)
        memberframe = JScrollPane(memberpane)

        chat = JPanel(doublebuffered)
        chat.setLayout(BoxLayout(chat, BoxLayout.Y_AXIS))
        chat.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        chat.add(self.typepad)
        chat.add(buttons)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.X_AXIS))
        mainpane.add(chat)
        mainpane.add(memberframe)

    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    def updatelist(self):
        self.memberdata.setDataVector([self.members], self.headers)

    #actionListener
    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            GroupConversation.sendText(self, text)

    def hidewindow(self, ae):
        self.hide()
Esempio n. 18
0
class tag(ITab):
    def __init__(self, callbacks, name):
        self._callbacks = callbacks
        self.name = name

    def getTabCaption(self):
        return self.name

    def getUiComponent(self):
        return self.tabs

    def setFontItalic(self, label):
        label.setFont(
            Font(label.getFont().getName(), Font.ITALIC,
                 label.getFont().getSize()))

    def setFontBold(self, label):
        label.setFont(Font('Serif', Font.BOLD, label.getFont().getSize()))

    # 配置界面添加
    def tagLoad(self):
        # 创建窗口 开始
        self.tabs = JTabbedPane()

        self.settings = JPanel(GridBagLayout())
        self.forward_requests_settings = JPanel(GridBagLayout())
        self.white_list_domain_settings = JPanel(GridBagLayout())
        self.white_list_http_method_settings = JPanel(GridBagLayout())

        c = GridBagConstraints()

        # 界面选项卡1-标签加载
        self.tag_1_1(c)
        self.tag_1_2(c)

        # 界面选项卡2-标签加载
        self.tag_2_1(c)
        self.tag_2_2(c)

        # 界面选项卡3-标签加载
        self.tag_3_1(c)

        # 界面选项卡4-标签加载
        self.tag_4_1(c)
        self.tag_4_2(c)
        self.tag_4_3(c)
        self.tag_4_4(c)
        self.tag_4_5(c)
        self.tag_4_6(c)
        self.tag_4_7(c)
        self.tag_4_8(c)
        self.tag_4_9(c)
        self.tag_4_10(c)
        self.tag_4_11(c)
        self.tag_4_12(c)
        self.tag_4_13(c)
        self.tag_4_14(c)
        self.tag_4_15(c)

        # 添加选项卡
        self.tabs.addTab(u'基本设置', self.settings)
        self.tabs.addTab(u'http请求转发设置', self.forward_requests_settings)
        self.tabs.addTab(u'白名单域名设置', self.white_list_domain_settings)
        self.tabs.addTab(u'白名单http方法设置', self.white_list_http_method_settings)

        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.addSuiteTab(self)

    # 选项卡1-标签1-ui
    def tag_1_1(self, c):
        # 创建 检查框
        self.is_start_box = JCheckBox(u'是否启动插件',
                                      ForwardRequestsConfig.IS_START)
        self.setFontBold(self.is_start_box)
        self.is_start_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.is_start_box, c)

        # 在窗口添加一句话
        is_start_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_start_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(is_start_box_lbl, c)

    # 选项卡1-标签1-值
    def isStartBox(self):
        return self.is_start_box.isSelected()

    # 选项卡1-标签2-ui
    def tag_1_2(self, c):
        # 创建 检查框
        self.url_repeated_box = JCheckBox(
            u'是否启动url重复验证', ForwardRequestsConfig.URL_REPEATED_VERIFY)
        self.setFontBold(self.url_repeated_box)
        self.url_repeated_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(self.url_repeated_box, c)

        # 在窗口添加一句话
        url_repeated_box_lbl = JLabel(u'打勾-开启验证, 不打勾-关闭验证')
        self.setFontItalic(url_repeated_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.settings.add(url_repeated_box_lbl, c)

    # 选项卡1-标签2-值
    def urlRepeatedBox(self):
        return self.url_repeated_box.isSelected()

    # 选项卡2-标签1-ui
    def tag_2_1(self, c):
        # 创建 检查框
        self.is_proxy_forward_requests_box = JCheckBox(
            u'是否启动Proxy模块请求转发(推荐打勾)',
            ForwardRequestsConfig.IS_START_PROXY_FORWARD_REQUESTS)
        self.setFontBold(self.is_proxy_forward_requests_box)
        self.is_proxy_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.forward_requests_settings.add(self.is_proxy_forward_requests_box,
                                           c)

        # 在窗口添加一句话
        is_proxy_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_proxy_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.forward_requests_settings.add(is_proxy_forward_requests_box_lbl,
                                           c)

    # 选项卡2-标签2-ui
    def tag_2_2(self, c):
        # 创建 检查框
        self.is_repeater_forward_requests_box = JCheckBox(
            u'是否启动Repeater模块请求转发',
            ForwardRequestsConfig.IS_START_REPEATER_FORWARD_REQUESTS)
        self.setFontBold(self.is_repeater_forward_requests_box)
        self.is_repeater_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.forward_requests_settings.add(
            self.is_repeater_forward_requests_box, c)

        # 在窗口添加一句话
        is_repeater_forward_requests_box_lbl = JLabel(u'打勾-启动, 不打勾-关闭')
        self.setFontItalic(is_repeater_forward_requests_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.forward_requests_settings.add(
            is_repeater_forward_requests_box_lbl, c)

    # 获取允许转发的burp模块列表
    def getWhiteListModule(self):
        white_list_module = []

        if self.is_proxy_forward_requests_box.isSelected():
            white_list_module.append(4)
        if self.is_repeater_forward_requests_box.isSelected():
            white_list_module.append(64)

        return white_list_module

    # 选项卡3-标签1-ui
    def tag_3_1(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

        # 输入框
        self.white_list_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.white_list_domain_settings.add(self.white_list_text_field, c)

        lblParamsNote = JLabel(u"白名单域名列表")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.white_list_domain_settings.add(lblParamsNote, c)

        # 添加 文本框
        self.white_list_text_area = JTextArea()
        self.white_list_text_area.setColumns(20)
        self.white_list_text_area.setRows(10)
        self.white_list_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.white_list_mouse_listener = TextAreaMouseListener(
            self.white_list_text_area)
        self.white_list_text_area.addMouseListener(
            self.white_list_mouse_listener)

        # 向文本框添加数据
        for name in white_list_names:
            self.white_list_text_area.append(name + '\n' + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.white_list_text_area)
        self.white_list_domain_settings.add(sp, c)

        # 添加 删除 重置
        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.white_list_text_field,
                                  self.white_list_text_area,
                                  self.white_list_mouse_listener,
                                  white_list_names)

        # 添加按钮
        self.white_list_add_button = JButton(
            u'添加', actionPerformed=handlers.handler_add)
        _c.gridy = 1
        buttonsPanel.add(self.white_list_add_button, _c)

        # 删除按钮
        self.white_list_rm_button = JButton(
            u'删除', actionPerformed=handlers.handler_rm)
        _c.gridy = 2
        buttonsPanel.add(self.white_list_rm_button, _c)

        # 重置按钮
        self.white_list_restore_button = JButton(
            u'重置', actionPerformed=handlers.handler_restore)
        _c.gridy = 3
        buttonsPanel.add(self.white_list_restore_button, _c)

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.white_list_domain_settings.add(buttonsPanel, c)

    # 获取白名单域名列表
    def getWhiteList(self):
        return self.text_area_to_list(self.white_list_text_area)

    # 获取指定text数据
    def text_area_to_list(self, text_area):
        l = []
        text_list = text_area.getText().strip().split('\n')
        for data in text_list:
            if data == '':
                continue
            data = data.replace("\n", '')
            data = data.replace("\r", '')
            data = data.strip(' ')
            l.append(data)
        return l

    # 选项卡4-标签1-ui
    def tag_4_1(self, c):
        # 创建 检查框
        self.is_get_forward_requests_box = JCheckBox(
            u'转发GET请求', ForwardRequestsConfig.IS_GET_FORWARD_REQUESTS)
        self.setFontBold(self.is_get_forward_requests_box)
        self.is_get_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.white_list_http_method_settings.add(
            self.is_get_forward_requests_box, c)

    # 选项卡4-标签2-ui
    def tag_4_2(self, c):
        # 创建 检查框
        self.is_post_forward_requests_box = JCheckBox(
            u'转发POST请求', ForwardRequestsConfig.IS_POST_FORWARD_REQUESTS)
        self.setFontBold(self.is_post_forward_requests_box)
        self.is_post_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.white_list_http_method_settings.add(
            self.is_post_forward_requests_box, c)

    # 选项卡4-标签3-ui
    def tag_4_3(self, c):
        # 创建 检查框
        self.is_put_forward_requests_box = JCheckBox(
            u'转发PUT请求', ForwardRequestsConfig.IS_PUT_FORWARD_REQUESTS)
        self.setFontBold(self.is_put_forward_requests_box)
        self.is_put_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.white_list_http_method_settings.add(
            self.is_put_forward_requests_box, c)

    # 选项卡4-标签4-ui
    def tag_4_4(self, c):
        # 创建 检查框
        self.is_patch_forward_requests_box = JCheckBox(
            u'转发PATCH请求', ForwardRequestsConfig.IS_PATCH_FORWARD_REQUESTS)
        self.setFontBold(self.is_patch_forward_requests_box)
        self.is_patch_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 4
        self.white_list_http_method_settings.add(
            self.is_patch_forward_requests_box, c)

    # 选项卡4-标签5-ui
    def tag_4_5(self, c):
        # 创建 检查框
        self.is_delete_forward_requests_box = JCheckBox(
            u'转发DELETE请求', ForwardRequestsConfig.IS_DELETE_FORWARD_REQUESTS)
        self.setFontBold(self.is_delete_forward_requests_box)
        self.is_delete_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 5
        self.white_list_http_method_settings.add(
            self.is_delete_forward_requests_box, c)

    # 选项卡4-标签6-ui
    def tag_4_6(self, c):
        # 创建 检查框
        self.is_copy_forward_requests_box = JCheckBox(
            u'转发COPY请求', ForwardRequestsConfig.IS_COPY_FORWARD_REQUESTS)
        self.setFontBold(self.is_copy_forward_requests_box)
        self.is_copy_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 6
        self.white_list_http_method_settings.add(
            self.is_copy_forward_requests_box, c)

    # 选项卡4-标签7-ui
    def tag_4_7(self, c):
        # 创建 检查框
        self.is_head_forward_requests_box = JCheckBox(
            u'转发HEAD请求', ForwardRequestsConfig.IS_HEAD_FORWARD_REQUESTS)
        self.setFontBold(self.is_head_forward_requests_box)
        self.is_head_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 7
        self.white_list_http_method_settings.add(
            self.is_head_forward_requests_box, c)

    # 选项卡4-标签8-ui
    def tag_4_8(self, c):
        # 创建 检查框
        self.is_options_forward_requests_box = JCheckBox(
            u'转发OPTIONS请求', ForwardRequestsConfig.IS_OPTIONS_FORWARD_REQUESTS)
        self.setFontBold(self.is_options_forward_requests_box)
        self.is_options_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 8
        self.white_list_http_method_settings.add(
            self.is_options_forward_requests_box, c)

    # 选项卡4-标签9-ui
    def tag_4_9(self, c):
        # 创建 检查框
        self.is_link_forward_requests_box = JCheckBox(
            u'转发LINK请求', ForwardRequestsConfig.IS_LINK_FORWARD_REQUESTS)
        self.setFontBold(self.is_link_forward_requests_box)
        self.is_link_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 9
        self.white_list_http_method_settings.add(
            self.is_link_forward_requests_box, c)

    # 选项卡4-标签10-ui
    def tag_4_10(self, c):
        # 创建 检查框
        self.is_unlink_forward_requests_box = JCheckBox(
            u'转发UNLINK请求', ForwardRequestsConfig.IS_UNLINK_FORWARD_REQUESTS)
        self.setFontBold(self.is_unlink_forward_requests_box)
        self.is_unlink_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 10
        self.white_list_http_method_settings.add(
            self.is_unlink_forward_requests_box, c)

    # 选项卡4-标签11-ui
    def tag_4_11(self, c):
        # 创建 检查框
        self.is_purge_forward_requests_box = JCheckBox(
            u'转发PURGE请求', ForwardRequestsConfig.IS_PURGE_FORWARD_REQUESTS)
        self.setFontBold(self.is_purge_forward_requests_box)
        self.is_purge_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 11
        self.white_list_http_method_settings.add(
            self.is_purge_forward_requests_box, c)

    # 选项卡4-标签12-ui
    def tag_4_12(self, c):
        # 创建 检查框
        self.is_lock_forward_requests_box = JCheckBox(
            u'转发LOCK请求', ForwardRequestsConfig.IS_LOCK_FORWARD_REQUESTS)
        self.setFontBold(self.is_lock_forward_requests_box)
        self.is_lock_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 12
        self.white_list_http_method_settings.add(
            self.is_lock_forward_requests_box, c)

    # 选项卡4-标签13-ui
    def tag_4_13(self, c):
        # 创建 检查框
        self.is_unlock_forward_requests_box = JCheckBox(
            u'转发UNLOCK请求', ForwardRequestsConfig.IS_UNLOCK_FORWARD_REQUESTS)
        self.setFontBold(self.is_unlock_forward_requests_box)
        self.is_unlock_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 13
        self.white_list_http_method_settings.add(
            self.is_unlock_forward_requests_box, c)

    # 选项卡4-标签14-ui
    def tag_4_14(self, c):
        # 创建 检查框
        self.is_propfind_forward_requests_box = JCheckBox(
            u'转发PROPFIND请求',
            ForwardRequestsConfig.IS_PROPFIND_FORWARD_REQUESTS)
        self.setFontBold(self.is_propfind_forward_requests_box)
        self.is_propfind_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 14
        self.white_list_http_method_settings.add(
            self.is_propfind_forward_requests_box, c)

    # 选项卡4-标签15-ui
    def tag_4_15(self, c):
        # 创建 检查框
        self.is_view_forward_requests_box = JCheckBox(
            u'转发VIEW请求', ForwardRequestsConfig.IS_VIEW_FORWARD_REQUESTS)
        self.setFontBold(self.is_view_forward_requests_box)
        self.is_view_forward_requests_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 15
        self.white_list_http_method_settings.add(
            self.is_view_forward_requests_box, c)

    # 获取白名单http方法
    def getWhiteListHttpMethod(self):
        l = []
        if self.is_get_forward_requests_box.isSelected():
            l.append('GET')
        if self.is_post_forward_requests_box.isSelected():
            l.append('POST')
        if self.is_put_forward_requests_box.isSelected():
            l.append('PUT')
        if self.is_patch_forward_requests_box.isSelected():
            l.append('PATCH')
        if self.is_delete_forward_requests_box.isSelected():
            l.append('DELETE')
        if self.is_copy_forward_requests_box.isSelected():
            l.append('COPY')
        if self.is_head_forward_requests_box.isSelected():
            l.append('HEAD')
        if self.is_options_forward_requests_box.isSelected():
            l.append('OPTIONS')
        if self.is_link_forward_requests_box.isSelected():
            l.append('LINK')
        if self.is_unlink_forward_requests_box.isSelected():
            l.append('UNLINK')
        if self.is_purge_forward_requests_box.isSelected():
            l.append('PURGE')
        if self.is_lock_forward_requests_box.isSelected():
            l.append('LOCK')
        if self.is_unlock_forward_requests_box.isSelected():
            l.append('UNLOCK')
        if self.is_propfind_forward_requests_box.isSelected():
            l.append('PROPFIND')
        if self.is_view_forward_requests_box.isSelected():
            l.append('VIEW')
        return l
Esempio n. 19
0
class JTabbedPaneClass:


    #判断域名返回IP地址
    def getIp(self, domain):
        domain = domain.split(":")[0]
        ipExpression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")
        if ipExpression.match(domain):
            return domain
        elif domainExpression.match(domain):
            myAddr = socket.getaddrinfo(domain,'http')[0][4][0]
            return myAddr
        
        else:
            return "domain error"


    #提取域名或IP信息
    def getDomain1(self, theDomain):
        domain1 = theDomain.split(":")[0]

        return domain1



    def __init__(self):
        

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None);
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"  

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed = self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)                  #激活自动换行功能 
        self.textArea.setWrapStyleWord(True);            # 激活断行不断字功能
                   
        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))            #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)
        



        #第二个Tab用来做子域名查询



        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)                  #激活自动换行功能 
        self.textArea2.setWrapStyleWord(True)           # 激活断行不断字功能
                   


        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed = self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)


        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url','http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
##
 
        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)                  #激活自动换行功能 
        self.textArea3.setWrapStyleWord(True)          # 激活断行不断字功能
        a = 0
        b = 0 
        self.label4 = JLabel(str(a) + "/" + str(b))
#
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed = self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))


#
        tabPane.addTab("Sebsitive File", panel3)
#
        frame.add(tabPane)
        frame.setVisible(True)
    #用来在第一个TAB打印nmap信息  
    def setResult(self,text):
        self.textArea.append(text)

    #用来在第二个TAB打印获得信息
    def setResult2(self,textId, textDomain, textIp):
        text = str(textId) + "----------------" + textDomain + "----------------" + str(textIp) + os.linesep
        self.textArea2.append(text)
        #self.textArea2.append("----------------------------------------" + os.linesep)

    #用来在第三个TAB打印文件扫描的结果
    def setResult3(self, theMess01):

    	self.textArea3.append(theMess01)


    def setLabel(self, a, b):
    	hg = str(a) + "/" + str(b)
    	self.label4.setText(hg)


    #C段扫描的主引擎
    def cNmapScan(self, event):

        self.textArea.setText("")
            #-------------------------------------------------------------------------------
        def ipRange(ipaddr):
            """
            Creates a generator that iterates through all of the IP addresses.
            The range can be specified in multiple formats.
        
                "192.168.1.0-192.168.1.255"    : beginning-end
                "192.168.1.0/24"               : CIDR
                "192.168.1.*"                  : wildcard
            
        
            """
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
               
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message 
                q = ipaddr.split('.')
                return reduce(lambda a,b: long(a)*256 + long(b), q)
           
            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))
            
            #-------------------------------------------------------------------------------
            def cidr_iprange(ipaddr, cidrmask):
                """
                Creates a generator that iterated through all of the IP addresses
                in a range given in CIDR notation
                """
                # Get all the binary one's
                mask = (long(2)**long(32-long(cidrmask))) - 1
            
                b = ipaddr_to_binary(ipaddr) 
                e = ipaddr_to_binary(ipaddr) 
                b = long(b & ~mask)
                e = long(e | mask)
            
                while (b <= e):
                    yield binary_to_ipaddr(b)
                    b = b + 1
         
            #-------------------------------------------------------------------------------
            def wildcard_iprange(ipaddr):
                """
                Creates a generator that iterates through all of the IP address
                in a range given with wild card notation
                """
                beginning = [] 
                end = [] 
                
                tmp = ipaddr.split('.')
                for i in tmp:
                    if i == '*':
                        beginning.append("0")
                        end.append("255") 
                    else:
                        beginning.append(i)
                        end.append(i) 
            
                b = beginning[:]
                e = end[:]
                
                while int(b[0]) <= int(e[0]):
                    while int(b[1]) <= int(e[1]):
                        while int(b[2]) <= int(e[2]):
                            while int(b[3]) <= int(e[3]):
                                yield b[0] + '.' + b[1] + '.' + b[2] + '.' + b[3]
                                b[3] = "%d" % (int(b[3]) + 1)
            
                            b[2] = "%d" % (int(b[2]) + 1)
                            b[3] = beginning[3]
            
                        b[1] = "%d" % (int(b[1]) + 1)
                        b[2] = beginning[2]
            
                    b[0] = "%d" % (int(b[0]) + 1)
                    b[1] = beginning[1]       
            
            # Did we get the IP address in the span format? 
            span_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The beginning IP Address
                                     \s*-\s*
                                     (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The end IP Address
                                  ''', re.VERBOSE)
        
            res = span_re.match(ipaddr)
            if res:
                beginning = res.group(1)
                end = res.group(2)
                return span_iprange(beginning, end)
                                         
            # Did we get the IP address in the CIDR format? 
            cidr_re = re.compile(r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The IP Address
                                     /(\d{1,2})                             # The mask
                                  ''', re.VERBOSE)
        
            res = cidr_re.match(ipaddr)
            if res:
                addr = res.group(1)
                cidrmask = res.group(2)
                return cidr_iprange(addr, cidrmask)
        
            # Did we get the IP address in the wildcard format? 
            wild_re = re.compile(r'''(\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)   # The IP Address
                                  ''', re.VERBOSE)
        
            res = wild_re.match(ipaddr)
            if res:
                return wildcard_iprange(ipaddr)
            return "The ip address given to ipaddr is improperly formatted"


        ipCidr = self.textfield1.getText()

        domainExpression = re.compile("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")

        if domainExpression.match(ipCidr):
            JOptionPane.showMessageDialog(None, "You must enter IP", "s1riu5", JOptionPane.INFORMATION_MESSAGE)
        

        else:
            ipList = list(ipRange(ipCidr))
            print len(ipList)
            if len(ipList) == 256:
                del ipList[0]
                del ipList[254]
    
            global NMAPPATH

            scan=ScanList(ipList, self, [NMAPPATH,"-Pn", "-sT", "-sV", "--open"])
            scan.start()

    
  

    def subDomain(self, event):
    	print self.textfield2.getText()
        b = subDomainThread(self.textfield2.getText(), self)
        b.start()

        


    def senFileScan(self, event):
        #print "Hello"

        urlListASP = ["/admin.asp"]
        urlListASPX = ["/admin.aspx"]
        urlListJSP = ["/admin.jsp"]
        urlListPHP = ["/admin.php"]
        urlListMDB = ["/admin.mdb"]
        urlListDIR = ["/admin/"]
        

        if self.chkbox1.isSelected():
            
            domainTextObj1 = open("path/ASP.txt", "r")
            for each1 in domainTextObj1.readlines():
                each1 = each1.strip()
                urlListASP.append(each1)
            domainTextObj1.close()

        if self.chkbox2.isSelected():
            domainTextObj2 = open("path/ASPX.txt", "r")
            for each2 in domainTextObj2.readlines():
                each2 = each2.strip()
                urlListASPX.append(each2)
            domainTextObj2.close()
            
        if self.chkbox3.isSelected():
            domainTextObj3 = open("path/JSP.txt", "r")
            for each3 in domainTextObj3.readlines():
                each3 = each3.strip()
                urlListJSP.append(each3)
            domainTextObj3.close()
        if self.chkbox4.isSelected():
            domainTextObj4 = open("path/PHP.txt", "r")
            for each4 in domainTextObj4.readlines():
                each4 = each4.strip()
                urlListPHP.append(each4)
            domainTextObj4.close()
        if self.chkbox5.isSelected():
            domainTextObj5 = open("path/MDB.txt", "r")
            for each5 in domainTextObj5.readlines():
                each5 = each5.strip()
                urlListMDB.append(each5)
            domainTextObj5.close()
        if self.chkbox6.isSelected():
            domainTextObj6 = open("path/DIR.txt", "r")
            for each6 in domainTextObj6.readlines():
                each6 = each6.strip()
                urlListDIR.append(each6)
            domainTextObj6.close()

        app = []
        app = urlListASP + urlListASPX + urlListJSP + urlListPHP + urlListMDB + urlListDIR
        app1 = list(set(app))
        

        theUrlText = self.textfield3.getText()

        


        #if str(theUrlText[0 : 7]) == "http://":
         #   theUrlText = "http://" + theUrlText
        

        print len(app1)
        print len(app)


        #fileObj1 = eachFileScan(theUrlText, app)
        #fileObj1.start()
        ab = numControl(theUrlText, app1, self)
        ab.start()
Esempio n. 20
0
class JTabbedPaneClass:

    #判断域名返回IP地址
    def getIp(self, domain):
        domain = domain.split(":")[0]
        ipExpression = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
        domainExpression = re.compile(
            "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"
        )
        if ipExpression.match(domain):
            return domain
        elif domainExpression.match(domain):
            myAddr = socket.getaddrinfo(domain, 'http')[0][4][0]
            return myAddr

        else:
            return "domain error"

    #提取域名或IP信息
    def getDomain1(self, theDomain):
        domain1 = theDomain.split(":")[0]

        return domain1

    def __init__(self):

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None)
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed=self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)  #激活自动换行功能
        self.textArea.setWrapStyleWord(True)
        # 激活断行不断字功能

        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))  #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)

        #第二个Tab用来做子域名查询

        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)  #激活自动换行功能
        self.textArea2.setWrapStyleWord(True)  # 激活断行不断字功能

        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed=self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)

        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url', 'http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
        ##

        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)  #激活自动换行功能
        self.textArea3.setWrapStyleWord(True)  # 激活断行不断字功能
        a = 0
        b = 0
        self.label4 = JLabel(str(a) + "/" + str(b))
        #
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed=self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))

        #
        tabPane.addTab("Sebsitive File", panel3)
        #
        frame.add(tabPane)
        frame.setVisible(True)

    #用来在第一个TAB打印nmap信息
    def setResult(self, text):
        self.textArea.append(text)

    #用来在第二个TAB打印获得信息
    def setResult2(self, textId, textDomain, textIp):
        text = str(
            textId
        ) + "----------------" + textDomain + "----------------" + str(
            textIp) + os.linesep
        self.textArea2.append(text)
        #self.textArea2.append("----------------------------------------" + os.linesep)

    #用来在第三个TAB打印文件扫描的结果
    def setResult3(self, theMess01):

        self.textArea3.append(theMess01)

    def setLabel(self, a, b):
        hg = str(a) + "/" + str(b)
        self.label4.setText(hg)

    #C段扫描的主引擎
    def cNmapScan(self, event):

        self.textArea.setText("")

        #-------------------------------------------------------------------------------
        def ipRange(ipaddr):
            """
            Creates a generator that iterates through all of the IP addresses.
            The range can be specified in multiple formats.
        
                "192.168.1.0-192.168.1.255"    : beginning-end
                "192.168.1.0/24"               : CIDR
                "192.168.1.*"                  : wildcard
            
        
            """
            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message
                q = ipaddr.split('.')
                return reduce(lambda a, b: long(a) * 256 + long(b), q)

            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))

            def ipaddr_to_binary(ipaddr):
                """
                A useful routine to convert a ipaddr string into a 32 bit long integer
                """
                # from Greg Jorgensens python mailing list message
                q = ipaddr.split('.')
                return reduce(lambda a, b: long(a) * 256 + long(b), q)

            #-------------------------------------------------------------------------------
            def binary_to_ipaddr(ipbinary):
                """
                Convert a 32-bit long integer into an ipaddr dotted-quad string
                """
                # This one is from Rikard Bosnjakovic
                return socket.inet_ntoa(struct.pack('!I', ipbinary))

            #-------------------------------------------------------------------------------
            def cidr_iprange(ipaddr, cidrmask):
                """
                Creates a generator that iterated through all of the IP addresses
                in a range given in CIDR notation
                """
                # Get all the binary one's
                mask = (long(2)**long(32 - long(cidrmask))) - 1

                b = ipaddr_to_binary(ipaddr)
                e = ipaddr_to_binary(ipaddr)
                b = long(b & ~mask)
                e = long(e | mask)

                while (b <= e):
                    yield binary_to_ipaddr(b)
                    b = b + 1

            #-------------------------------------------------------------------------------
            def wildcard_iprange(ipaddr):
                """
                Creates a generator that iterates through all of the IP address
                in a range given with wild card notation
                """
                beginning = []
                end = []

                tmp = ipaddr.split('.')
                for i in tmp:
                    if i == '*':
                        beginning.append("0")
                        end.append("255")
                    else:
                        beginning.append(i)
                        end.append(i)

                b = beginning[:]
                e = end[:]

                while int(b[0]) <= int(e[0]):
                    while int(b[1]) <= int(e[1]):
                        while int(b[2]) <= int(e[2]):
                            while int(b[3]) <= int(e[3]):
                                yield b[0] + '.' + b[1] + '.' + b[2] + '.' + b[
                                    3]
                                b[3] = "%d" % (int(b[3]) + 1)

                            b[2] = "%d" % (int(b[2]) + 1)
                            b[3] = beginning[3]

                        b[1] = "%d" % (int(b[1]) + 1)
                        b[2] = beginning[2]

                    b[0] = "%d" % (int(b[0]) + 1)
                    b[1] = beginning[1]

            # Did we get the IP address in the span format?
            span_re = re.compile(
                r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The beginning IP Address
                                     \s*-\s*
                                     (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The end IP Address
                                  ''', re.VERBOSE)

            res = span_re.match(ipaddr)
            if res:
                beginning = res.group(1)
                end = res.group(2)
                return span_iprange(beginning, end)

            # Did we get the IP address in the CIDR format?
            cidr_re = re.compile(
                r'''(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   # The IP Address
                                     /(\d{1,2})                             # The mask
                                  ''', re.VERBOSE)

            res = cidr_re.match(ipaddr)
            if res:
                addr = res.group(1)
                cidrmask = res.group(2)
                return cidr_iprange(addr, cidrmask)

            # Did we get the IP address in the wildcard format?
            wild_re = re.compile(
                r'''(\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)\.
                                     (\d{1,3}|\*)   # The IP Address
                                  ''', re.VERBOSE)

            res = wild_re.match(ipaddr)
            if res:
                return wildcard_iprange(ipaddr)
            return "The ip address given to ipaddr is improperly formatted"

        ipCidr = self.textfield1.getText()

        domainExpression = re.compile(
            "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"
        )

        if domainExpression.match(ipCidr):
            JOptionPane.showMessageDialog(None, "You must enter IP", "s1riu5",
                                          JOptionPane.INFORMATION_MESSAGE)

        else:
            ipList = list(ipRange(ipCidr))
            print len(ipList)
            if len(ipList) == 256:
                del ipList[0]
                del ipList[254]

            global NMAPPATH

            scan = ScanList(ipList, self,
                            [NMAPPATH, "-Pn", "-sT", "-sV", "--open"])
            scan.start()

    def subDomain(self, event):
        print self.textfield2.getText()
        b = subDomainThread(self.textfield2.getText(), self)
        b.start()

    def senFileScan(self, event):
        #print "Hello"

        urlListASP = ["/admin.asp"]
        urlListASPX = ["/admin.aspx"]
        urlListJSP = ["/admin.jsp"]
        urlListPHP = ["/admin.php"]
        urlListMDB = ["/admin.mdb"]
        urlListDIR = ["/admin/"]

        if self.chkbox1.isSelected():

            domainTextObj1 = open("path/ASP.txt", "r")
            for each1 in domainTextObj1.readlines():
                each1 = each1.strip()
                urlListASP.append(each1)
            domainTextObj1.close()

        if self.chkbox2.isSelected():
            domainTextObj2 = open("path/ASPX.txt", "r")
            for each2 in domainTextObj2.readlines():
                each2 = each2.strip()
                urlListASPX.append(each2)
            domainTextObj2.close()

        if self.chkbox3.isSelected():
            domainTextObj3 = open("path/JSP.txt", "r")
            for each3 in domainTextObj3.readlines():
                each3 = each3.strip()
                urlListJSP.append(each3)
            domainTextObj3.close()
        if self.chkbox4.isSelected():
            domainTextObj4 = open("path/PHP.txt", "r")
            for each4 in domainTextObj4.readlines():
                each4 = each4.strip()
                urlListPHP.append(each4)
            domainTextObj4.close()
        if self.chkbox5.isSelected():
            domainTextObj5 = open("path/MDB.txt", "r")
            for each5 in domainTextObj5.readlines():
                each5 = each5.strip()
                urlListMDB.append(each5)
            domainTextObj5.close()
        if self.chkbox6.isSelected():
            domainTextObj6 = open("path/DIR.txt", "r")
            for each6 in domainTextObj6.readlines():
                each6 = each6.strip()
                urlListDIR.append(each6)
            domainTextObj6.close()

        app = []
        app = urlListASP + urlListASPX + urlListJSP + urlListPHP + urlListMDB + urlListDIR
        app1 = list(set(app))

        theUrlText = self.textfield3.getText()

        #if str(theUrlText[0 : 7]) == "http://":
        #   theUrlText = "http://" + theUrlText

        print len(app1)
        print len(app)

        #fileObj1 = eachFileScan(theUrlText, app)
        #fileObj1.start()
        ab = numControl(theUrlText, app1, self)
        ab.start()
Esempio n. 21
0
class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, ITab,
                   FocusListener, ActionListener, MouseAdapter):
    _version = "0.2"
    _name = "PyRules"
    _varsStorage = _name + "_vars"
    _scriptStorage = _name + "_script"

    _enabled = 0
    _vars = {}

    def registerExtenderCallbacks(self, callbacks):
        print "Load:" + self._name + " " + self._version

        self.callbacks = callbacks
        self.helpers = callbacks.helpers

        #Create Tab layout
        self.jVarsPane = JTextPane()
        self.jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jVarsPane.addFocusListener(self)

        self.jMenuPanel = JPanel()
        self.jLeftUpPanel = JPanel()

        self.jEnable = JCheckBox()
        self.jEnable.setFont(Font('Monospaced', Font.BOLD, 11))
        self.jEnable.setForeground(Color(0, 0, 204))
        self.jEnable.setText(self._name)
        self.jEnable.addActionListener(self)

        self.jDocs = JLabel()
        self.jDocs.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jDocs.setForeground(Color(51, 102, 255))
        self.jDocs.setText(Strings.docs_titel)
        self.jDocs.setToolTipText(Strings.docs_tooltip)
        self.jDocs.addMouseListener(self)

        self.jConsoleText = JTextArea()
        self.jConsoleText.setFont(Font('Monospaced', Font.PLAIN, 10))
        self.jConsoleText.setBackground(Color(244, 246, 247))
        self.jConsoleText.setEditable(0)
        self.jConsoleText.setWrapStyleWord(1)
        self.jConsoleText.setRows(10)
        self.jScrollConsolePane = JScrollPane()
        self.jScrollConsolePane.setViewportView(self.jConsoleText)
        #set initial text
        self.jConsoleText.setText(Strings.console_disable)

        self.jMenuPanelLayout = GroupLayout(self.jMenuPanel)
        self.jMenuPanel.setLayout(self.jMenuPanelLayout)
        self.jMenuPanelLayout.setHorizontalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addComponent(
                        self.jEnable).addPreferredGap(
                            LayoutStyle.ComponentPlacement.RELATED, 205,
                            32767).addComponent(self.jDocs)))

        self.jMenuPanelLayout.setVerticalGroup(
            self.jMenuPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    self.jMenuPanelLayout.createSequentialGroup().addGroup(
                        self.jMenuPanelLayout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).addComponent(
                                self.jEnable).addComponent(self.jDocs)).addGap(
                                    0, 7, 32767)))

        self.jConsolePane = JPanel()
        self.jConsoleLayout = GroupLayout(self.jConsolePane)
        self.jConsolePane.setLayout(self.jConsoleLayout)
        self.jConsoleLayout.setHorizontalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jScrollConsolePane))
        self.jConsoleLayout.setVerticalGroup(
            self.jConsoleLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addGroup(
                    GroupLayout.Alignment.TRAILING,
                    self.jConsoleLayout.createSequentialGroup().addComponent(
                        self.jScrollConsolePane, GroupLayout.DEFAULT_SIZE, 154,
                        32767).addContainerGap()))
        self.jLeftUpPanelLayout = GroupLayout(self.jLeftUpPanel)
        self.jLeftUpPanel.setLayout(self.jLeftUpPanelLayout)
        self.jLeftUpPanelLayout.setHorizontalGroup(
            self.jLeftUpPanelLayout.createParallelGroup(
                GroupLayout.Alignment.LEADING).addComponent(
                    self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    32767).addComponent(self.jMenuPanel,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE))
        self.jLeftUpPanelLayout.setVerticalGroup(
            self.jLeftUpPanelLayout.
            createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                GroupLayout.Alignment.TRAILING,
                self.jLeftUpPanelLayout.createSequentialGroup().addComponent(
                    self.jMenuPanel, GroupLayout.PREFERRED_SIZE,
                    GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE).addPreferredGap(
                        LayoutStyle.ComponentPlacement.RELATED).addComponent(
                            self.jConsolePane, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.DEFAULT_SIZE, 32767)))

        self.jScrollpaneLeftDown = JScrollPane()
        self.jScrollpaneLeftDown.setViewportView(self.jVarsPane)

        self.jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                         self.jLeftUpPanel,
                                         self.jScrollpaneLeftDown)
        self.jSplitPaneLeft.setDividerLocation(300)

        self.jScriptPane = JTextPane()
        self.jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11))
        self.jScriptPane.addMouseListener(self)

        self.JScrollPaneRight = JScrollPane()
        self.JScrollPaneRight.setViewportView(self.jScriptPane)

        self.jSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                     self.jSplitPaneLeft,
                                     self.JScrollPaneRight)
        self.jSplitPane.setDividerLocation(400)

        #Load saved saved settings
        ##Load vars
        vars = callbacks.loadExtensionSetting(self._varsStorage)
        if vars:
            vars = base64.b64decode(vars)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-vars.py") as fvars:
                    vars = fvars.read()
            # load the default text
            except:
                vars = Strings.vars

        ## initiate the persistant variables
        locals_ = {}
        try:
            exec(vars, {}, locals_)
        except Exception as e:
            print e
        self._vars = locals_

        ## update the vars screen
        self.jVarsPane.document.insertString(self.jVarsPane.document.length,
                                             vars, SimpleAttributeSet())

        ##Load script
        script = callbacks.loadExtensionSetting(self._scriptStorage)
        if script:
            script = base64.b64decode(script)
        else:
            # try to load the example
            try:
                with open("examples/Simple-CSRF-script.py") as fscript:
                    script = fscript.read()
            # load the default text
            except:
                script = Strings.script

        ## compile the rules
        self._script = script
        self._code = ''

        try:
            self._code = compile(script, '<string>', 'exec')
        except Exception as e:
            print(
                '{}\nReload extension after you correct the error.'.format(e))

        ## update the rules screen
        self.jScriptPane.document.insertString(
            self.jScriptPane.document.length, script, SimpleAttributeSet())

        #Register Extension
        callbacks.customizeUiComponent(self.getUiComponent())
        callbacks.addSuiteTab(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerHttpListener(self)

        self.jScriptPane.requestFocus()

    def getUiComponent(self):
        return self.jSplitPane

    def getTabCaption(self):
        return self._name

    def actionPerformed(self, event):
        #Check box was clicked
        if self.jEnable == event.getSource():
            if self._enabled == 1:
                self._enabled = 0
                # console content shows help
                self.jConsoleText.setText(Strings.console_disable)
            else:
                self._enabled = 1
                # console content displays the current persistent variable state
                self.jConsoleText.setText(Strings.console_state)
                self.jConsoleText.append(pformat(self._vars))
                self.jConsoleText.append(Strings.extra_line)
                self.jConsoleText.append(Strings.console_log)
        return

    def mouseClicked(self, event):
        if event.source == self.jDocs:
            uri = URI.create("https://github.com/DanNegrea/PyRules")
            if uri and Desktop.isDesktopSupported() and Desktop.getDesktop(
            ).isSupported(Desktop.Action.BROWSE):
                Desktop.getDesktop().browse(uri)
        return

    def focusGained(self, event):

        if self.jConsolePane == event.getSource():
            pass
            #print "Status pane gained focus" #debug
        return

    def focusLost(self, event):
        #Reinitialize the persistent values
        if self.jVarsPane == event.getSource():
            # get the text from the pane
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)

            # compute the new values
            locals_ = {}
            exec(vars, {}, locals_)
            self._vars = locals_

            # display the new result in console
            self.jConsoleText.append(Strings.console_state)
            self.jConsoleText.append(pformat(self._vars))
            self.jConsoleText.append(Strings.extra_line)
            self.jConsoleText.append(Strings.console_log)

            # scroll to bottom
            verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
            verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return

    def extensionUnloaded(self):
        try:
            #Save the latestest vars and script text
            ## save vars
            end = self.jVarsPane.document.length
            vars = self.jVarsPane.document.getText(0, end)
            vars = base64.b64encode(vars)
            self.callbacks.saveExtensionSetting(self._varsStorage, vars)
            ## save script/rules
            end = self.jScriptPane.document.length
            script = self.jScriptPane.document.getText(0, end)
            script = base64.b64encode(script)
            self.callbacks.saveExtensionSetting(self._scriptStorage, script)
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        print "Unloaded"  #debug
        return

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if self._enabled == 0:
            return

        try:
            locals_ = {
                'extender': self,
                'callbacks': self.callbacks,
                'helpers': self.helpers,
                'toolFlag': toolFlag,
                'messageIsRequest': messageIsRequest,
                'messageInfo': messageInfo,
                'log': self.log
            }
            # add the _vars as gloval variables
            locals_ = dict(locals_, **self._vars)

            # execute the script/rules
            try:
                exec(self.getCode, {}, locals_)
            # catch exit() call inside the rule
            except SystemExit:
                pass

            # update the persistant variables by searching the local variables with the same name
            for key in self._vars:
                # assumption self._vars dictionary is smaller than locals_
                if key in locals_:
                    self._vars[key] = locals_[key]
        except Exception:
            traceback.print_exc(file=self.callbacks.getStderr())
        return

    #Returns the compiled script
    @property
    def getCode(self):
        end = self.jScriptPane.document.length
        script = self.jScriptPane.document.getText(0, end)

        # if the script hasn't changed return the already compile text
        if script == self._script:
            return self._code
        self._script = script

        # compile, store and return the result
        self._code = compile(script, '<string>', 'exec')
        return self._code

    #Log the information into the console screen
    def log(self, obj):
        # if string just append. else use pformat from pprint
        if isinstance(obj, str):
            self.jConsoleText.append(obj + "\n")
        else:
            self.jConsoleText.append(pformat(obj) + "\n")
        # scroll to bottom
        verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar()
        verticalScrollBar.setValue(verticalScrollBar.getMaximum())
        return
class DetermineCookieFrame(JFrame):
    """ This is the GUI for for the user to control the actions when
        determining which cookie is the session cookie.
    """

    def __init__(self, callbacks, selected_message):
        super(DetermineCookieFrame, self).__init__()
        self.callbacks = callbacks
        self.selected_message = selected_message
        self.windowClosing = self.close

    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue());
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)    
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)


        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service, original_request_bytes)
        parameters = request_info.getParameters();
        cookie_parameters = [parameter for parameter in parameters if parameter.getType() == IParameter.PARAM_COOKIE]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append("This may require up to " + str(num_requests_needed) + " requests to be made. Hit 'Run' to begin.\n")

    def start(self, event):
        global cancelThread
        cancelThread = False
        self.runButton.setEnabled(False)
        self.cancelButton.setText("Cancel")
        thread = ThreadDetermineCookie(self.callbacks, self.selected_message, self.statusTextArea, self.progressBar)
        thread.start()

    def cancel(self, event):
        self.setVisible(False);
        self.dispose();

    def close(self, event):
        global cancelThread
        cancelThread = True
Esempio n. 23
0
class BurpExtender(IBurpExtender, IProxyListener, ITab):
    def getTabCaption(self):  ### ITab
        return NAME

    def getUiComponent(self):  ### ITab
        return self.tabs

    def setFontItalic(self, label):
        label.setFont(
            Font(label.getFont().getName(), Font.ITALIC,
                 label.getFont().getSize()))

    def setFontBold(self, label):
        label.setFont(Font('Serif', Font.BOLD, label.getFont().getSize()))

    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable, in_scope_only
        global remove_csrf_headers, remove_csrf_params, change_method_to_post
        global change_ct_to_json, change_ct_to_plain, change_to_get

        callbacks = this_callbacks
        helpers = callbacks.getHelpers()
        callbacks.setExtensionName(NAME)

        self.settings = JPanel(GridBagLayout())
        c = GridBagConstraints()

        self.extension_enable_box = JCheckBox('Enable extension',
                                              extension_enable)
        self.setFontBold(self.extension_enable_box)
        self.extension_enable_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 0
        c.gridwidth = 1
        c.weightx = 1
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.WEST
        self.settings.add(self.extension_enable_box, c)

        self.in_scope_only_box = JCheckBox('Modify only in-scope requests',
                                           in_scope_only)
        self.setFontBold(self.in_scope_only_box)
        self.in_scope_only_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 1
        self.settings.add(self.in_scope_only_box, c)

        self.remove_csrf_headers_box = JCheckBox('Remove CSRF headers',
                                                 remove_csrf_params)
        self.setFontBold(self.remove_csrf_headers_box)
        self.remove_csrf_headers_box.setForeground(Color(0, 0, 153))
        c.insets = Insets(40, 5, 5, 5)
        c.gridx = 0
        c.gridy = 2
        self.settings.add(self.remove_csrf_headers_box, c)

        remove_csrf_headers_box_lbl = JLabel(
            'Check to remove headers with CSRF tokens from all requests.')
        self.setFontItalic(remove_csrf_headers_box_lbl)
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.settings.add(remove_csrf_headers_box_lbl, c)

        self.remove_csrf_params_box = JCheckBox('Remove CSRF parameters',
                                                remove_csrf_params)
        self.setFontBold(self.remove_csrf_params_box)
        self.remove_csrf_params_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 4
        self.settings.add(self.remove_csrf_params_box, c)

        remove_csrf_params_box_lbl = JLabel(
            'Check to remove URL/body parameters with CSRF tokens from all requests. URL-encoded, multipart, JSON parameters are supported.'
        )
        self.setFontItalic(remove_csrf_params_box_lbl)
        c.gridx = 0
        c.gridy = 5
        self.settings.add(remove_csrf_params_box_lbl, c)

        self.change_method_to_post_box = JCheckBox(
            'Change HTTP method to POST', change_method_to_post)
        self.setFontBold(self.change_method_to_post_box)
        self.change_method_to_post_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 6
        self.settings.add(self.change_method_to_post_box, c)

        change_method_to_post_lbl = JLabel(
            'Check to convert PUT/DELETE/PATCH method to POST in all requests.'
        )
        self.setFontItalic(change_method_to_post_lbl)
        c.gridx = 0
        c.gridy = 7
        self.settings.add(change_method_to_post_lbl, c)

        self.change_ct_to_json_box = JCheckBox('Change media type to json',
                                               change_ct_to_json)
        self.setFontBold(self.change_ct_to_json_box)
        self.change_ct_to_json_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 8
        self.settings.add(self.change_ct_to_json_box, c)

        change_ct_to_json_lbl = JLabel(
            'Check to convert body to json and set Content-Type to application/json in url-encoded requests.'
        )
        self.setFontItalic(change_ct_to_json_lbl)
        c.gridx = 0
        c.gridy = 9
        self.settings.add(change_ct_to_json_lbl, c)

        self.change_ct_to_plain_box = JCheckBox(
            'Change Content-Type to text/plain', change_ct_to_plain)
        self.setFontBold(self.change_ct_to_plain_box)
        self.change_ct_to_plain_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 10
        self.settings.add(self.change_ct_to_plain_box, c)

        change_ct_to_plain_lbl = JLabel(
            'Check to set Content-Type to text/plain in request with non-simple media type. Simple media types - application/application/x-www-form-urlencoded, text/plain, multipart/form-data.'
        )
        self.setFontItalic(change_ct_to_plain_lbl)
        c.gridx = 0
        c.gridy = 11
        self.settings.add(change_ct_to_plain_lbl, c)

        self.change_to_get_box = JCheckBox('Change to GET', change_to_get)
        self.setFontBold(self.change_to_get_box)
        self.change_to_get_box.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 12
        self.settings.add(self.change_to_get_box, c)

        change_to_get_lbl = JLabel(
            'Check to convert POST/PUT/DELETE/PATCH url-encoded requests to GET.'
        )
        self.setFontItalic(change_to_get_lbl)
        c.gridx = 0
        c.gridy = 13
        self.settings.add(change_to_get_lbl, c)

        self.csrf_headers_params = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblParams = JLabel("CSRF parameters:")
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblParams, c)

        self.csrf_param_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.csrf_headers_params.add(self.csrf_param_text_field, c)

        lblParamsNote = JLabel(
            "Remove parameter from request if name contains")
        self.setFontItalic(lblParamsNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.csrf_headers_params.add(lblParamsNote, c)

        self.csrf_params_text_area = JTextArea()
        self.csrf_params_text_area.setColumns(20)
        self.csrf_params_text_area.setRows(10)
        self.csrf_params_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_params_mouse_listener = TextAreaMouseListener(
            self.csrf_params_text_area)
        self.csrf_params_text_area.addMouseListener(
            self.csrf_params_mouse_listener)
        for name in csrf_params_names:
            self.csrf_params_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.csrf_params_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_param_text_field,
                                  self.csrf_params_text_area,
                                  self.csrf_params_mouse_listener,
                                  csrf_params_names)
        self.csrf_param_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_param_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_param_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_param_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_param_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_param_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        lblHeaders = JLabel("CSRF headers:")
        self.setFontBold(lblHeaders)
        lblHeaders.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(40, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.csrf_headers_params.add(lblHeaders, c)

        self.csrf_header_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 2
        self.csrf_headers_params.add(self.csrf_header_text_field, c)

        lblHeadersNote = JLabel("Remove header from request if name equals to")
        self.setFontItalic(lblHeadersNote)
        c.fill = GridBagConstraints.NONE
        c.insets = Insets(5, 5, 5, 5)
        c.gridx = 0
        c.gridy = 3
        self.csrf_headers_params.add(lblHeadersNote, c)

        self.csrf_headers_text_area = JTextArea()
        self.csrf_headers_text_area.setColumns(20)
        self.csrf_headers_text_area.setRows(10)
        self.csrf_headers_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.csrf_headers_mouse_listener = TextAreaMouseListener(
            self.csrf_headers_text_area)
        self.csrf_headers_text_area.addMouseListener(
            self.csrf_headers_mouse_listener)
        for name in csrf_headers_names:
            self.csrf_headers_text_area.append(name + os.linesep)
        c.gridx = 1
        c.gridy = 3
        sp = JScrollPane(self.csrf_headers_text_area)
        self.csrf_headers_params.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.csrf_header_text_field,
                                  self.csrf_headers_text_area,
                                  self.csrf_headers_mouse_listener,
                                  csrf_headers_names)
        self.csrf_header_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.csrf_header_rm_button = JButton(
            'Remove', actionPerformed=handlers.handler_rm)
        self.csrf_header_restore_button = JButton(
            'Restore', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.csrf_header_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.csrf_header_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.csrf_header_restore_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 3
        c.fill = GridBagConstraints.NONE
        self.csrf_headers_params.add(buttonsPanel, c)

        self.whitelist = JPanel(GridBagLayout())
        c = GridBagConstraints()

        lblWhitelist = JLabel("URLs whitelist:")
        self.setFontBold(lblWhitelist)
        lblWhitelist.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.whitelist.add(lblWhitelist, c)

        self.whitelist_text_field = JTextField()
        c.fill = GridBagConstraints.BOTH
        c.gridx = 1
        c.gridy = 0
        self.whitelist.add(self.whitelist_text_field, c)

        lblWhitelistNote = JLabel(
            "Do not perform request modification if URL starts with")
        self.setFontItalic(lblWhitelistNote)
        c.fill = GridBagConstraints.NONE
        c.gridx = 0
        c.gridy = 1
        self.whitelist.add(lblWhitelistNote, c)

        self.whitelist_text_area = JTextArea()
        self.whitelist_text_area.setColumns(30)
        self.whitelist_text_area.setRows(10)
        self.whitelist_text_area.setEditable(False)
        c.fill = GridBagConstraints.BOTH
        self.whitelist_mouse_listener = TextAreaMouseListener(
            self.whitelist_text_area)
        self.whitelist_text_area.addMouseListener(
            self.whitelist_mouse_listener)
        c.gridx = 1
        c.gridy = 1
        sp = JScrollPane(self.whitelist_text_area)
        self.whitelist.add(sp, c)

        buttonsPanel = JPanel(GridBagLayout())
        _c = GridBagConstraints()
        _c.insets = Insets(3, 3, 3, 3)
        _c.gridx = 0
        _c.gridy = 0
        _c.fill = GridBagConstraints.BOTH
        _c.weightx = 1
        _c.gridwidth = 1

        handlers = ButtonHandlers(self.whitelist_text_field,
                                  self.whitelist_text_area,
                                  self.whitelist_mouse_listener, [])
        self.whitelist_add_button = JButton(
            'Add', actionPerformed=handlers.handler_add)
        self.whitelist_rm_button = JButton('Remove',
                                           actionPerformed=handlers.handler_rm)
        self.whitelist_clear_button = JButton(
            'Clear', actionPerformed=handlers.handler_restore)
        buttonsPanel.add(self.whitelist_add_button, _c)
        _c.gridy = 1
        buttonsPanel.add(self.whitelist_rm_button, _c)
        _c.gridy = 2
        buttonsPanel.add(self.whitelist_clear_button, _c)
        _c.gridy = 3

        c.gridx = 2
        c.gridy = 1
        c.fill = GridBagConstraints.NONE
        self.whitelist.add(buttonsPanel, c)

        self.tabs = JTabbedPane()
        self.tabs.addTab('Settings', self.settings)
        self.tabs.addTab('CSRF params/headers to remove',
                         self.csrf_headers_params)
        self.tabs.addTab('Requests whitelist', self.whitelist)

        callbacks.customizeUiComponent(self.tabs)
        callbacks.addSuiteTab(self)

        callbacks.registerProxyListener(self)

        callbacks.registerContextMenuFactory(
            SendToWhitelist(self.whitelist_text_area))

        print "Successfully loaded %s v%s by Mikhail Egorov @0ang3el" % (
            NAME, VERSION)

    def text_area_to_list(self, text_area):
        l = text_area.getText().strip().split('\n')
        return l if l != [''] else []

    def filter_headers(self, headers):
        _headers = headers[:]
        for header in headers:
            for csrf_header in self.text_area_to_list(
                    self.csrf_headers_text_area):
                if header.lower().startswith(csrf_header.lower()):
                    _headers.remove(header)

        return _headers

    def processProxyMessage(self, messageIsRequest,
                            message):  ### IProxyListener
        global callbacks
        extension_enable = self.extension_enable_box.isSelected()
        if not extension_enable:
            return  # Do nothing

        in_scope_only = self.in_scope_only_box.isSelected()

        remove_csrf_headers = self.remove_csrf_headers_box.isSelected()
        remove_csrf_params = self.remove_csrf_params_box.isSelected()
        change_method_to_post = self.change_method_to_post_box.isSelected()
        change_ct_to_json = self.change_ct_to_json_box.isSelected()
        change_ct_to_plain = self.change_ct_to_plain_box.isSelected()
        change_to_get = self.change_to_get_box.isSelected()

        request_response = message.getMessageInfo()
        request_info = helpers.analyzeRequest(request_response)
        request_method = request_info.getMethod()

        if in_scope_only and not callbacks.isInScope(request_info.getUrl()):
            return  # Do nothing when URL is not in scope

        if not messageIsRequest or request_method not in [
                'POST', 'PUT', 'DELETE', 'PATCH'
        ]:
            return  # Do nothing

        for whitelisted in self.text_area_to_list(self.whitelist_text_area):
            if str(request_info.getUrl()).startswith(whitelisted):
                return  # Do nothing when URL is whitelisted

        http_service = request_response.getHttpService()
        request = request_response.getRequest()
        headers = request_info.getHeaders()
        parameters = request_info.getParameters()

        new_headers = headers
        if remove_csrf_headers:
            new_headers = self.filter_headers(headers)  # Remove CSRF headers

        if change_ct_to_plain and request_info.getContentType() not in [
                IRequestInfo.CONTENT_TYPE_URL_ENCODED,
                IRequestInfo.CONTENT_TYPE_MULTIPART
        ]:
            for i in range(len(new_headers)):
                if new_headers[i].lower().startswith(
                        'content-type'):  # Change CT to text/plain
                    new_headers[i] = 'Content-Type: text/plain'

        if remove_csrf_params:
            for parameter in parameters:  # Remove CSRF parameters from request's body or URL
                for csrf_param in self.text_area_to_list(
                        self.csrf_params_text_area):
                    if parameter.getType() != IParameter.PARAM_COOKIE and \
                            csrf_param.lower() in parameter.getName().lower():
                        if request_info.getContentType(
                        ) == IRequestInfo.CONTENT_TYPE_MULTIPART:
                            start = parameter.getNameStart()
                            end = parameter.getNameEnd()

                            request = request[:start] + helpers.stringToBytes(
                                "REPLACEMENT") + request[end:]
                        elif parameter.getType() == IParameter.PARAM_JSON:
                            start = parameter.getNameStart() - 1
                            end = parameter.getValueEnd() + 1
                            request = request[:start] + request[end:]

                            offset = helpers.analyzeRequest(
                                http_service, request).getBodyOffset()
                            body = request[offset:]
                            body = re.sub(",\s*,", ",", body)
                            body = re.sub("{\s*,", "{", body)
                            body = re.sub(",\s*}", "}", body)

                            request = helpers.buildHttpMessage(headers, body)
                        elif parameter.getType() in [
                                IParameter.PARAM_URL, IParameter.PARAM_BODY
                        ]:
                            request = helpers.removeParameter(
                                request, parameter)

        offset = helpers.analyzeRequest(http_service, request).getBodyOffset()
        body = request[offset:]

        if change_ct_to_json and request_info.getContentType(
        ) == IRequestInfo.CONTENT_TYPE_URL_ENCODED:
            for i in range(len(new_headers)):
                if new_headers[i].lower().startswith(
                        'content-type'):  # Change to JSON from URL-encoded
                    new_headers[i] = 'Content-Type: application/json'

            body = safe_bytes_to_string(body)
            d = dict((k, v if len(v) > 1 else v[0])
                     for k, v in parse_qs(body).iteritems())
            body = dumps(d)

        if (change_method_to_post and request_method != 'POST') or (change_to_get and not change_ct_to_json and \
                                request_info.getContentType() == IRequestInfo.CONTENT_TYPE_URL_ENCODED):
            for i in range(len(new_headers)):
                if new_headers[i].startswith("PUT") or new_headers[i].startswith("DELETE") \
                        or new_headers[i].startswith("PATCH"):
                    new_headers[i] = new_headers[i].replace(
                        request_method, 'POST', 1)
                    break

        new_request = helpers.buildHttpMessage(
            new_headers, body)  # Create new request with valid Content-Length

        if (change_method_to_post and request_method != 'POST') or (change_to_get and not change_ct_to_json and \
                                request_info.getContentType() == IRequestInfo.CONTENT_TYPE_URL_ENCODED):
            param1 = helpers.buildParameter('method', request_method,
                                            IParameter.PARAM_URL)
            param2 = helpers.buildParameter('_method', request_method,
                                            IParameter.PARAM_URL)
            new_request = helpers.addParameter(new_request, param1)
            new_request = helpers.addParameter(new_request, param2)
            if change_to_get:
                new_request = helpers.toggleRequestMethod(
                    new_request)  # Change any URL-encoded request to GET

        message.setInterceptAction(
            IInterceptedProxyMessage.ACTION_FOLLOW_RULES_AND_REHOOK)
        message.getMessageInfo().setRequest(new_request)
        message.getMessageInfo().setHighlight('red')
class DetermineCookieFrame(JFrame):
    """ This is the GUI for for the user to control the actions when
        determining which cookie is the session cookie.
    """
    def __init__(self, callbacks, selected_message):
        super(DetermineCookieFrame, self).__init__()
        self.callbacks = callbacks
        self.selected_message = selected_message
        self.windowClosing = self.close

    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(
            BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue())
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service,
                                              original_request_bytes)
        parameters = request_info.getParameters()
        cookie_parameters = [
            parameter for parameter in parameters
            if parameter.getType() == IParameter.PARAM_COOKIE
        ]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append(
            "This may require up to " + str(num_requests_needed) +
            " requests to be made. Hit 'Run' to begin.\n")

    def start(self, event):
        global cancelThread
        cancelThread = False
        self.runButton.setEnabled(False)
        self.cancelButton.setText("Cancel")
        thread = ThreadDetermineCookie(self.callbacks, self.selected_message,
                                       self.statusTextArea, self.progressBar)
        thread.start()

    def cancel(self, event):
        self.setVisible(False)
        self.dispose()

    def close(self, event):
        global cancelThread
        cancelThread = True
Esempio n. 25
0
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory):
    EXTENSION_NAME = "AutoRecon"
    # subdomain = list()
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "Accept":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language":
        "en-US,en;q=0.9",
        "Accept-Encoding":
        "gzip, deflate, br",
    }

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName(self.EXTENSION_NAME)

        callbacks.issueAlert("AutoRecon is enabled")

        # add the custom tab to Burp's UI
        self.initUI()
        # self._newpanel.setLayout(FlowLayout())
        # callbacks.customizeUiComponent(self._newpanel)
        callbacks.addSuiteTab(self)

        self.callable = [
            # self.sublister,
            # self.shodan_search,
            self.certsh_search,
            # self.anubis,
            # self.googleDig,
            # self.censys,
            # self.certspotter,
            # self.bufferover_run,
            # self.urlscan,
            # self.otx_alienvault,
            # self.threatminer,
            # self.netcraft,
            # self.threatcrowd,
            # self.dnsdumpster,
            # self.virustotal,
            # self.ptrarchive,
        ]
        # self.callable = [self.censys]

        # define stdout writer
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)
        self._stdout.println(self.EXTENSION_NAME + " by @bourne")
        self._stdout.println(
            "================================================")
        self._stdout.println(
            'TIP: Right click on any domain and add it to scope in "autoRecon"'
        )
        self._stdout.println("")
        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )

        self.context = None

        callbacks.registerContextMenuFactory(self)

        return

    def initUI(self):
        self.tab = JPanel()

        # UI for Output
        self.outputLabel = JLabel("AutoRecon Log:")
        self.outputLabel.setFont(Font("Tahoma", Font.BOLD, 14))
        self.outputLabel.setForeground(Color(255, 102, 52))
        self.logPane = JScrollPane()
        self.outputTxtArea = JTextArea()
        self.outputTxtArea.setFont(Font("Consolas", Font.PLAIN, 12))
        self.outputTxtArea.setLineWrap(True)
        self.logPane.setViewportView(self.outputTxtArea)
        self.clearBtn = JButton("Clear Log", actionPerformed=self.clearLog)
        self.exportBtn = JButton("Export Log", actionPerformed=self.exportLog)
        self.parentFrm = JFileChooser()

        # Layout
        layout = GroupLayout(self.tab)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)
        self.tab.setLayout(layout)

        layout.setHorizontalGroup(layout.createParallelGroup().addGroup(
            layout.createSequentialGroup().addGroup(
                layout.createParallelGroup().addComponent(
                    self.outputLabel).addComponent(self.logPane).addComponent(
                        self.clearBtn).addComponent(self.exportBtn))))

        layout.setVerticalGroup(layout.createParallelGroup().addGroup(
            layout.createParallelGroup().addGroup(
                layout.createSequentialGroup().addComponent(
                    self.outputLabel).addComponent(self.logPane).addComponent(
                        self.clearBtn).addComponent(self.exportBtn))))

    def getTabCaption(self):
        """Name of our tab"""
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.tab

    def clearLog(self, event):
        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )

    def exportLog(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 createMenuItems(self, context_menu):
        self.context = context_menu
        menu_list = ArrayList()
        menu_list.add(
            JMenuItem("Add domain to scope for AutoRecon",
                      actionPerformed=self.threadAnalysis))
        return menu_list

    def threadAnalysis(self, event):
        http_traffic = self.context.getSelectedMessages()

        self._stdout.println(str(len(http_traffic)) + " requests highlighted")

        for traffic in http_traffic:
            http_service = traffic.getHttpService()
            host = http_service.getHost()
            if host.startswith("www."):
                host = host[4:]

            self._stdout.println("User selected host: " + str(host))

        self.subdomain = list()
        threads = []
        for i in self.callable:
            time.sleep(1)
            thread = threading.Thread(target=i, args=(host, ))
            # thread.daemon = True
            threads.append(thread)
            thread.start()

        for i in threads:
            i.join()

        self.outputTxtArea.setText(
            self.EXTENSION_NAME + " by @bourne" + "\n" +
            "================================================" + "\n" +
            'TIP: Right click on any domain and add it to scope in "autoRecon"\n'
        )
        self.outputTxtArea.append("\n DOMAIN: " + host)
        self.outputTxtArea.append("\n Total {} subdomains found :\n\n".format(
            len(set(self.subdomain))))
        for s in set(self.subdomain):
            if not "*" in s:
                self.outputTxtArea.append("\n" + s)
                # request_url = """https://api.viewdns.info/portscan/?host={}&apikey=3b59ef16aea9a71c7e6ae2872e83008493375e9e&output=json""".format(
                #     s
                # )
                # try:
                #     # self.outputTxtArea.append(request_url)
                #     time.sleep(2)
                #     req = requests.get(request_url, verify=False, headers=self.headers, timeout=3)
                #     req = json.loads(req.text)
                # except Exception as e:
                #     self.outputTxtArea.append(str(e))

                # for i in req["response"]["port"]:
                #     if i["status"] == "open":
                #         self.outputTxtArea.append("\n\t",i["number"],i["service"])

                try:
                    req = requests.get(
                        """http://web.archive.org/cdx/search/cdx?url=*.{0}/*
                                    &output=json&fl=original&collapse=urlkey&page=/"""
                        .format(s),
                        verify=False,
                        headers=self.headers,
                        timeout=3)
                    temp = []
                    t = json.loads(req.text)
                    for i in t:
                        temp.extend(i)
                except Exception:
                    pass
                paths = []
                count = 0
                for i in range(1, len(temp)):
                    not_contains = re.compile("|".join(
                        ["js", "txt", "git", "zip"]))
                    # print(type(temp[i]))

                    if temp[i] not in paths and not_contains.search(temp[i]):
                        paths.append(temp[i])
                        count += 1
                for i in paths:
                    if ".js" in i.lower() or ".zip" in i.lower(
                    ) or ".txt" in i.lower() or ".git" in i.lower():
                        self.outputTxtArea.append("\n\t" + i)

        # thread = threading.Thread(target=self.certsh_search, args=(host,))
        # thread.daemon = True
        # thread.start()

        # thread = threading.Thread(target=self.shodan_search, args=(host,))
        # thread.daemon = True
        # thread.start()

    def certsh_search(self, host):
        BASE_URL = "https://crt.sh"
        threadLocal.response = requests.get(BASE_URL + "/?q=%." + host +
                                            "&output=json")
        # self._stdout.println(threadLocal.response)
        threadLocal.result = threadLocal.response.json()
        # self._stdout.println(result)
        threadLocal.sub = []

        for item in threadLocal.result:
            s = item["name_value"]
            t = s.split("\n")
            self.subdomain.extend(t)
            # self.subdomain.append(s)
            # self._stdout.println(item)
            self._stdout.println(self.subdomain)
            self._stdout.println("....")
            if s not in threadLocal.sub:
                threadLocal.sub.append(s)
                self._stdout.println(s)
        return

    def shodan_search(self, host):
        BASE_URL = "https://api.shodan.io/shodan/host/search/"
        SHODAN_API_KEY = "J1Rp7W8tcqmhsdiB3ZU3JVhOlPpOHp8X"
        API = "WozM2OXwuUSMSsiseIkPtyLFxYnDUrPP"
        QUERY = "hostname"

        try:
            threadLocal.response = requests.get(
                "https://api.shodan.io/shodan/host/search?key=" +
                SHODAN_API_KEY + "&query=hostname:" + host)
            # self._stdout.println(response.text)
            threadLocal.result = threadLocal.response.json()
            # self._stdout.println(result)
            threadLocal.sub = []
            for item in threadLocal.result["matches"]:
                s = item["hostnames"][0]
                self.subdomain.append(s)
                if s not in threadLocal.sub:
                    threadLocal.sub.append(s)
                    self._stdout.println(s)
            return
        except Exception as error:
            logging.exception("message")

    def anubis(self, host):
        BASE_URL = "https://jldc.me/anubis/subdomains/{0}".format(host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)
            for w in results:
                if "*" not in w and w.endswith(
                        "." + host) and w not in threadLocal.sub:
                    threadLocal.sub.append(w)
                    self.subdomain.append(w)
                    self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    def bufferover_run(self, host):
        try:
            threadLocal.response = requests.get(
                "http://dns.bufferover.run/dns?q={0}".format(host))
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["FDNS_A"]
            for w in results:
                domain = w.split(",")[1]
                if ("*" not in domain and domain.endswith("." + host)
                        and domain not in threadLocal.sub):
                    threadLocal.sub.append(domain)
                    self.subdomain.append(domain)
                    self._stdout.println(domain)
            return
        except Exception as error:
            logging.exception("message")

    def urlscan(self, host):
        BASE_URL = "https://urlscan.io/api/v1/search/?q=domain:{0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["results"]
            for w in results:
                domain = w["page"]["domain"]
                if ("*" not in domain and domain.endswith("." + host)
                        and domain not in threadLocal.sub):
                    threadLocal.sub.append(domain)
                    self.subdomain.append(domain)
                    self._stdout.println(domain)
            return
        except Exception as error:
            logging.exception("message")

    def otx_alienvault(self, host):
        BASE_URL = "https://otx.alienvault.com/api/v1/indicator/domain/{0}/passive_dns".format(
            host)

        try:
            tHeader = {
                "Host": "otx.alienvault.com",
                "User-Agent":
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
                "Accept":
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Cache-Control": "max-age=0",
            }

            response = requests.get(BASE_URL)
            threadLocal.sub = []
            self._stdout.println(response.status_code)
            # results = json.loads(threadLocal.response.text)["passive_dns"]
            # for w in results:
            #     h = w["hostname"]
            #     if "*" not in h and h.endswith("." + host) and h not in threadLocal.sub:
            #         threadLocal.sub.append(h)
            #         self.subdomain.append(h)
            #         self._stdout.println(h)
            return
        except Exception as error:
            logging.exception("message")

    def threatminer(self, host):
        BASE_URL = "https://api.threatminer.org/v2/domain.php?q={0}&api=True&rt=5".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            results = json.loads(threadLocal.response.text)["results"]
            for w in results:
                if "*" not in w and w.endswith(
                        "." + host) and w not in threadLocal.sub:
                    threadLocal.sub.append(w)
                    self.subdomain.append(w)
                    self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    # def censys(self, host):
    #     try:
    #         censys_certificates = censys.certificates.CensysCertificates(
    #             api_id="5d63a69e-6142-46ec-830f-7279734e76f0", api_secret="qz6uDnlOCfZPJIXVyKvheot5HUxqZjNl")
    #         certificate_query = 'parsed.names: %s' % host
    #         certificates_search_results = censys_certificates.search(
    #             certificate_query, fields=['parsed.names'])

    #         subdomains = []
    #         for search_result in certificates_search_results:
    #             subdomains.extend(search_result['parsed.names'])
    #             self._stdout.println(search_result['parsed.names'])
    #     except Exception as error:
    #         self._stderr.println(error)

    #     return threadLocal.subs

    def certspotter(self, host):
        BASE_URL = "https://certspotter.com/api/v0/certs?domain={0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            if threadLocal.response.status_code == 200:
                for w in (threadLocal.response.content.replace(
                        '"', " ").replace("'", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.sub):
                        threadLocal.sub.append(w)
                        self.subdomain.append(w)
                        self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")

    def googleDig(self, host):
        try:
            url_1 = "https://toolbox.googleapps.com/apps/dig/#ANY/"
            url_2 = "https://toolbox.googleapps.com/apps/dig/lookup"
            s = requests.session()
            threadLocal.req = s.get(url_1)
            csrf_middleware = re.compile(
                "<input type='hidden' name='csrfmiddlewaretoken' value='(.*?)' />",
                re.S).findall(threadLocal.req.content)[0]
            # tHeader = self.headers
            # tHeader["Referer"] = url_1
            threadLocal.req = s.post(
                url_2,
                cookies={"csrftoken": csrf_middleware},
                data={
                    "csrfmiddlewaretoken": csrf_middleware,
                    "domain": host,
                    "typ": "ANY",
                },
                headers={"Referer": url_1},
                verify=False,
            )
            threadLocal.subs = []
            if threadLocal.req.status_code is 200:
                for w in (json.loads(
                        threadLocal.req.content)["response"].replace(
                            '"', " ").replace(";", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host + ".")
                            and w[:-1] not in threadLocal.subs):
                        threadLocal.subs.append(w[:-1])
                        self.subdomain.append(w[:-1])
            else:
                # warn 403
                pass
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def netcraft(self, host):
        try:
            threadLocal.n = 0
            threadLocal.results = ""
            url = (
                "https://searchdns.netcraft.com/?restriction=site+contains&host=*.{0}"
                "&lookup=wait..&position=limited".format(host))

            threadLocal.subs = []
            while "<b>Next page</b></a>" not in threadLocal.results:
                while 1:
                    try:
                        threadLocal.results = requests.get(url)
                        break
                    except:
                        threadLocal.n += 1
                        if threadLocal.n is 3:
                            break
                if threadLocal.n is 3:
                    break
                if threadLocal.results.status_code is 200:
                    for l in re.compile(
                            '<a href="http://toolbar.netcraft.com/site_report\?url=(.*)">'
                    ).findall(threadLocal.results.content):
                        domain = parse_url(l).host

                        if ("*" not in domain and domain.endswith("." + host)
                                and domain not in threadLocal.subs):
                            threadLocal.subs.append(domain)
                            self.subdomain.append(domain)
                else:
                    # warn 403
                    break
                try:
                    url = ("http://searchdns.netcraft.com" +
                           re.compile('<A href="(.*?)"><b>Next page</b></a>').
                           findall(threadLocal.results.content)[0])
                except:
                    break
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def threatcrowd(self, host):
        try:
            threadLocal.n = 0
            url = "https://www.threatcrowd.org/searchApi/v2/domain/report/?domain={0}".format(
                host)
            threadLocal.subs = []
            while 1:
                try:
                    threadLocal.results = requests.get(url)
                    break
                except:
                    threadLocal.n += 1
                    if threadLocal.n is 3:
                        break
            if threadLocal.results.status_code is 200:
                try:
                    threadLocal.subs = json.loads(
                        threadLocal.results.content)["subdomains"]
                    for i in threadLocal.subs:
                        self.subdomain.append(i)
                except:
                    threadLocal.subs = []
            else:
                # warn 403
                pass
            return threadLocal.subs
        except Exception as error:
            logging.exception("message")

    def dnsdumpster(self, host):
        try:
            url = "https://dnsdumpster.com/"
            s = requests.session()
            threadLocal.req = s.get(url)
            csrf_middleware = re.compile(
                "<input type='hidden' name='csrfmiddlewaretoken' value='(.*?)' />",
                re.S).findall(threadLocal.req.content)[0]
            threadLocal.req = s.post(
                url,
                cookies={"csrftoken": csrf_middleware},
                data={
                    "csrfmiddlewaretoken": csrf_middleware,
                    "targetip": host
                },
                headers={"Referer": url},
            )
            threadLocal.subs = []
            if threadLocal.req.status_code is 200:
                for w in (threadLocal.req.content.replace(".<", " ").replace(
                        "<", " ").replace(">", " ").rsplit()):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.subs):
                        threadLocal.subs.append(w)
                        self.subdomain.append(w)
            else:
                # warn 403
                pass
        except Exception as error:
            logging.exception("message")
        return threadLocal.subs

    def virustotal(self, host):
        n = 0
        url = "https://www.virustotal.com/en/domain/{0}/information/".format(
            host)
        threadLocal.subs = []
        try:
            threadLocal.results = requests.get(url, headers=headers)
            if threadLocal.results.status_code is 200:
                try:
                    for l in re.compile(
                            '<div class="enum.*?">.*?<a target="_blank" href=".*?">(.*?)</a>',
                            re.S,
                    ).findall(threadLocal.results.content):
                        domain = parse_url(l).host
                        if ("*" not in domain
                                and domain.strip().endswith("." + host)
                                and domain.strip() not in threadLocal.subs):
                            threadLocal.subs.append(domain.strip())
                except:
                    pass
            else:
                # warn 403
                pass
        except:
            pass
        return threadLocal.subs

    def ptrarchive(self, host):
        n = 0
        url = "http://ptrarchive.com/tools/search2.htm?label={0}&date=ALL".format(
            host)
        threadLocal.subs = []
        try:
            threadLocal.results = requests.get(url, headers=headers)
            if threadLocal.results.status_code is 200:
                for sub in threadLocal.results.content.rsplit():
                    if ("*" in sub and sub.endswith("." + host)
                            and sub not in threadLocal.subs):
                        threadLocal.subs.append(sub)
            else:
                # warn 403
                pass
        except:
            pass
        return threadLocal.subs

    def sublister(self, host):
        BASE_URL = "https://api.sublist3r.com/search.php?domain={0}".format(
            host)

        try:
            threadLocal.response = requests.get(BASE_URL)
            threadLocal.sub = []
            if threadLocal.response.status_code == 200:
                for w in (json.loads(threadLocal.response.text)):
                    if ("*" not in w and w.endswith("." + host)
                            and w not in threadLocal.sub):
                        threadLocal.sub.append(w)
                        self.subdomain.append(w)
                        self._stdout.println(w)
            return
        except Exception as error:
            logging.exception("message")