Beispiel #1
0
class DynamicComboBox(java.lang.Runnable, ActionListener):

    #---------------------------------------------------------------------------
    # Name: run()
    # Role: Instantiate the user class
    # Note: Invoked by the Swing Event Dispatch Thread
    #---------------------------------------------------------------------------
    def run(self):
        self.frame = frame = JFrame('DynamicComboBox',
                                    size=(310, 137),
                                    layout=BorderLayout(),
                                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        panel = JPanel()
        panel.add(JLabel('Pick one:'))
        self.choices = 'The,quick,brown,fox,jumped'.split(',')
        self.choices.extend('over,the,lazy,spam'.split(','))
        self.ComboBox = ComboBox = JComboBox(self.choices, editable=1)
        ComboBox.addActionListener(self)
        panel.add(ComboBox)
        frame.add(panel, BorderLayout.NORTH)
        panel = JPanel()
        self.RemoveButton = JButton('Remove', actionPerformed=self.remove)
        panel.add(self.RemoveButton)
        frame.add(panel, BorderLayout.CENTER)
        panel = JPanel(alignmentX=Component.CENTER_ALIGNMENT)
        self.msg = panel.add(JLabel('Make a selection'))
        frame.add(panel, BorderLayout.SOUTH)
        frame.setVisible(1)

    #---------------------------------------------------------------------------
    # Name: actionPerformed()
    # Role: Event handler associated withe the JComboBox
    #---------------------------------------------------------------------------
    def actionPerformed(self, event):
        cb = self.ComboBox
        item = cb.getSelectedItem().strip()
        items = [cb.getItemAt(i) for i in range(cb.getItemCount())]
        if item:
            if item not in items:
                cb.addItem(item)
                self.RemoveButton.setEnabled(1)
            msg = 'Selection: "%s"' % item
            self.msg.setText(msg)
        else:
            cb.setSelectedIndex(0)

    #---------------------------------------------------------------------------
    # Name: remove()
    # Role: Event handler associated withe the "Remove" button
    #---------------------------------------------------------------------------
    def remove(self, event):
        cb = self.ComboBox
        index = cb.getSelectedIndex()
        item = cb.getSelectedItem()
        try:
            cb.removeItem(item)
            self.msg.setText('Item removed: "%s"' % item)
        except:
            self.msg.setText('Remove request failed')
        self.RemoveButton.setEnabled(cb.getItemCount() > 1)
Beispiel #2
0
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.isEnabled = False
        callbacks.setExtensionName('app-traffic')
        callbacks.addSuiteTab(self)
    # Called on "Enable" button click to spin up the API Gateway
    def enableGateway(self, event):
        self.isEnabled = True
        self.set_sys_proxy(True)
        self.enable_button.setEnabled(False)
        self.target_host.setEnabled(False)
        self.disable_button.setEnabled(True)
        return
    # Called on "Disable" button click to delete API Gateway
    def disableGateway(self, event):
        self.isEnabled = False
        self.set_sys_proxy(False)
        self.enable_button.setEnabled(True)
        self.target_host.setEnabled(True)
        self.disable_button.setEnabled(False)
        return
    # Tab name
    def getTabCaption(self):
        return 'app-traffic'
    def set_key(self, ip, value):  
        subprocess.Popen('taskkill /f /im iexplore.exe >nul 2>&1', shell=True)
        subprocess.Popen('reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /d "'+str(ip)+'" /f', shell=True)
        subprocess.Popen('reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d '+str(value)+' /f', shell=True)
        subprocess.Popen('ping -n 5 127.0.0.1 >nul', shell=True)
        subprocess.Popen('start iexplore.exe http://burp', shell=True)

    def set_sys_proxy(self,on_off):
        if on_off:
            self.set_key(self.target_host.text, 1)   
        else:
            self.set_key('', 0)  
    # Layout the UI
    def getUiComponent(self):
        self.panel = JPanel()
        self.main = JPanel()
        self.main.setLayout(BoxLayout(self.main, BoxLayout.Y_AXIS))
        self.target_host_panel = JPanel()
        self.main.add(self.target_host_panel)
        self.target_host_panel.setLayout(
            BoxLayout(self.target_host_panel, BoxLayout.X_AXIS))
        self.target_host_panel.add(JLabel('Listen Prot:'))
        self.target_host = JTextField('127.0.0.1:8080', 25)
        self.target_host_panel.add(self.target_host)
        self.buttons_panel = JPanel()
        self.main.add(self.buttons_panel)
        self.buttons_panel.setLayout(
            BoxLayout(self.buttons_panel, BoxLayout.X_AXIS))
        self.enable_button = JButton('Enable', actionPerformed= self.enableGateway)
        self.buttons_panel.add(self.enable_button)
        self.disable_button = JButton('Disable', actionPerformed= self.disableGateway)
        self.buttons_panel.add(self.disable_button)
        self.disable_button.setEnabled(False)
        self.panel.add(self.main)
        return self.panel
Beispiel #3
0
    def __init__(self,
                 logtable_factory=None,
                 external_filter_action_listener=None,
                 external_start_button_action_listener=None,
                 external_stop_button_action_listener=None,
                 external_clear_button_action_listener=None,
                 tools_keys=None):
        self.this = JPanel()

        if tools_keys is None:
            tools_keys = []

        self.external_start_button_action_listener = external_start_button_action_listener
        self.external_stop_button_action_listener = external_stop_button_action_listener
        self.external_clear_button_action_listener = external_clear_button_action_listener


        self.this.setLayout(BoxLayout(self.this, BoxLayout.Y_AXIS))

        # main split pane
        splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTableModel = LogTableModel()
        self.logTableModel = logTableModel
        if logtable_factory is not None:
            logTable = logtable_factory(logTableModel)
        else:
            # XXX: create a generic logtable that works even without burp to made it work standalone
            raise ValueError("logtable_factory cannot be none")
        scrollPane = JScrollPane(logTable)
        splitPane.setLeftComponent(scrollPane)

        # tabs with request/response viewers
        tabs = JTabbedPane()
        tabs.setBorder(BorderFactory.createLineBorder(Color.black))
        tabs.addTab("Request", logTable.getRequestViewer().getComponent())
        tabs.addTab("Response", logTable.getResponseViewer().getComponent())
        splitPane.setRightComponent(tabs)

        # top control panel
        controlPanel = JPanel(FlowLayout(FlowLayout.LEFT))

        toolLabel = JLabel("Select tool: ")
        controlPanel.add(toolLabel)


        tools = JavaArrayList(tools_keys)
        toolList = JComboBox(tools)
        toolList.addActionListener(external_filter_action_listener)
        controlPanel.add(toolList)

        startButton = JButton("Start")
        self.startButton = startButton
        controlPanel.add(startButton)
        stopButton = JButton("Stop")
        self.stopButton = stopButton
        controlPanel.add(stopButton)
        clearButton = JButton("Clear")
        self.clearButton = clearButton
        startButton.setEnabled(False)
        controlPanel.add(clearButton)
        scopeLabel = JLabel("In-scope items only?")
        controlPanel.add(scopeLabel)
        scopeCheckBox = JCheckBox()
        self.scopeCheckBox = scopeCheckBox
        controlPanel.add(scopeCheckBox)
        filterLabel = JLabel("Filter Query:")
        controlPanel.add(filterLabel)
        queryFilterText = JTextField(40)
        self.queryFilterText = queryFilterText
        controlPanel.add(queryFilterText)

        startButton.addActionListener(self.start_button_action_listener)

        stopButton.addActionListener(self.stop_button_action_listener)

        clearButton.addActionListener(self.clear_button_action_listener)

        controlPanel.setAlignmentX(0)
        self.this.add(controlPanel)
        self.this.add(splitPane)
Beispiel #4
0
def reloadJButton(game,dialog,node):
    c = JButton(text)
    if node.hasAttribute("enabled"): c.setEnabled(node.getAttribute("enabled")=="true");
class BurpExtender(IBurpExtender, IExtensionStateListener, ITab):
    ext_name = "CompuRacerExtension"
    ext_version = '1.2'
    loaded = True
    t = None

    def registerExtenderCallbacks(self, callbacks):
        Cb(callbacks)
        Cb.callbacks.setExtensionName(self.ext_name)

        try:
            global compuracer_communication_lock

            # option picker item objects (for Java compatibility)
            item1 = {'key': 'item1', 'name': '2'}
            item2 = {'key': 'item2', 'name': '3'}
            item3 = {'key': 'item3', 'name': '4'}
            item4 = {'key': 'item4', 'name': '5'}
            item5 = {'key': 'item5', 'name': '10'}
            item6 = {'key': 'item6', 'name': '15'}
            item7 = {'key': 'item7', 'name': '20'}
            item8 = {'key': 'item8', 'name': '25'}
            item9 = {'key': 'item9', 'name': '50'}
            item10 = {'key': 'item10', 'name': '100'}

            # main splitted pane + top pane
            self._main_splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
            self._outer_settings_pane = JPanel(BorderLayout())
            self._settings_pane = JPanel(GridBagLayout())
            c = GridBagConstraints()

            self.label_1 = JLabel("Number of parallel requests:")
            c.fill = GridBagConstraints.NONE
            c.gridx = 0
            c.gridy = 0
            c.insets = Insets(0, 5, 0, 10)
            c.anchor = GridBagConstraints.LINE_START
            self._settings_pane.add(self.label_1, c)

            self.input_parallel_requests = JComboBox([
                Item(item1),
                Item(item2),
                Item(item3),
                Item(item4),
                Item(item5),
                Item(item6),
                Item(item7),
                Item(item8),
                Item(item9),
                Item(item10)
            ])
            self.input_parallel_requests.setSelectedIndex(4)
            self.input_parallel_requests.setToolTipText(
                "Select the number of parallel requests that will be sent")
            self.input_parallel_requests.addActionListener(
                self.change_parallel_requests)
            c.gridx = 1
            c.gridy = 0
            c.insets = Insets(0, 5, 0, 10)
            self._settings_pane.add(self.input_parallel_requests, c)

            self.option_allow_redirects = JCheckBox(
                "Allow redirects", actionPerformed=self.check_allow_redirects)
            self.option_allow_redirects.setToolTipText(
                "Select whether redirect responses are followed")
            c.gridx = 2
            c.gridy = 0
            c.insets = Insets(0, 20, 0, 10)
            self._settings_pane.add(self.option_allow_redirects, c)

            self.option_sync_last_byte = JCheckBox(
                "Sync last byte", actionPerformed=self.check_sync_last_byte)
            self.option_sync_last_byte.setToolTipText(
                "Select whether last byte synchronisation is enabled")
            c.gridx = 2
            c.gridy = 1
            c.insets = Insets(0, 20, 0, 0)
            self._settings_pane.add(self.option_sync_last_byte, c)

            self.label_2 = JLabel("Send timeout in seconds:")
            c.gridx = 0
            c.gridy = 1
            c.insets = Insets(0, 5, 0, 0)
            self._settings_pane.add(self.label_2, c)

            self.input_send_timeout = JComboBox([
                Item(item2),
                Item(item4),
                Item(item5),
                Item(item7),
                Item(item9),
                Item(item10)
            ])
            self.input_send_timeout.setSelectedIndex(3)
            self.input_send_timeout.setToolTipText(
                "Select the wait-for-response timeout after sending the request(s)"
            )
            self.input_send_timeout.addActionListener(self.change_send_timeout)
            c.gridx = 1
            c.gridy = 1
            c.insets = Insets(0, 5, 0, 0)
            self._settings_pane.add(self.input_send_timeout, c)

            self.button_resend_batch = JButton("Resend requests")
            self.button_resend_batch.setToolTipText(
                "Resend all requests with the current configuration")
            self.button_resend_batch.setEnabled(False)
            self.button_resend_batch.addActionListener(
                MenuFactory.start_request_transmitter_button)
            c.gridx = 3
            c.gridy = 0
            c.insets = Insets(0, 20, 0, 10)
            self._settings_pane.add(self.button_resend_batch, c)

            immediate_data_ui_elements[
                "parallel_requests"] = self.input_parallel_requests
            immediate_data_ui_elements[
                "allow_redirects"] = self.option_allow_redirects
            immediate_data_ui_elements[
                "sync_last_byte"] = self.option_sync_last_byte
            immediate_data_ui_elements[
                "send_timeout"] = self.input_send_timeout
            immediate_data_ui_elements[
                "resend_batch"] = self.button_resend_batch

            c = GridBagConstraints()
            c.anchor = GridBagConstraints.WEST
            self._outer_settings_pane.add(self._settings_pane,
                                          BorderLayout.WEST)
            self._main_splitpane.setTopComponent(self._outer_settings_pane)

            self._results_splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
            self._main_splitpane.setBottomComponent(self._results_splitpane)

            # table of log entries
            self.tabs_right = JTabbedPane()
            global _textEditors, DEFAULT_RESULTS
            for i in range(3):
                _textEditors.append(Cb.callbacks.createTextEditor())
                _textEditors[-1].setText(str.encode("\n" + DEFAULT_RESULTS))

            self.tabs_right.add("Summary", _textEditors[0].getComponent())
            self.tabs_right.add("Full result", _textEditors[1].getComponent())
            self.tabs_right.add("Config", _textEditors[2].getComponent())
            self._results_splitpane.setRightComponent(self.tabs_right)

            # tabs with request/response viewers
            global _requestViewers, _requestPane
            _requestPane = JTabbedPane()
            _requestViewers.append(
                Cb.callbacks.createMessageEditor(None, False))
            _requestPane.addTab("Request", _requestViewers[-1].getComponent())
            self._results_splitpane.setLeftComponent(_requestPane)

            # customize our UI components
            Cb.callbacks.customizeUiComponent(self._settings_pane)
            Cb.callbacks.customizeUiComponent(self.tabs_right)
            Cb.callbacks.customizeUiComponent(_requestPane)

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

        except RuntimeException as e:
            callbacks.printError(traceback.format_exc())
            e = PyException(e)
            print("10")
            print(str(self))
            print("{}\t{}\n{}\n".format(e.type, e.value, e.traceback))
        Cb.callbacks.registerContextMenuFactory(MenuFactory())
        callbacks.registerExtensionStateListener(self)

        self.start_alive_checker()

        Cb.callbacks.printOutput('%s v%s extension loaded\n' %
                                 (self.ext_name, self.ext_version))

    def change_parallel_requests(self, event):
        global immediate_data
        try:
            num_parallel = MenuFactory.item_selected(event)
            if num_parallel != immediate_data['settings'][0]:
                self.update_setting(0, num_parallel,
                                    "number of parallel requests")
        except Exception as e:
            print(e)

    def change_send_timeout(self, event):
        global immediate_data
        try:
            send_timeout = MenuFactory.item_selected(event)
            if send_timeout != immediate_data['settings'][4]:
                self.update_setting(4, send_timeout, "send timeout")
        except Exception as e:
            print(e)

    def check_allow_redirects(self, event):
        global immediate_data
        is_selected = MenuFactory.button_selected(event)
        if is_selected != immediate_data['settings'][2]:
            self.update_setting(2, is_selected, "allow redirects")

    def check_sync_last_byte(self, event):
        global immediate_data
        is_selected = MenuFactory.button_selected(event)
        if is_selected != immediate_data['settings'][3]:
            self.update_setting(3, is_selected, "allow redirects")

    def resend_batches(self, event):
        global _storedRequests
        if _storedRequests is not None:
            self.sen

    # helper method for two methods above
    def update_setting(self, index, new_value, text):
        global immediate_data
        success = True
        print("> Updating {}..".format(text))
        old_value = immediate_data['settings'][index]
        immediate_data['settings'][index] = new_value
        if MenuFactory.set_immediate_mode_settings(
            {'settings': immediate_data['settings']}):
            print("> Success!")
        else:
            print("> Failed!")
            immediate_data['settings'][index] = old_value
            success = False
        return success

    # for ITab
    def getTabCaption(self):
        return "CompuRacer"

    # for ITab
    def getUiComponent(self):
        return self._main_splitpane

    # def getHttpService(self):
    #     global _storedRequest
    #     return _storedRequest.getHttpService()
    #
    # def getRequest(self):
    #     global _storedRequest
    #     return _storedRequest.getRequest()
    #
    # def getResponse(self):
    #     global _storedRequest
    #     return _storedRequest.getResponse()

    def start_alive_checker(self):
        self.t = threading.Thread(name='Alive checker',
                                  target=self.alive_checker)
        self.t.start()

    def closest_match(self, number, list_of_numbers):
        return min(list(zip(list_of_numbers, range(len(list_of_numbers)))),
                   key=lambda item: (abs(item[0] - number), item[1]))

    def alive_checker(self):
        global compuRacer_ip, compuRacer_port, alive_check_path, racer_alive, immediate_mode, compuracer_communication_lock
        unloaded = False
        old_alive = racer_alive
        parallel_req_options = [2, 3, 4, 5, 10, 15, 20, 25, 50, 100]
        send_time_options = [3, 5, 10, 20, 50, 100]
        while not unloaded:
            try:
                with compuracer_communication_lock:
                    response = requests.get("http://{}:{}/{}".format(
                        compuRacer_ip, compuRacer_port, alive_check_path),
                                            timeout=2)
                    racer_alive = response and response.status_code and response.status_code == 200
                    success, mode, settings = MenuFactory.get_immediate_mode_settings(
                    )
                    if success:
                        immediate_data['mode'] = mode
                        immediate_data['settings'] = settings

                        # update UI button states
                        immediate_data_ui_elements[
                            "parallel_requests"].setSelectedIndex(
                                self.closest_match(
                                    immediate_data['settings'][0],
                                    parallel_req_options)[1])
                        immediate_data_ui_elements[
                            "allow_redirects"].setSelected(
                                bool(immediate_data['settings'][2]))
                        immediate_data_ui_elements[
                            "sync_last_byte"].setSelected(
                                bool(immediate_data['settings'][3]))
                        immediate_data_ui_elements[
                            "send_timeout"].setSelectedIndex(
                                self.closest_match(
                                    immediate_data['settings'][4],
                                    send_time_options)[1])

            except Exception as e:
                # it surely did not work
                racer_alive = False
                print(e)
            if racer_alive and not old_alive:
                print("> Racer is now alive!")
                MenuFactory.set_state_of_all_buttons(True)
                old_alive = True
            elif not racer_alive and old_alive:
                print("> Racer became dead!")
                MenuFactory.set_state_of_all_buttons(False)
                old_alive = False
            time.sleep(5)
            if not self.loaded:
                unloaded = True

    def extensionUnloaded(self):
        print("\n> Unloading..")
        self.loaded = False
        self.t.join()
        print("> Done.")
class GUI_TestWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    # TODO: Update this for your UI
    def checkBoxEvent(self, event):
        if self.Exec_Program_CB.isSelected():
            self.local_settings.setSetting('Exec_Prog_Flag', 'true')
            self.Program_Executable_TF.setEnabled(True)
            self.Find_Program_Exec_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Exec_Prog_Flag', 'false')
            self.Program_Executable_TF.setText("")
            self.Program_Executable_TF.setEnabled(False)
            self.Find_Program_Exec_BTN.setEnabled(False)

        if self.Imp_File_CB.isSelected():
            self.local_settings.setSetting('Imp_File_Flag', 'true')
            self.File_Imp_TF.setEnabled(True)
            self.Find_Imp_File_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Imp_File_Flag', 'false')
            self.File_Imp_TF.setText("")
            self.local_settings.setSetting('File_Imp_TF', "")
            self.File_Imp_TF.setEnabled(False)
            self.Find_Imp_File_BTN.setEnabled(False)

    def keyPressed(self, event):
        self.local_settings.setSetting('Area', self.area.getText()) 

    def onchange_cb(self, event):
        self.local_settings.setSetting('ComboBox', event.item) 
        #self.Error_Message.setText(event.item)

    def onchange_lb(self, event):
        self.local_settings.setSetting('ListBox', "")
        list_selected = self.List_Box_LB.getSelectedValuesList()
        self.local_settings.setSetting('ListBox', str(list_selected))      
        # if (len(list_selected) > 0):
            # self.Error_Message.setText(str(list_selected))
        # else:
            # self.Error_Message.setText("")

    def onClick(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("SQLite", ["sqlite"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Select SQLite")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           if self.File_Imp_TF.isEnabled():
              self.File_Imp_TF.setText(Canonical_file)
              self.local_settings.setSetting('File_Imp_TF', Canonical_file)
           else:
              self.local_settings.setSetting('ExecFile', Canonical_file)
              self.Program_Executable_TF.setText(Canonical_file)

    # TODO: Update this for your UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Exec_Program_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Exec_Program_CB ) 

        self.Program_Executable_TF = JTextField(20) 
        self.Program_Executable_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick)
        self.Find_Program_Exec_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Imp_File_CB = JCheckBox( "Import File", actionPerformed=self.checkBoxEvent) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Imp_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Imp_File_CB ) 

        self.File_Imp_TF = JTextField(20) 
        self.File_Imp_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.File_Imp_TF, self.gbcPanel0 ) 
        self.panel0.add( self.File_Imp_TF ) 

        self.Find_Imp_File_BTN = JButton( "Find File", actionPerformed=self.onClick) 
        self.Find_Imp_File_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Imp_File_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 7 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Find_Imp_File_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Imp_File_BTN ) 

        self.Check_Box_CB = JCheckBox( "Check Box 1", actionPerformed=self.checkBoxEvent) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Check_Box_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Box_CB ) 

        self.dataComboBox_CB = ("Chocolate", "Ice Cream", "Apple Pie") 
        self.ComboBox_CB = JComboBox( self.dataComboBox_CB)
        self.ComboBox_CB.itemStateChanged = self.onchange_cb        
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.ComboBox_CB, self.gbcPanel0 ) 
        self.panel0.add( self.ComboBox_CB ) 
        
        self.dataList_Box_LB = ("Chocolate", "Ice Cream", "Apple Pie", "Pudding", "Candy" )
        self.List_Box_LB = JList( self.dataList_Box_LB, valueChanged=self.onchange_lb)
        #self.List_Box_LB.itemStateChanged = self.onchange_lb
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        # self.Radio_Button_RB = JRadioButton( "Radio Button"  ) 
        # self.rbgPanel0.add( self.Radio_Button_RB ) 
        # self.gbcPanel0.gridx = 7 
        # self.gbcPanel0.gridy = 17
        # self.gbcPanel0.gridwidth = 1 
        # self.gbcPanel0.gridheight = 1 
        # self.gbcPanel0.fill = GridBagConstraints.BOTH 
        # self.gbcPanel0.weightx = 1 
        # self.gbcPanel0.weighty = 0 
        # self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        # self.gbPanel0.setConstraints( self.Radio_Button_RB, self.gbcPanel0 ) 
        # self.panel0.add( self.Radio_Button_RB ) 

        # self.Label_1 = JLabel( "Error Message:") 
        # self.Label_1.setEnabled(True)
        # self.gbcPanel0.gridx = 2 
        # self.gbcPanel0.gridy = 19
        # self.gbcPanel0.gridwidth = 1 
        # self.gbcPanel0.gridheight = 1 
        # self.gbcPanel0.fill = GridBagConstraints.BOTH 
        # self.gbcPanel0.weightx = 1 
        # self.gbcPanel0.weighty = 0 
        # self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        # self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        # self.panel0.add( self.Label_1 ) 
		
        # self.Error_Message = JLabel( "") 
        # self.Error_Message.setEnabled(True)
        # self.gbcPanel0.gridx = 6
        # self.gbcPanel0.gridy = 19
        # self.gbcPanel0.gridwidth = 1 
        # self.gbcPanel0.gridheight = 1 
        # self.gbcPanel0.fill = GridBagConstraints.BOTH 
        # self.gbcPanel0.weightx = 1 
        # self.gbcPanel0.weighty = 0 
        # self.gbcPanel0.anchor = GridBagConstraints.NORTH
        # self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        # self.panel0.add( self.Error_Message ) 
		
        self.add(self.panel0)

    # TODO: Update this for your UI
    def customizeComponents(self):
        self.Exec_Program_CB.setSelected(self.local_settings.getSetting('Exec_Prog_Flag') == 'true')
        self.Imp_File_CB.setSelected(self.local_settings.getSetting('Imp_File_Flag') == 'true')
        self.Check_Box_CB.setSelected(self.local_settings.getSetting('Check_Box_1') == 'true')

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #7
0
class BurpExtender(IBurpExtender, IExtensionStateListener, ITab,
                   IHttpListener):
    def __init__(self):
        self.allEndpoints = []
        self.currentEndpoint = 0
        self.aws_access_key_id = ''
        self.aws_secret_accesskey = ''
        self.enabled_regions = {}

    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.helpers
        self.isEnabled = False

        callbacks.registerHttpListener(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.setExtensionName(EXT_NAME)
        callbacks.addSuiteTab(self)

    def getTargetProtocol(self):
        if self.https_button.isSelected() == True:
            return 'https'
        else:
            return 'http'

    def getRegions(self):
        self.enabled_regions = {}
        for region in AVAIL_REGIONS:
            cur_region = region.replace('-', '_')
            cur_region = cur_region + '_status'
            region_status = getattr(self, cur_region)
            if region_status.isSelected():
                #dict to contain the running regions and API gateway IDs
                self.enabled_regions.update({region: ''})
        return

#AWS functions

#Uses boto3 to test the AWS keys and make sure they are valid NOT IMPLEMENTED

    def testKeys(self):
        return

    #Uses boto3 to spin up an API Gateway
    def startAPIGateway(self):
        self.getRegions()
        for region in self.enabled_regions.keys():
            self.awsclient = boto3.client(
                'apigateway',
                aws_access_key_id=self.access_key.text,
                aws_secret_access_key=self.secret_key.text,
                region_name=region)

            self.create_api_response = self.awsclient.create_rest_api(
                name=API_NAME, endpointConfiguration={'types': [
                    'REGIONAL',
                ]})

            get_resource_response = self.awsclient.get_resources(
                restApiId=self.create_api_response['id'])

            self.restAPIId = self.create_api_response['id']
            self.enabled_regions[region] = self.restAPIId

            create_resource_response = self.awsclient.create_resource(
                restApiId=self.create_api_response['id'],
                parentId=get_resource_response['items'][0]['id'],
                pathPart='{proxy+}')

            self.awsclient.put_method(
                restApiId=self.create_api_response['id'],
                resourceId=get_resource_response['items'][0]['id'],
                httpMethod='ANY',
                authorizationType='NONE',
                requestParameters={
                    'method.request.path.proxy': True,
                    'method.request.header.X-My-X-Forwarded-For': True
                })

            self.awsclient.put_integration(
                restApiId=self.create_api_response['id'],
                resourceId=get_resource_response['items'][0]['id'],
                type='HTTP_PROXY',
                httpMethod='ANY',
                integrationHttpMethod='ANY',
                uri=self.getTargetProtocol() + '://' + self.target_host.text +
                '/',
                connectionType='INTERNET',
                requestParameters={
                    'integration.request.path.proxy':
                    'method.request.path.proxy',
                    'integration.request.header.X-Forwarded-For':
                    'method.request.header.X-My-X-Forwarded-For'
                })

            self.awsclient.put_method(
                restApiId=self.create_api_response['id'],
                resourceId=create_resource_response['id'],
                httpMethod='ANY',
                authorizationType='NONE',
                requestParameters={
                    'method.request.path.proxy': True,
                    'method.request.header.X-My-X-Forwarded-For': True
                })

            self.awsclient.put_integration(
                restApiId=self.create_api_response['id'],
                resourceId=create_resource_response['id'],
                type='HTTP_PROXY',
                httpMethod='ANY',
                integrationHttpMethod='ANY',
                uri=self.getTargetProtocol() + '://' + self.target_host.text +
                '/{proxy}',
                connectionType='INTERNET',
                requestParameters={
                    'integration.request.path.proxy':
                    'method.request.path.proxy',
                    'integration.request.header.X-Forwarded-For':
                    'method.request.header.X-My-X-Forwarded-For'
                })

            self.deploy_response = self.awsclient.create_deployment(
                restApiId=self.restAPIId, stageName=STAGE_NAME)

            self.allEndpoints.append(self.restAPIId + '.execute-api.' +
                                     region + '.amazonaws.com')

            self.usage_response = self.awsclient.create_usage_plan(
                name='burpusage',
                description=self.restAPIId,
                apiStages=[{
                    'apiId': self.restAPIId,
                    'stage': STAGE_NAME
                }])

        #Print out some info to burp console
        print 'Following regions and API IDs started:'
        print self.enabled_regions
        print 'List of endpoints being used:'
        print self.allEndpoints
        return

    #Uses boto3 to delete the API Gateway
    def deleteAPIGateway(self):
        if self.enabled_regions:
            for region in self.enabled_regions.keys():
                self.awsclient = boto3.client(
                    'apigateway',
                    aws_access_key_id=self.access_key.text,
                    aws_secret_access_key=self.secret_key.text,
                    region_name=region)

                response = self.awsclient.delete_rest_api(
                    restApiId=self.enabled_regions[region])
                print response
        self.enabled_regions = {}
        self.allEndpoints = []
        return

    #Called on "save" button click to save the settings
    def saveKeys(self, event):
        aws_access_key_id = self.access_key.text
        aws_secret_access_key = self.secret_key.text
        self.callbacks.saveExtensionSetting("aws_access_key_id",
                                            aws_access_key_id)
        self.callbacks.saveExtensionSetting("aws_secret_access_key",
                                            aws_secret_access_key)
        return

    #Called on "Enable" button click to spin up the API Gateway
    def enableGateway(self, event):
        self.startAPIGateway()
        self.status_indicator.text = ENABLED
        self.isEnabled = True
        self.enable_button.setEnabled(False)
        self.secret_key.setEnabled(False)
        self.access_key.setEnabled(False)
        self.target_host.setEnabled(False)
        self.disable_button.setEnabled(True)
        return

    #Called on "Disable" button click to delete API Gateway
    def disableGateway(self, event):
        self.deleteAPIGateway()
        self.status_indicator.text = DISABLED
        self.isEnabled = False
        self.enable_button.setEnabled(True)
        self.secret_key.setEnabled(True)
        self.access_key.setEnabled(True)
        self.target_host.setEnabled(True)
        self.disable_button.setEnabled(False)
        return

    def getCurrEndpoint():

        return

    #Traffic redirecting
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        # only process requests
        if not messageIsRequest or not self.isEnabled:
            return

        # get the HTTP service for the request
        httpService = messageInfo.getHttpService()

        #Modify the request host, host header, and path to point to the new API endpoint
        #Should always use HTTPS because API Gateway only uses HTTPS
        if ':' in self.target_host.text:  #hacky fix for https://github.com/RhinoSecurityLabs/IPRotate_Burp_Extension/issues/14
            host_no_port = self.target_host.text.split(':')[0]

        else:
            host_no_port = self.target_host.text

        if (host_no_port == httpService.getHost()):
            #Cycle through all the endpoints each request until then end of the list is reached
            if self.currentEndpoint < len(self.allEndpoints) - 1:
                self.currentEndpoint += 1
            #Reset to 0 when end it reached
            else:
                self.currentEndpoint = 0

            messageInfo.setHttpService(
                self.helpers.buildHttpService(
                    self.allEndpoints[self.currentEndpoint], 443, True))

            requestInfo = self.helpers.analyzeRequest(messageInfo)
            new_headers = requestInfo.headers

            #Update the path to point to the API Gateway path
            req_head = new_headers[0]
            #hacky fix for https://github.com/RhinoSecurityLabs/IPRotate_Burp_Extension/issues/14
            if 'http://' in req_head or 'https://' in req_head:
                cur_path = re.findall('https?:\/\/.*?\/(.*) ', req_head)[0]
                new_headers[0] = re.sub(
                    ' (.*?) ', " /" + STAGE_NAME + "/" + cur_path + " ",
                    req_head)

            else:
                new_headers[0] = re.sub(' \/', " /" + STAGE_NAME + "/",
                                        req_head)

            #Replace the Host header with the Gateway host
            for header in new_headers:
                if header.startswith('Host: '):
                    host_header_index = new_headers.index(header)
                    new_headers[
                        host_header_index] = 'Host: ' + self.allEndpoints[
                            self.currentEndpoint]

            #Update the headers insert the existing body
            body = messageInfo.request[requestInfo.getBodyOffset(
            ):len(messageInfo.request)]
            messageInfo.request = self.helpers.buildHttpMessage(
                new_headers, body)

    #Tab name
    def getTabCaption(self):
        return EXT_NAME

    #Handle extension unloading
    def extensionUnloaded(self):
        self.deleteAPIGateway()
        return

    #Layout the UI
    def getUiComponent(self):
        aws_access_key_id = self.callbacks.loadExtensionSetting(
            "aws_access_key_id")
        aws_secret_accesskey = self.callbacks.loadExtensionSetting(
            "aws_secret_access_key")
        if aws_access_key_id:
            self.aws_access_key_id = aws_access_key_id
        if aws_secret_accesskey:
            self.aws_secret_accesskey = aws_secret_accesskey

        self.panel = JPanel()

        self.main = JPanel()
        self.main.setLayout(BoxLayout(self.main, BoxLayout.Y_AXIS))

        self.access_key_panel = JPanel()
        self.main.add(self.access_key_panel)
        self.access_key_panel.setLayout(
            BoxLayout(self.access_key_panel, BoxLayout.X_AXIS))
        self.access_key_panel.add(JLabel('Access Key: '))
        self.access_key = JTextField(self.aws_access_key_id, 25)
        self.access_key_panel.add(self.access_key)

        self.secret_key_panel = JPanel()
        self.main.add(self.secret_key_panel)
        self.secret_key_panel.setLayout(
            BoxLayout(self.secret_key_panel, BoxLayout.X_AXIS))
        self.secret_key_panel.add(JLabel('Secret Key: '))
        self.secret_key = JPasswordField(self.aws_secret_accesskey, 25)
        self.secret_key_panel.add(self.secret_key)

        self.target_host_panel = JPanel()
        self.main.add(self.target_host_panel)
        self.target_host_panel.setLayout(
            BoxLayout(self.target_host_panel, BoxLayout.X_AXIS))
        self.target_host_panel.add(JLabel('Target host: '))
        self.target_host = JTextField('ifconfig.io', 25)
        self.target_host_panel.add(self.target_host)

        self.buttons_panel = JPanel()
        self.main.add(self.buttons_panel)
        self.buttons_panel.setLayout(
            BoxLayout(self.buttons_panel, BoxLayout.X_AXIS))
        self.save_button = JButton('Save Keys', actionPerformed=self.saveKeys)
        self.buttons_panel.add(self.save_button)
        self.enable_button = JButton('Enable',
                                     actionPerformed=self.enableGateway)
        self.buttons_panel.add(self.enable_button)
        self.disable_button = JButton('Disable',
                                      actionPerformed=self.disableGateway)
        self.buttons_panel.add(self.disable_button)
        self.disable_button.setEnabled(False)

        self.protocol_panel = JPanel()
        self.main.add(self.protocol_panel)
        self.protocol_panel.setLayout(
            BoxLayout(self.protocol_panel, BoxLayout.Y_AXIS))
        self.protocol_panel.add(JLabel("Target Protocol:"))
        self.https_button = JRadioButton("HTTPS", True)
        self.http_button = JRadioButton("HTTP", False)
        self.protocol_panel.add(self.http_button)
        self.protocol_panel.add(self.https_button)
        buttongroup = ButtonGroup()
        buttongroup.add(self.https_button)
        buttongroup.add(self.http_button)

        self.regions_title = JPanel()
        self.main.add(self.regions_title)
        self.regions_title.add(JLabel("Regions to launch API Gateways in:"))

        self.regions_panel = JPanel()
        self.main.add(self.regions_panel)
        glayout = GridLayout(4, 3)
        self.regions_panel.setLayout(glayout)
        for region in AVAIL_REGIONS:
            cur_region = region.replace('-', '_')
            cur_region = cur_region + '_status'
            if cur_region.startswith(
                    "ap") and cur_region != 'ap_east_1_status':
                setattr(self, cur_region, JCheckBox(region, True))
            else:
                setattr(self, cur_region, JCheckBox(region, False))
            attr = getattr(self, cur_region)
            self.regions_panel.add(attr)

        self.status = JPanel()
        self.main.add(self.status)
        self.status.setLayout(BoxLayout(self.status, BoxLayout.X_AXIS))
        self.status_indicator = JLabel(DISABLED, JLabel.CENTER)
        self.status.add(self.status_indicator)

        self.panel.add(self.main)
        return self.panel
Beispiel #8
0
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab,
                   IExtensionStateListener, IMessageEditorController,
                   IHttpListener):
    '''
    IBurpExtender:               Hook into burp and inherit base classes
    ITab:                        Create new tabs inside burp
    IMessageEditorTabFactory:    Access createNewInstance
    '''
    def registerExtenderCallbacks(self, callbacks):

        # Set encoding to utf-8 to avoid some errors
        reload(sys)
        sys.setdefaultencoding('utf8')

        # Keep a reference to callback object and helper object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # Set the extension name that shows in the burp extension menu
        callbacks.setExtensionName("InjectionScanner")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._logLock = Lock()
        self._httpLock = Lock()

        # The length of the basis used to fetch abnormal data, default to zero
        self._basisLen = 0

        # 1: {POST. GET}; 2: {urlencoded, json, xml}
        self._postGet = 'NaN'
        self._dataType = 'NaN'

        # Scan list
        self._simpleList = [
            '\'', '\"', '/', '/*', '#', ')', '(', ')\'', '(\'', 'and 1=1',
            'and 1=2', 'and 1>2', 'and 12', '+', 'and+12', '/**/and/**/1'
        ]
        self._xmlList = ['a', 'b', 'c', 'd', 'e']  # Not setted

        # Response mutex: True = is blocking; False = free to go
        # self._mutexR = False

        # Other classes instance
        self._dataTable = Guis_DefaultTM()
        self._logTable = Guis_AbstractTM(self)
        self._xh = XMLHandler()
        listeners = Guis_Listeners(self, self._logTable)
        '''
        Setting GUIs
        '''
        # Divide the whole pane two: one upper and one lower pane
        self._mainSplitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._mainSplitpane.setResizeWeight(0.4)

        # Initizlize request table
        dataTable = JTable(self._dataTable)
        dataScrollPane = JScrollPane(dataTable)
        dataScrollPane.setPreferredSize(Dimension(0, 125))
        self._dataTable.addTableModelListener(listeners)

        # Initialize log table
        logTable = Guis_LogTable(self._logTable)
        logScrollPane = JScrollPane(logTable)
        logScrollPane.setPreferredSize(Dimension(0, 125))

        # Split the upper pane to two panes
        tableSplitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        tableSplitpane.setResizeWeight(0.5)

        # Set the data table to the left and log to the right
        tableSplitpane.setLeftComponent(dataScrollPane)
        tableSplitpane.setRightComponent(logScrollPane)

        # Tabs with request/response viewers
        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())

        # Create buttons that do operation with the test
        self._basisLabel = JLabel('Basis: ' + str(self._basisLen))
        self._levelLabel = JLabel('Level:')
        self._setBasisButton = JButton('Set Basis')
        self._hitOnceButton = JButton('Hit Once')
        self._autoScanButton = JButton('Auto Scan')
        self._clearLogButton = JButton('Clear Log')
        self._cancelButton = JButton('Cancel')
        self._levelSelection = JComboBox()

        self._levelSelection.addItem('1')
        self._levelSelection.addItem('2')
        self._levelSelection.addItem('3')
        self._hitOnceButton.addActionListener(listeners)
        self._autoScanButton.addActionListener(listeners)
        self._clearLogButton.addActionListener(listeners)
        self._setBasisButton.addActionListener(listeners)
        self._cancelButton.addActionListener(listeners)
        self._basisLabel.setPreferredSize(Dimension(100, 20))

        # Create bottom pane for holding the buttons
        buttonPane = JPanel()
        buttonPane.setLayout(BorderLayout())
        centerPane = JPanel()
        leftPane = JPanel()
        rightPane = JPanel()
        leftPane.add(self._basisLabel)
        centerPane.add(self._setBasisButton)
        centerPane.add(self._hitOnceButton)
        centerPane.add(self._autoScanButton)
        centerPane.add(self._cancelButton)
        centerPane.add(self._clearLogButton)
        rightPane.add(self._levelLabel)
        rightPane.add(self._levelSelection)
        buttonPane.add(centerPane, BorderLayout.CENTER)
        buttonPane.add(leftPane, BorderLayout.WEST)
        buttonPane.add(rightPane, BorderLayout.EAST)

        # Create and set the bottom panel that holds viewers and buttons
        utilPane = JPanel()
        utilPane.setLayout(BorderLayout())
        utilPane.add(tabs, BorderLayout.CENTER)
        utilPane.add(buttonPane, BorderLayout.SOUTH)

        self._mainSplitpane.setLeftComponent(tableSplitpane)
        self._mainSplitpane.setRightComponent(utilPane)

        # Customize UI components
        callbacks.customizeUiComponent(self._mainSplitpane)
        callbacks.customizeUiComponent(dataTable)
        callbacks.customizeUiComponent(dataScrollPane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(logScrollPane)
        callbacks.customizeUiComponent(tabs)
        callbacks.customizeUiComponent(buttonPane)
        callbacks.customizeUiComponent(utilPane)
        callbacks.customizeUiComponent(self._basisLabel)
        callbacks.customizeUiComponent(self._setBasisButton)
        callbacks.customizeUiComponent(self._hitOnceButton)
        callbacks.customizeUiComponent(self._autoScanButton)
        callbacks.customizeUiComponent(self._clearLogButton)
        callbacks.customizeUiComponent(self._levelSelection)
        callbacks.customizeUiComponent(self._cancelButton)

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

        # Register the context menu and message editor for new tabs
        callbacks.registerContextMenuFactory(self)

        # Register as a HTTP listener
        callbacks.registerHttpListener(self)

        return

    '''
    ITab implementation
    '''

    def getTabCaption(self):
        return 'InjectionScanner'

    def getUiComponent(self):
        return self._mainSplitpane

    '''
    IContextMenuFactory implementation
    '''

    def createMenuItems(self, invocation):
        menu = []

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

        # Message viewer request will show menu item if selected by the user
        if ctx == 0 or ctx == 2:
            menu.append(
                swing.JMenuItem("Send to InjectionScanner",
                                None,
                                actionPerformed=lambda x, inv=invocation: self.
                                sendToExtender(inv)))

        return menu if menu else None

    '''
    IMessageEditorController Implementation
    '''

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

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

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

    '''
    IHttpListener implementation
    '''

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):

        # Skip this function if the message is request
        if messageIsRequest:
            return

        # Lock the log entry in case race condition
        self._logLock.acquire()
        row = self._log.size()

        # Fetch request message
        requestBody = messageInfo.getRequest()
        requestInfo = self._helpers.analyzeResponse(requestBody)
        requestHeaders = requestInfo.getHeaders()
        if self._postGet == 'POST':
            requestData = self._helpers.bytesToString(
                requestBody[requestInfo.getBodyOffset():])
        elif self._postGet == 'GET':
            for header in requestHeaders:

                if 'GET' in header:
                    # If the request is GET, update the GET data
                    requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE)
                    requestUrl = re.sub('\sHTTP/1.1\S*', '', requestUrl,
                                        re.IGNORECASE)

                    if '?' in requestUrl:
                        requestData = re.sub('\S*\?', '', requestUrl,
                                             re.IGNORECASE)

                    else:
                        print('processHttpMessage: no parameter in GET url')
        else:
            print('processHttpMessage: _postGet not defined')
            self._logLock.release()
            return

        # Fetch the http type (GET/POST)
        httpType = requestHeaders[0].split(' ')

        # Fetch response message
        responseBody = messageInfo.getResponse()
        responseInfo = self._helpers.analyzeResponse(responseBody)
        responseHeaders = responseInfo.getHeaders()
        self._responseLength = ''

        # Fetch the content length
        self._responseLength = self.fetchContentLength(responseHeaders)

        # If the response message is auto-generated, ignore it. If not, add it into the log list
        if self._callbacks.getToolName(toolFlag) != 'Proxy':

            self._log.add(
                LogEntry(httpType[0], requestData,
                         self._callbacks.saveBuffersToTempFiles(messageInfo),
                         self._responseLength))
            self._logTable.fireTableRowsInserted(row, row)

        self._logLock.release()

    '''
    Fetch content length from the headers given
    '''

    def fetchContentLength(self, fromHeaders):

        for header in fromHeaders:
            if re.search('^Content-Length', header, re.IGNORECASE) is not None:
                return re.sub('^Content-Length\:\s+', '', header,
                              re.IGNORECASE)

    '''
    When the user select 'Send to InjectionScanner', call this function
    '''

    def sendToExtender(self, invocation):

        # Init/reset request data before sending to extender
        self.initRequestInfo()

        try:
            # Initialize basic information
            invMessage = invocation.getSelectedMessages()
            requestMessage = invMessage[0]
            requestInfo = self._helpers.analyzeRequest(requestMessage)
            self._requestBody = requestMessage.getRequest()

            # Set the _currentlyDisplayedItem so each time the data is sent to the extender
            self._currentlyDisplayedItem = self._callbacks.saveBuffersToTempFiles(
                requestMessage)

            # Fetch the request data
            bodyLen = len(self._helpers.bytesToString(self._requestBody))
            if requestInfo.getBodyOffset() < bodyLen:
                self._requestData = self._helpers.bytesToString(
                    self._requestBody[requestInfo.getBodyOffset():])
            elif requestInfo.getBodyOffset() == bodyLen:
                self._requestData = ''
            else:
                print('sendToExtender: body length < body offset')

            # Fetch the headers and Http service
            requestHeaders = list(requestInfo.getHeaders())
            self._httpService = requestMessage.getHttpService()

            # Initialize POST/GET identifier and User-Agent
            for header in requestHeaders:
                if re.search('^POST', header, re.IGNORECASE) is not None:
                    self._postGet = 'POST'

                elif re.search('^GET', header, re.IGNORECASE) is not None:
                    self._postGet = 'GET'

                    # If the request is GET, initialize the url and GET data
                    self._requestUrl = re.sub('^GET\s+', '', header,
                                              re.IGNORECASE)
                    self._requestUrl = re.sub('\sHTTP/1.1\S*', '',
                                              self._requestUrl, re.IGNORECASE)

                    if '?' in self._requestUrl:
                        self._requestDataGet = re.sub('\S*\?', '',
                                                      self._requestUrl,
                                                      re.IGNORECASE)

                    else:
                        print('sendToExtender: no parameter in GET url')

                # If the request if POST, fetch the request data type by content type
                if self._postGet == 'POST' and re.search(
                        '^Content-Type', header, re.IGNORECASE) is not None:

                    contentType = re.sub('^Content-Type', '', header,
                                         re.IGNORECASE)
                    if 'urlencoded' in contentType:
                        self._dataType = 'urlencoded'

                    elif 'json' in contentType:
                        self._dataType = 'json'

                    elif 'xml' in contentType or 'http' in conentType:
                        self._dataType = 'xml'

                    else:
                        print(
                            'sendToExtender: _dataType is not supported, do not scan'
                        )

                # Initialze the User-Agent if it exists
                if re.search('^User-Agent', header, re.IGNORECASE) is not None:
                    self._userAgent = re.sub('^User-Agent\:\s+', '', header,
                                             re.IGNORECASE)

            # If there's no content type in the header,fetch from data
            if self._postGet == 'POST' and self._dataType == '':

                if self._requestData != '':

                    if self._requestData[
                            0] == '{' and '}' in self._requestData and ':' in self._requestData:
                        self._dataType = 'json'

                    elif self._requestData[0] == '<' and self._requestData[
                            -1] == '>':
                        self._dataType = 'xml'

                    else:
                        self._dataType = 'urlencoded'

                else:
                    print(
                        'sendToExtender: _postGet is POST but _requestData is null'
                    )

            # Clear the table before adding elements
            self._dataTable.setRowCount(0)

            # Update request viewer
            self.updateRequestViewer()

            # Fill request data
            self.fillRequestData()

        except Exception as e:
            print(e)

    '''
    Fill the data into the request table
    '''

    def fillRequestData(self):

        # If _postGet is GET, also adds URL to the table
        if self._postGet == 'GET':

            dataList = self._requestDataGet.split('&')
            for data in dataList:

                if '=' in data:
                    x = data.split('=', 1)
                    self._dataDict[str(x[0])] = str(x[1])
                    self._dataTable.addRow([str(x[0]), str(x[1])])
                    self._dataLen += 1

            self._dataTable.addRow(['URL', self._requestUrl])
            self._UrlRow = self._dataLen

            if self._userAgent != '':
                self._dataTable.addRow(['User-Agent', self._userAgent])

        elif self._postGet == 'POST':

            if self._dataType == 'urlencoded':

                dataList = self._requestData.split('&')
                for data in dataList:

                    if '=' in data:
                        x = data.split('=', 1)
                        self._dataDict[str(x[0])] = str(x[1])
                        self._dataTable.addRow([str(x[0]), str(x[1])])
                        self._dataLen += 1

            elif self._dataType == 'json':

                self._dataDict = json.loads(self._requestData)
                for key in self._dataDict:

                    # Convert '"' to '\"' to be the same as that in the data
                    value = str(self._dataDict[key])
                    if '\"' in value:
                        value = value.replace('\"', '\\\"')
                    self._dataDict[key] = value

                    self._dataTable.addRow([str(key), self._dataDict[key]])
                    self._dataLen += 1

            elif self._dataType == 'xml':

                # Use xml package to convert the xml string to dict
                # Note1: the xml dict will be in reverse order
                # Note2: the arrtibute will also be added into dict, need to be pop
                # Note3: special characters like \" will be considered as "
                xml.sax.parseString(self._requestData, self._xh)
                self._attr = re.sub('\>(\S*\s*)*', '', self._requestData[1:],
                                    re.IGNORECASE)

                self._dataDict = self._xh.getDict()
                self._dataDict.pop(self._attr)

                for key in self._dataDict:
                    self._dataTable.addRow(
                        [str(key), str(self._dataDict[key])])
                    self._dataLen += 1

            else:
                print('fillRequestData: _dataType not defined')

            if self._userAgent != '':
                self._dataTable.addRow(['User-Agent', self._userAgent])
                self._savedUserAgent = self._userAgent

        else:
            print('fillRequestData: _postGet not defined')

    '''
    Receive & update the response after sending request to the server
    '''

    def receiveResponse(self):

        # Init/reset response data before receiving response
        self.initResponseInfo()

        # Launch the http thread
        self._httpThread = Thread(target=self.makeRequest,
                                  args=(
                                      self._httpService,
                                      self._requestBody,
                                  ))
        self._httpThread.start()

    '''
    Make Http request to a service
    '''

    def makeRequest(self, httpService, requestBody):
        self._httpLock.acquire()

        # Disable the hit buttons before starting the thread
        self._hitOnceButton.setEnabled(False)
        self._autoScanButton.setEnabled(False)

        self._responseMessage = self._callbacks.makeHttpRequest(
            httpService, requestBody)

        # Enable the hit buttons
        self._hitOnceButton.setEnabled(True)
        self._autoScanButton.setEnabled(True)

        # Unblock the mutex
        self._httpLock.release()

    '''
    updateRequestViewer
    '''

    def updateRequestViewer(self):
        self._requestViewer.setMessage(self.getRequest(), True)

    '''
    updateResponseViewer
    '''

    def updateResponseViewer(self):
        self._responseViewer.setMessage(self.getResponse(), False)

    '''
    Level 1 auto: only loop through the data, do not modify the 'submit' section
    '''

    def autoScan1(self):
        # TODO: Add a 'cancel' button to stop when the user think it takes too long
        # TODO: Add XML support
        if self._postGet == 'GET':

            for i in range(0, self._dataLen):

                title = self._dataTable.getValueAt(i, 0)
                baseValue = self._dataDict[title]

                for value in self._simpleList:

                    # TODO: update more value that should not be changed
                    if 'submit' not in title.lower(
                    ) and 'submit' not in self._dataDict[title].lower(
                    ) and 'search' not in title.lower(
                    ) and 'search' not in self._dataDict[title].lower():

                        # Update the table in case the loop interrupt in the middle
                        # Note that the URL will be automatically updated due to this code, so no need to manually update the URL section
                        self._dataTable.setValueAt(value, i, 1)

                        # Send & request the HTTP request/response
                        self.updateRequestViewer()
                        self.receiveResponse()

                # Reset the table
                self._dataTable.setValueAt(baseValue, i, 1)

        if self._postGet == 'POST':

            if self._dataType == 'urlencoded' or self._dataType == 'json':

                for i in range(0, self._dataLen):

                    title = self._dataTable.getValueAt(i, 0)
                    baseValue = self._dataDict[title]

                    if 'submit' in title.lower() or 'submit' in self._dataDict[
                            title].lower() or 'search' in title.lower(
                            ) or 'search' in self._dataDict[title].lower():
                        continue

                    for value in self._simpleList:

                        self._dataTable.setValueAt(value, i, 1)

                        self.updateRequestViewer()
                        self.receiveResponse()

                    # Reset the table
                    self._dataTable.setValueAt(baseValue, i, 1)

            elif self._dataType == 'xml':

                for i in range(0, self._dataLen):

                    title = self._dataTable.getValueAt(i, 0)
                    baseValue = self._dataDict[title]

                    for value in self._xmlList:

                        # Update the table in case the loop interrupt in the middle
                        self._dataTable.setValueAt(value, i, 1)

                        # Send & request the HTTP request/response
                        self.updateRequestViewer()
                        self.receiveResponse()

                    # Reset the table
                    self._dataTable.setValueAt(baseValue, i, 1)

    '''
    Level 2 auto: loop through the data as well as the user agent (if exist)
    '''

    def autoScan2(self):

        # If the User-Agent does not exist, only performs level 1 auto
        if self._userAgent != '':

            baseUserAgent = self._userAgent
            baseExpression = 'User-Agent: ' + baseUserAgent

            for value in self._simpleList:
                oldExpression = 'User-Agent: ' + self._userAgent
                newExpression = 'User-Agent: ' + value

                # Update the values accordingly
                requestBodyString = self._helpers.bytesToString(
                    self._requestBody)
                self._requestBody = requestBodyString.replace(
                    oldExpression, newExpression)
                self._userAgent = value

                self.updateRequestViewer()
                self.receiveResponse()

            # Reset the value back to original after each loop
            requestBodyString = self._helpers.bytesToString(self._requestBody)
            self._requestBody = requestBodyString.replace(
                newExpression, baseExpression)
            self._savedUserAgent = baseUserAgent
            self.updateRequestViewer()

        # Perform level 1 scan also
        self.autoScan1()

    '''
    Level 3 auto: Alpha: use the timer to perform blind insertion
    '''

    # TODO: 目前只支持GET/urlencoded,后续添加更多支持
    def autoScan3(self):

        self._timeReach = False
        timer = Timer(5, self.timeReach)

        # Modify the first element to perform blind injection
        title = self._dataTable.getValueAt(i, 0)
        oldExpression = title + '=' + self._dataDict[title]
        newExpression = title + '=' + '1\' and if(1=0,1, sleep(10)) --+'

        if self._postGet == 'GET':

            # Update the values accordingly
            requestBodyString = self._helpers.bytesToString(self._requestBody)
            self._requestBody = requestBodyString.replace(
                oldExpression, newExpression)
            self._requestDataGet = self._requestDataGet.replace(
                oldExpression, newExpression)
            self._requestUrl = self._requestUrl.replace(
                oldExpression, newExpression)
            self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+'
            self._requestModel.setValueAt('1\' and if(1=0,1, sleep(10)) --+',
                                          0, 1)

        elif self._postGet == 'POST':

            if self._dataType == 'urlencoded':

                # Update the values accordingly
                requestBodyString = self._helpers.bytesToString(
                    self._requestBody)
                self._requestBody = requestBodyString.replace(
                    oldExpression, newExpression)
                self._requestData = self._requestData.replace(
                    oldExpression, newExpression)
                self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+'
                self._requestModel.setValueAt(
                    '1\' and if(1=0,1, sleep(10)) --+', 0, 1)

            else:
                print('autoScan3: _dataType not supported')

        else:
            print('autoScan3: _postGet not defined')

        timer.start()

        self.updateRequestViewer()
        self.receiveResponse()

        # Print the result
        if self._timeReach:
            print('Delay scan succeed')
        else:
            print('Delay scan failed')

        # Cancel the timer
        timer.cancel()

    def timeReach(self):
        self._timeReach = True

    '''
    Fetch the 'abnormal' payloads that shows very different response length from the normal ones
    '''

    def getAbnormal(self, basis, coefficient):

        # If the basis is not set, do nothing
        abnormList = ArrayList()
        if basis == 0:
            return None

        # Fetch the abnormals from the log list
        for log in self._log:
            if float(log._responseLen) / float(basis) < coefficient or float(
                    basis) / float(log._responseLen) < coefficient:
                abnormList.append(log._payload)

        return abnormList

    '''
    Turn a simple dict of key/value pairs into XML
    '''

    def dictToXml(self, tag, d):

        elem = Element(tag)

        for key, val in d.items():
            child = Element(key)
            child.text = str(val)
            # Add element in reverse order so that the result is correct
            elem.insert(0, child)

        return elem

    '''
    initRequestInfo
    '''

    def initRequestInfo(self):
        self._postGet = ''
        self._userAgent = ''
        self._requestUrl = ''
        self._requestBody = ''
        self._requestData = ''
        self._requestDataGet = ''
        self._httpService = None
        self._dataDict = {}
        self._dataType = ''
        self._dataLen = 0
        self._attr = ''
        self._contentLength = 0
        self._currentlyDisplayedItem = None

    '''
    initResponseInfo
    '''

    def initResponseInfo(self):
        self._responseBody = None
        self._responseMessage = None
        self._responseLength = ''

    '''
    printRequest
    '''

    def printRequest(self):
        print('----------------')
        print(self._postGet)
        print('----------------')
        print(self._userAgent)
        print('----------------')
        print(self._requestUrl)
        print('----------------')
        print(self._requestBody)
        print('----------------')
        print(self._requestData)
        print('----------------')
        print(self._requestDataGet)
        print('----------------')
        print(self._httpService)
        print('----------------')
        print(self._dataDict)
        print('----------------')
        print(self._dataLen)
        print('----------------')
        print(self._attr)
        print('----------------')

    '''
    printResponse
    '''

    def printResponse(self):
        print('----------------')
        print(self._responseBody)
        print('----------------')
        print(self._responseMessage)
        print('----------------')
        print(self._responseLength)
        print('----------------')
class HashImageSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    def FindFTKTxtFile(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("ALL", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Find FTK Log File")
       
       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('FTKLogFile', Canonical_file)
           setSetting('FTKLogFile', Canonical_file)
           self.FTKLogFile_TF.setText(Canonical_file)

    def keyPressedMD5(self, event):  
        self.local_settings.setSetting('MD5Hash', self.MD5HashValue_TF.getText())

    def keyPressedSHA1(self, event):  
        self.local_settings.setSetting('SHA1Hash', self.SHA1HashValue_TF.getText())

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Label_1 = JLabel("MD5 Hash Value To Verify")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.MD5HashValue_TF = JTextField(20, focusLost=self.keyPressedMD5) 
        self.MD5HashValue_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.MD5HashValue_TF, self.gbcPanel0 ) 
        self.panel0.add( self.MD5HashValue_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_2 = JLabel("SHA1 Hash Value To Verify")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.SHA1HashValue_TF = JTextField(20, focusLost=self.keyPressedSHA1) 
        self.SHA1HashValue_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.SHA1HashValue_TF, self.gbcPanel0 ) 
        self.panel0.add( self.SHA1HashValue_TF ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_3 = JLabel("FTK Log File")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 

        self.FTKLogFile_TF = JTextField(20) 
        self.FTKLogFile_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.FTKLogFile_TF, self.gbcPanel0 ) 
        self.panel0.add( self.FTKLogFile_TF ) 

        self.FTKLogFile_BTN = JButton( "Find File", actionPerformed=self.FindFTKTxtFile)
        self.FTKLogFile_BTN.setEnabled(True)
        self.rbgPanel0.add( self.FTKLogFile_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.FTKLogFile_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.FTKLogFile_BTN ) 

        self.Label_4 = JLabel( "Message:") 
        self.Label_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 29
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_4, self.gbcPanel0 ) 
        self.panel0.add( self.Label_4 ) 
		
        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        pass
        
    # Return the settings used
    def getSettings(self):
        self.local_settings.setSetting('MD5Hash', self.MD5HashValue_TF.getText())
        self.local_settings.setSetting('SHA1Hash', self.SHA1HashValue_TF.getText())
        return self.local_settings
Beispiel #10
0
class AccountManagementGUI:
    def __init__(self):
        self.acctmanager = AccountManager()
        self.mainframe = JFrame("Account Manager")
        self.chatui = None
        self.headers = ["Account Name", "Status", "Autologin", "Gateway"]
        self.data = UneditableTableModel([], self.headers)
        self.table = JTable(self.data)
        self.table.columnSelectionAllowed = 0  # cannot select columns
        self.table.selectionMode = ListSelectionModel.SINGLE_SELECTION

        self.connectbutton = JButton("Connect", actionPerformed=self.connect)
        self.dconnbutton = JButton("Disconnect", actionPerformed=self.disconnect)
        self.deletebutton = JButton("Delete", actionPerformed=self.deleteAccount)
        self.buildpane()
        self.mainframe.pack()
        self.mainframe.show()

    def buildpane(self):
        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(self.connectbutton)
        buttons.add(self.dconnbutton)
        buttons.add(JButton("New", actionPerformed=self.addNewAccount))
        buttons.add(self.deletebutton)
        buttons.add(JButton("Quit", actionPerformed=self.quit))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(JScrollPane(self.table))
        mainpane.add(buttons)
        self.update()

    def update(self):
        self.data.setDataVector(self.acctmanager.getSnapShot(), self.headers)
        if self.acctmanager.isEmpty():
            self.deletebutton.setEnabled(0)
            self.connectbutton.setEnabled(0)
            self.dconnbutton.setEnabled(0)
        else:
            self.deletebutton.setEnabled(1)
            if not 1 in self.acctmanager.getConnectionInfo():  # all disconnected
                self.dconnbutton.setEnabled(0)
                self.connectbutton.setEnabled(1)
            elif not 0 in self.acctmanager.getConnectionInfo():  # all connected
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(0)
            else:
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(1)

    # callable button actions
    def connect(self, ae):
        print "Trying to connect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to connect to an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            if not self.chatui:
                self.chatui = twisted.words.im.jychat.JyChatUI()
            self.acctmanager.connect(acctname, self.chatui)
            self.update()

    def disconnect(self, ae):
        print "Trying to disconnect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to logoff an account but no account was selected."
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.disconnect(acctname)
            self.update()

    def addNewAccount(self, ae):
        print "Starting new account creation"
        NewAccountGUI(self).show()

    def deleteAccount(self, ae):
        print "Deleting account"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to delete an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.delAccount(acctname)
            self.update()

    def quit(self, ae):
        self.acctmanager.quit()
        sys.exit()
Beispiel #11
0
class BeautifierPanel(JPanel):
    def __init__(self):
        super(BeautifierPanel, self).__init__()
        self.setLayout(BorderLayout())

        self.beautifyTextArea = JTextArea(5, 10)
        self.beautifyTextArea.setLineWrap(True)
        self.beautifyTextArea.setDocument(self.CustomUndoPlainDocument())
        # The undo doesn't work well before replace text. Below is rough fix, so not need to know how undo work for now
        self.beautifyTextArea.setText(" ")
        self.beautifyTextArea.setText("")

        self.undoManager = UndoManager()
        self.beautifyTextArea.getDocument().addUndoableEditListener(
            self.undoManager)
        self.beautifyTextArea.getDocument().addDocumentListener(
            self.BeautifyDocumentListener(self))

        beautifyTextWrapper = JPanel(BorderLayout())
        beautifyScrollPane = JScrollPane(self.beautifyTextArea)
        beautifyTextWrapper.add(beautifyScrollPane, BorderLayout.CENTER)
        self.add(beautifyTextWrapper, BorderLayout.CENTER)

        self.beautifyButton = JButton("Beautify")
        self.beautifyButton.addActionListener(self.beautifyListener)
        self.undoButton = JButton("Undo")
        self.undoButton.addActionListener(self.undoListener)

        formatLabel = JLabel("Format:")
        self.formatsComboBox = JComboBox()
        for f in supportedFormats:
            self.formatsComboBox.addItem(f)

        self.statusLabel = JLabel("Status: Ready")
        preferredDimension = self.statusLabel.getPreferredSize()
        self.statusLabel.setPreferredSize(
            Dimension(preferredDimension.width + 20,
                      preferredDimension.height))
        self.sizeLabel = JLabel("0 B")
        preferredDimension = self.sizeLabel.getPreferredSize()
        self.sizeLabel.setPreferredSize(
            Dimension(preferredDimension.width + 64,
                      preferredDimension.height))
        self.sizeLabel.setHorizontalAlignment(SwingConstants.RIGHT)

        buttonsPanel = JPanel(FlowLayout())
        buttonsPanel.add(formatLabel)
        buttonsPanel.add(self.formatsComboBox)
        buttonsPanel.add(Box.createHorizontalStrut(10))
        buttonsPanel.add(self.beautifyButton)
        buttonsPanel.add(self.undoButton)

        bottomPanel = JPanel(BorderLayout())
        bottomPanel.add(self.statusLabel, BorderLayout.WEST)
        bottomPanel.add(buttonsPanel, BorderLayout.CENTER)
        bottomPanel.add(self.sizeLabel, BorderLayout.EAST)
        self.add(bottomPanel, BorderLayout.SOUTH)

        self.currentBeautifyThread = None

    class CustomUndoPlainDocument(PlainDocument):
        # Code from: https://stackoverflow.com/questions/24433089/jtextarea-settext-undomanager
        compoundEdit = CompoundEdit()

        def fireUndoableEditUpdate(self, e):
            if self.compoundEdit == None:
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).fireUndoableEditUpdate(e)
            else:
                self.compoundEdit.addEdit(e.getEdit())

        def replace(self, offset, length, text, attrs):
            if length == 0:
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).replace(offset, length, text, attrs)
            else:
                self.compoundEdit = CompoundEdit()
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).fireUndoableEditUpdate(
                          UndoableEditEvent(self, self.compoundEdit))
                super(BeautifierPanel.CustomUndoPlainDocument,
                      self).replace(offset, length, text, attrs)
                self.compoundEdit.end()
                self.compoundEdit = None

    def setText(self, text):
        self.beautifyTextArea.setText(text)

    def setRunningState(self):
        self.beautifyButton.setText("Cancel")
        self.undoButton.setEnabled(False)
        self.statusLabel.setText("Status: Running")

    def setReadyState(self):
        self.beautifyButton.setText("Beautify")
        self.undoButton.setEnabled(True)
        self.statusLabel.setText("Status: Ready")

    class BeautifyDocumentListener(DocumentListener):
        def __init__(self, beautifierPanel):
            super(BeautifierPanel.BeautifyDocumentListener, self).__init__()
            self.beautifierPanel = beautifierPanel

        def removeUpdate(self, e):
            self.updateSizeLabel()

        def insertUpdate(self, e):
            self.updateSizeLabel()

        def changedUpdate(self, e):
            pass

        def updateSizeLabel(self):
            length = len(self.beautifierPanel.beautifyTextArea.getText())
            if length >= 1024:
                length = "%.2f KB" % (length / 1024.0)
            else:
                length = "%d B" % length
            self.beautifierPanel.sizeLabel.setText(length)

    def beautifyListener(self, e):
        selectedFormat = self.formatsComboBox.getSelectedItem()
        data = self.beautifyTextArea.getText(
        )  # variable "data" is "unicode" type

        if self.currentBeautifyThread and self.currentBeautifyThread.isAlive():
            # TODO Need a graceful way to shutdown running beautify thread.
            self.currentBeautifyThread.callback = None
            self.currentBeautifyThread = None
            self.setReadyState()
        else:
            self.currentBeautifyThread = None
            self.setRunningState()

            def beautifyCallback(result):
                self.beautifyTextArea.setText(result)
                self.setReadyState()

            self.currentBeautifyThread = BeautifyThread(
                data, selectedFormat, beautifyCallback)
            self.currentBeautifyThread.start()

    def undoListener(self, e):
        if self.undoManager.canUndo():
            self.undoManager.undo()
Beispiel #12
0
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel
                                            ):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # Check to see if there are any entries that need to be populated from the database.
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;'
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString(
                        "Setting_Name") == "Volatility_Executable_Directory":
                    self.Program_Executable_TF.setText(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Directory(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Dir_Found(True)
                # if resultSet.getString("Setting_Name") == "Volatility_Version":
                # self.Version_CB.setSelectedItem(resultSet.getString("Setting_Value"))
            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):

        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = ""
            if (self.local_settings.getVolatility_Dir_Found()):
                SQL_Statement = 'Update settings set Setting_Value = "' + self.Program_Executable_TF.getText() + '"' + \
                                ' where setting_name = "Volatility_Executable_Directory";'
                # SQL_Statement2 = 'Update settings set Setting_Value = "' + self.Version_CB.getSelectedItem() + '"' + \
                # ' where setting_name = "Volatility_Version";'
            else:
                SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Executable_Directory", "' +  \
                                self.Program_Executable_TF.getText() + '");'
                # SQL_Statement2 = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Version", "' +  \
                # self.Version_CB.getSelectedItem() + '");'

            stmt.execute(SQL_Statement)
            # stmt.execute(SQL_Statement2)
            self.Error_Message.setText("Volatility Executable Directory Saved")
            self.local_settings.setVolatility_Directory(
                self.Program_Executable_TF.getText())
        except SQLException as e:
            self.Error_Message.setText(e.getMessage())
        stmt.close()
        dbConn.close()

    # When button to find file is clicked then open dialog to find the file and return it.
    def Find_Dir(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("All", ["*.*"])
        chooseFile.addChoosableFileFilter(filter)
        #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

        ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            Canonical_file = file.getCanonicalPath()
            #text = self.readPath(file)
            self.local_settings.setVolatility_Directory(Canonical_file)
            self.Program_Executable_TF.setText(Canonical_file)

    def keyPressed(self, event):
        self.local_settings.setProcessIDs(
            self.Process_Ids_To_Dump_TF.getText())
        #self.Error_Message.setText(self.Process_Ids_To_Dump_TF.getText())

    def checkBoxEvent(self, event):
        if self.Check_Box.isSelected():
            self.local_settings.setFlag(True)
        else:
            self.local_settings.setFlag(False)

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup()
        self.gbPanel0 = GridBagLayout()
        self.gbcPanel0 = GridBagConstraints()
        self.panel0.setLayout(self.gbPanel0)

        self.Error_Message = JLabel("")
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0)
        self.panel0.add(self.Error_Message)

        self.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0)
        self.panel0.add(self.Label_1)

        self.Program_Executable_TF = JTextField(10)
        self.Program_Executable_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Program_Executable_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Program_Executable_TF)

        self.Find_Program_Exec_BTN = JButton("Find Dir",
                                             actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Find_Program_Exec_BTN)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.Find_Program_Exec_BTN)

        self.Blank_1 = JLabel(" ")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0)
        self.panel0.add(self.Blank_1)

        self.Save_Settings_BTN = JButton("Save Volatility Exec Dir",
                                         actionPerformed=self.SaveSettings)
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Save_Settings_BTN)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0)
        self.panel0.add(self.Save_Settings_BTN)

        self.Blank_2 = JLabel(" ")
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0)
        self.panel0.add(self.Blank_2)

        self.Blank_3 = JLabel(" ")
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_3, self.gbcPanel0)
        self.panel0.add(self.Blank_3)

        self.Check_Box = JCheckBox(
            "Extract and Create Memory Image from Hiberfile",
            actionPerformed=self.checkBoxEvent)
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Check_Box, self.gbcPanel0)
        self.panel0.add(self.Check_Box)

        self.Blank_4 = JLabel(" ")
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 17
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_4, self.gbcPanel0)
        self.panel0.add(self.Blank_4)

        self.Blank_5 = JLabel(" ")
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 21
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_5, self.gbcPanel0)
        self.panel0.add(self.Blank_5)

        self.Blank_6 = JLabel(" ")
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 27
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_6, self.gbcPanel0)
        self.panel0.add(self.Blank_6)

        self.Label_3 = JLabel("Message:")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 29
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_3, self.gbcPanel0)
        self.panel0.add(self.Label_3)

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Check_Box.setSelected(self.local_settings.getFlag())
        self.check_Database_entries()
        #pass

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #13
0
class BurpExtender(IBurpExtender, ITab):
    socket_time_out = 3

    def registerExtenderCallbacks(self, callbacks):
        self.out = callbacks.getStdout()

        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("WhatsApp Decoder")

        self.banner = JLabel("WHATSAPP DECRYPTION AND ENCRYPTION EXTENSION BY DIKLA BARDA, ROMAN ZAIKIN", SwingConstants.CENTER)
        self.banner.setFont(Font("Serif", Font.PLAIN, 17))
        self.banner.setBorder(BorderFactory.createLineBorder(Color.BLACK))

        self.statusConn = JLabel("CONNECTION STATUS:  ")
        self.statusConnField = JLabel("NOT CONNECTED")
        self.statusAct = JLabel("ACTION STATUS:      ")
        self.statusActField = JLabel("OK")

        self.ref = JLabel("Ref object:  ")
        self.refField = JTextField("123", 80)
        self.refField.setToolTipText("Copy the Ref from burpsuit WebSocket, make sure that the parameter 'secret' is there and you copy only the 'ref' without the connection and other data, if not logout from your whatsapp web and login again.")

        self.privateKey = JLabel("Private Key:")
        self.privateKeyField = JTextField("123", 80)
        self.privateKeyField.setToolTipText("Copy the private key list from your whatsapp web according to our blog post ")

        self.publicKey = JLabel("Public Key: ")
        self.publicKeyField = JTextField("123", 80)
        self.publicKeyField.setToolTipText("Copy the public key list from your whatsapp web according to our blog post")

        self.statusPanel1 = JPanel()
        self.statusPanel1.add(self.statusConn)
        self.statusPanel1.add(self.statusConnField)

        self.statusPanel2 = JPanel()
        self.statusPanel2.add(self.statusAct)
        self.statusPanel2.add(self.statusActField)

        self.privateKeyPanel = JPanel()
        self.privateKeyPanel.add(self.privateKey)
        self.privateKeyPanel.add(self.privateKeyField)

        self.publicKeyPanel = JPanel()
        self.publicKeyPanel.add(self.publicKey)
        self.publicKeyPanel.add(self.publicKeyField)

        self.refPanel = JPanel()
        self.refPanel.add(self.ref)
        self.refPanel.add(self.refField)

        self.messageField = JTextArea("", 5, 90)
        self.messageField.setLineWrap(True)
        self.messageField.setToolTipText("If you putting in the incoming traffic you can copy it from burp suit, the outgoing is the list from aesCbcEncrypt")

        self.whatsAppMessagesPanel = JPanel()
        self.whatsAppMessagesPanel.add(self.messageField)

        self.btnSave = JButton("Connect", actionPerformed=self.saveConfig)
        self.btnRestore = JButton("Clear", actionPerformed=self.clearConfig)

        self.grpConfig = JPanel()
        self.grpConfig.add(self.btnSave)
        self.grpConfig.add(self.btnRestore)

        self.btnIncoming = JButton("Incoming", actionPerformed=self.performAction)
        self.btnOutgoing = JButton("Outgoing", actionPerformed=self.performAction)

        self.btnEncrypt = JButton("Encrypt", actionPerformed=self.performAction)
        self.btnEncrypt.setEnabled(False)  # Can't send data without a direction

        self.btnDecrypt = JButton("Decrypt", actionPerformed=self.performAction)
        self.btnDecrypt.setEnabled(False)  # Can't send data without a direction

        self.btnCrypt = JPanel()
        self.btnCrypt.add(self.btnIncoming)
        self.btnCrypt.add(self.btnEncrypt)
        self.btnCrypt.add(self.btnDecrypt)
        self.btnCrypt.add(self.btnOutgoing)

        self.tab = JPanel()
        layout = GridBagLayout()
        self.tab.setLayout(layout)

        c = GridBagConstraints()

        c.ipadx = 0
        c.ipady = 0

        c.fill = GridBagConstraints.BOTH
        #c.weightx = 0 # gap between the x items
        #c.weighty = 0 # gap between the y items

        c.anchor = GridBagConstraints.NORTHWEST

        c.gridx = 0
        c.gridy = 0
        self.tab.add(self.banner, c)

        c.gridx = 0
        c.gridy = 1
        self.tab.add(self.refPanel, c)

        c.gridx = 0
        c.gridy = 2
        self.tab.add(self.privateKeyPanel, c)

        c.gridx = 0
        c.gridy = 3
        self.tab.add(self.publicKeyPanel, c)

        c.gridx = 0
        c.gridy = 4
        c.anchor = GridBagConstraints.CENTER
        self.tab.add(self.grpConfig, c)

        c.gridx = 0
        c.gridy = 5
        self.tab.add(self.whatsAppMessagesPanel, c)

        c.gridx = 0
        c.gridy = 6
        self.tab.add(self.btnCrypt, c)

        c.gridx = 0
        c.gridy = 7
        self.tab.add(self.statusPanel1, c)

        c.gridx = 0
        c.gridy = 8
        self.tab.add(self.statusPanel2, c)

        # restore config
        self.restoreConfig()
        callbacks.addSuiteTab(self)

    def performAction(self, e=None):

        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        self.data = self.messageField.getText()

        eventSource = e.getSource()
        eventSource.setEnabled(False)

        # Incoming data
        if eventSource == self.btnIncoming:
            self.direction = "in"
            self.btnOutgoing.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Outgoing data
        elif eventSource == self.btnOutgoing:
            self.direction = "out"
            self.btnIncoming.setEnabled(True)
            self.btnEncrypt.setEnabled(True)
            self.btnDecrypt.setEnabled(True)

        # Send
        elif eventSource == self.btnDecrypt:
            self.btnDecrypt.setEnabled(True)
            clientData = json.dumps({"action": "decrypt",
                                     "data": {
                                            "direction": self.direction,
                                            "msg": self.messageField.getText()
                                        }
                                     })

            self.client.sendto(clientData, ("127.0.0.1",2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)

                if serverData["status"] == 0:
                    print serverData
                    self.messageField.setText(json.dumps(serverData["data"]))
                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        elif eventSource == self.btnEncrypt:
            self.btnEncrypt.setEnabled(True)
            clientData = json.dumps({"action": "encrypt",
                                     "data": {
                                         "direction": self.direction,
                                         "msg": self.messageField.getText()
                                     }
                                     })

            self.client.sendto(clientData, ("127.0.0.1", 2912))
            try:
                serverData, addr = self.client.recvfrom(2048)
                serverData = json.loads(serverData)
                if serverData["status"] == 0:
                    if isinstance(serverData["data"], list):
                        self.messageField.setText(json.dumps(serverData["data"]))
                    else:
                        self.messageField.setText(serverData["data"])

                    self.statusActField.setForeground(Color.GREEN)
                    self.statusActField.setText("OK")
                else:
                    self.statusActField.setForeground(Color.RED)
                    self.statusActField.setText("Error: {}".format(json.dumps(serverData["data"])))

            except socket.timeout:
                pass

        self.client.close()


    def saveConfig(self, e=None):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.client.settimeout(self.socket_time_out)

        config = {
            'ref': self.refField.getText(),
            'private': self.privateKeyField.getText(),
            'public': self.publicKeyField.getText(),
        }

        self.callbacks.saveExtensionSetting("config", pickle.dumps(config))

        try:
            clientData = json.dumps({"action":"init",
                                     "data":{
                                         "ref":json.loads(self.refField.getText()),
                                         "private":self.privateKeyField.getText(),
                                         "public":self.publicKeyField.getText()
                                     }
                                    })

            self.client.sendto(clientData, ("127.0.0.1", 2912))

            serverData, addr = self.client.recvfrom(2048)
            print (serverData)

            self.statusConnField.setText("CONNECTED")
            self.statusActField.setForeground(Color.GREEN)
            self.statusActField.setText("OK")

        except socket.timeout:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: Can't connect to the local server make sure parser.py is running!")
            pass

        except Exception as e:
            self.statusActField.setForeground(Color.RED)
            self.statusActField.setText("Error: make Sure the ref is a correct json!")

        self.client.close()

    def clearConfig(self, e=None):
        self.refField.setText("")
        self.privateKeyField.setText("")
        self.publicKeyField.setText("")
        self.statusConnField.setText("NOT CONNECTED")
        self.statusActField.setText("OK")
        self.messageField.setText("")

    def restoreConfig(self, e=None):
        storedConfig = self.callbacks.loadExtensionSetting("config")
        if storedConfig != None:
            config = pickle.loads(storedConfig)
            self.refField.setText(config["ref"])
            self.privateKeyField.setText(config["private"])
            self.publicKeyField.setText(config["public"])

    def getTabCaption(self):
        return ("WhatsApp Decoder")

    def getUiComponent(self):
        return self.tab
Beispiel #14
0
class PreferencesFrame(JFrame, ActionListener, WindowListener, ItemListener, HyperlinkListener):
    """Dialog with preferences
    """
    def __init__(self, parent, title, app):
        from javax.swing import JCheckBox, JRadioButton, ButtonGroup
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.getContentPane().setLayout(BorderLayout(0, 5))
        self.tabbedPane = JTabbedPane()

        #1 Tab: general
        panel1 = JPanel()
        panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS))

        #Checkbutton to enable/disable update check when script starts
        self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn"))
        self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip"))

        #Download tools
        downloadBtn = JButton(self.app.strings.getString("updatesBtn"),
                              ImageProvider.get("dialogs", "refresh"),
                              actionPerformed=self.on_downloadBtn_clicked)
        downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip"))

        #Checkbuttons for enabling/disabling tools
        toolsPanel = JPanel(BorderLayout(0, 5))
        title = self.app.strings.getString("enable_disable_tools")
        toolsPanel.setBorder(BorderFactory.createTitledBorder(title))
        infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning"))
        infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC))
        toolsPanel.add(infoLbl, BorderLayout.PAGE_START)

        toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0))
        self.toolsCBtns = []
        for tool in self.app.realTools:
            toolCBtn = JCheckBox()
            toolCBtn.addItemListener(self)
            toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT)
            self.toolsCBtns.append(toolCBtn)

            toolPane = JPanel()
            toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS))
            toolPane.add(toolCBtn)
            toolPane.add(toolLbl)
            toolsStatusPane.add(toolPane)
        toolsPanel.add(toolsStatusPane, BorderLayout.CENTER)

        #Radiobuttons for enabling/disabling layers when a new one
        #is added
        layersPanel = JPanel(GridLayout(0, 1))
        title = self.app.strings.getString("errors_layers_manager")
        layersPanel.setBorder(BorderFactory.createTitledBorder(title))
        errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info"))
        errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC))
        layersPanel.add(errorLayersLbl)
        self.layersRBtns = {}
        group = ButtonGroup()
        for mode in self.app.layersModes:
            layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode))
            group.add(layerRBtn)
            layersPanel.add(layerRBtn)
            self.layersRBtns[mode] = layerRBtn

        #Max number of errors text field
        self.maxErrorsNumberTextField = JTextField()
        self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip"))
        self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder()
        self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self))

        #layout
        self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(self.updateCBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(downloadBtn)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(toolsPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(layersPanel)
        panel1.add(Box.createRigidArea(Dimension(0, 15)))
        maxErrP = JPanel(BorderLayout(5, 0))
        maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START)
        maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER)
        p = JPanel(BorderLayout())
        p.add(maxErrP, BorderLayout.PAGE_START)
        p.setAlignmentX(Component.LEFT_ALIGNMENT)
        panel1.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"),
                          None,
                          panel1,
                          None)

        #2 Tab: favourite zones
        panel2 = JPanel(BorderLayout(5, 15))
        panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))

        #status
        topPanel = JPanel()
        topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS))
        infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info"))
        infoPanel.getEditorPane().addHyperlinkListener(self)
        infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"),
                                           actionListener=self)
        self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip"))
        self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT)
        topPanel.add(infoPanel)
        topPanel.add(Box.createRigidArea(Dimension(0, 10)))
        topPanel.add(self.favZoneStatusCBtn)
        #table
        self.zonesTable = JTable()
        tableSelectionModel = self.zonesTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ZonesTableListener(self))
        columns = ["",
                   self.app.strings.getString("Type"),
                   self.app.strings.getString("Name")]
        tableModel = ZonesTableModel([], columns)
        self.zonesTable.setModel(tableModel)
        self.scrollPane = JScrollPane(self.zonesTable)
        #map
        self.zonesMap = JMapViewer()
        self.zonesMap.setZoomContolsVisible(False)
        self.zonesMap.setMinimumSize(Dimension(100, 200))

        #buttons
        self.removeBtn = JButton(self.app.strings.getString("Remove"),
                            ImageProvider.get("dialogs", "delete"),
                            actionPerformed=self.on_removeBtn_clicked)
        self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip"))
        newBtn = JButton(self.app.strings.getString("New"),
                         ImageProvider.get("dialogs", "add"),
                         actionPerformed=self.on_newBtn_clicked)
        newBtn.setToolTipText(self.app.strings.getString("new_tooltip"))

        #layout
        panel2.add(topPanel, BorderLayout.PAGE_START)
        panel2.add(self.scrollPane, BorderLayout.LINE_START)
        panel2.add(self.zonesMap, BorderLayout.CENTER)
        self.buttonsPanel = JPanel()
        self.buttonsPanel.add(self.removeBtn)
        self.buttonsPanel.add(newBtn)
        panel2.add(self.buttonsPanel, BorderLayout.PAGE_END)

        self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"),
                          None,
                          panel2,
                          None)

        #3 Tab Tools options
        panel3 = JPanel()
        panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS))
        panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7))
        for tool in self.app.realTools:
            if hasattr(tool, 'prefs'):
                p = JPanel(FlowLayout(FlowLayout.LEFT))
                p.setBorder(BorderFactory.createTitledBorder(tool.title))
                p.add(tool.prefsGui)
                panel3.add(p)

        self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"),
                          None,
                          panel3,
                          None)

        self.add(self.tabbedPane, BorderLayout.CENTER)

        exitPanel = JPanel()
        saveBtn = JButton(self.app.strings.getString("OK"),
                          ImageProvider.get("ok"),
                          actionPerformed=self.on_saveBtn_clicked)
        cancelBtn = JButton(self.app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=self.on_cancelBtn_clicked)
        saveBtn.setToolTipText(self.app.strings.getString("save_preferences"))
        saveBtn.setAlignmentX(0.5)
        exitPanel.add(saveBtn)
        exitPanel.add(cancelBtn)
        self.add(exitPanel, BorderLayout.PAGE_END)

        self.addWindowListener(self)
        self.pack()

    def windowClosing(self, windowEvent):
        self.on_cancelBtn_clicked()

    def hyperlinkUpdate(self, e):
        if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED:
            OpenBrowser.displayUrl(e.getURL().toString())

    def itemStateChanged(self, e):
        """A ttol has been activated/deactivated.
           Check if at least one tool is on.
        """
        if all(not button.isSelected() for button in self.toolsCBtns):
            JOptionPane.showMessageDialog(
                Main.parent,
                self.app.strings.getString("tools_disabled_warning"),
                self.app.strings.getString("tools_disabled_warning_title"),
                JOptionPane.WARNING_MESSAGE)
            source = e.getItemSelectable()
            source.setSelected(True)

    def actionPerformed(self, e=None):
        """Enable/disable favourite zones panel
        """
        for container in (self.scrollPane, self.buttonsPanel):
            self.enableComponents(container, self.favZoneStatusCBtn.isSelected())
        if self.favZoneStatusCBtn.isSelected():
            self.check_removeBtn_status()

    def enableComponents(self, container, enable):
        components = container.getComponents()
        for component in components:
            component.setEnabled(enable)
            if isinstance(component, Container):
                self.enableComponents(component, enable)

    def on_downloadBtn_clicked(self, e):
        update_checker.Updater(self.app, "manual")

    def clean_map(self):
        """Remove all rectangles and polygons from the map
        """
        self.zonesMap.removeAllMapRectangles()
        self.zonesMap.removeAllMapPolygons()

    def update_gui_from_preferences(self):
        """Update gui status of preferences frame from config file
        """
        #print "\n- updating Preferences gui"
        onOff = {"on": True, "off": False}
        #1 Tab
        #check for update
        self.updateCBtn.setSelected(onOff[self.app.checkUpdate])

        #tools status, enabled or not
        for toolIndex, tool in enumerate(self.app.realTools):
            if "tool.%s" % tool.name in self.app.properties.keys():
                configstatus = self.app.properties.getProperty("tool.%s" % tool.name)
            else:
                configstatus = "on"     # new tool
            self.toolsCBtns[toolIndex].setSelected(onOff[configstatus])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            button.setSelected(mode == self.app.layersMode)

        #max errors number
        self.maxErrorsNumberTextField.setText(str(self.app.maxErrorsNumber))

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()

        #2 Tab
        #favourite area
        self.update_favourite_area_gui_from_preferences()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                tool.prefsGui.update_gui(tool.prefs)

    def update_favourite_area_gui_from_preferences(self):
        #status
        self.favZoneStatusCBtn.setSelected(self.app.favouriteZoneStatus)
        #table
        #store zones to a temporary list, used to store changes
        #and save them when preferences dialog is closed
        self.app.tempZones = list(self.app.zones)
        self.zonesTable.getModel().setNumRows(0)
        for zone in self.app.tempZones:
            self.zonesTable.getModel().addRow([zone.country,
                                               zone.icon,
                                               zone.name])
        if self.app.favZone is not None:
            selectedRow = self.app.tempZones.index(self.app.favZone)
            self.zonesTable.setRowSelectionInterval(selectedRow, selectedRow)
        self.zonesTable.getColumnModel().getColumn(0).setMaxWidth(30)
        self.zonesTable.getColumnModel().getColumn(1).setMaxWidth(50)
        #enable or disable favourite zone buttons
        self.actionPerformed()

### fav area editing buttons ###########################################
    def on_removeBtn_clicked(self, e):
        rowsNum = self.zonesTable.getSelectedRows()
        rowsNum.reverse()
        for rowNum in rowsNum:
            del self.app.tempZones[rowNum]
            self.zonesTable.getModel().removeRow(rowNum)
        if len(self.app.tempZones) != 0:
            if rowNum == 0:
                self.zonesTable.setRowSelectionInterval(0, 0)
            else:
                self.zonesTable.setRowSelectionInterval(rowNum - 1, rowNum - 1)
        self.check_removeBtn_status()

    def check_removeBtn_status(self):
        if self.app.tempZones != [] and len(self.zonesTable.getSelectedRows()) != 0:
            self.removeBtn.setEnabled(True)
        else:
            self.removeBtn.setEnabled(False)
            self.clean_map()

    def on_newBtn_clicked(self, e):
        try:
            self.newZoneDialog
        except AttributeError:
            self.newZoneDialog = NewZoneDialog(self.app)
        bbox = self.app.get_frame_bounds()
        self.app.newZone = Zone(self.app,
                                self.app.strings.getString("New_zone"),
                                "rectangle",
                                ",".join(["%0.4f" % x for x in bbox]),
                                "")
        self.newZoneDialog.update_gui_from_preferences()
        self.newZoneDialog.show()

### Exit from preferences ##############################################
    def on_cancelBtn_clicked(self, event=None):
        if hasattr(self, "newZoneDialog") and self.newZoneDialog.isVisible():
            self.newZoneDialog.close_dialog()
        self.dispose()

    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop,
                                            onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones],
                   "deleted": [z for z in self.app.zones if not z in self.app.tempZones]}
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(File.separator.join([self.app.SCRIPTDIR,
                                          "configuration",
                                          "favourite_zones",
                                          "%s.txt" % zone.name]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([self.app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones",
                                            "%s.txt" % zone.name])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name",
                                            "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()
Beispiel #15
0
class CuckooSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.tag_list = []
        self.initComponents()
        self.customizeComponents()
        self.path_to_cuckoo_exe = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cuckoo_api.exe")
 
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Submit_File_CB.isSelected():
            self.local_settings.setSubmit_File(True)
            self.local_settings.setSubmit_URL(False)
        else:
            self.local_settings.setSubmit_File(False)
            
        # if self.Submit_URL_CB.isSelected():
            # self.local_settings.setSubmit_URL(True)
            # self.local_settings.setSubmit_File(False)
        # else:
            # self.local_settings.setSubmit_URL(False)
            
    def onchange_lb(self, event):
        self.local_settings.cleartag_list()
        list_selected = self.List_Box_LB.getSelectedValuesList()
        self.local_settings.settag_list(list_selected)      

    def find_tags(self):
        
        sql_statement = "SELECT distinct(display_name) u_tag_name FROM content_tags INNER JOIN tag_names ON " + \
                        " content_tags.tag_name_id = tag_names.tag_name_id;"
        skCase = Case.getCurrentCase().getSleuthkitCase()
        dbquery = skCase.executeQuery(sql_statement)
        resultSet = dbquery.getResultSet()
        while resultSet.next():
             self.tag_list.append(resultSet.getString("u_tag_name"))
        dbquery.close()

    # Check to see if there are any entries that need to be populated from the database.        
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\gui_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Select Protocol, cuckoo_host, cuckoo_port from cuckoo_server' 
           resultSet = stmt.executeQuery(SQL_Statement)
           while resultSet.next():
               self.Protocol_TF.setText(resultSet.getString("Protocol"))
               self.IP_Address_TF.setText(resultSet.getString("cuckoo_host"))
               self.Port_Number_TF.setText(resultSet.getString("cuckoo_port"))
               self.local_settings.setProtocol(resultSet.getString("Protocol"))
               self.local_settings.setIP_Address(resultSet.getString("cuckoo_host"))
               self.local_settings.setPort_Number(resultSet.getString("cuckoo_port"))
           self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = ""
           SQL_Statement = 'Update cuckoo_server set Protocol = "' + self.Protocol_TF.getText() + '", ' + \
                               '                     Cuckoo_Host = "' + self.IP_Address_TF.getText() + '", ' + \
                               '                     Cuckoo_port = "' + self.Port_Number_TF.getText() + '";' 
           
           #self.Error_Message.setText(SQL_Statement)
           stmt.execute(SQL_Statement)
           self.Error_Message.setText("Cuckoo settings Saved")
           #self.local_settings.setCuckoo_Directory(self.Program_Executable_TF.getText())
        except SQLException as e:
           self.Error_Message.setText(e.getMessage())
        stmt.close()
        dbConn.close()
           
    # Check to see if the Cuckoo server is available and you can talk to it
    def Check_Server(self, e):

       pipe = Popen([self.path_to_cuckoo_exe, self.Protocol_TF.getText(),self.IP_Address_TF.getText(), self.Port_Number_TF.getText(), "cuckoo_status" ], stdout=PIPE, stderr=PIPE)
        
       out_text = pipe.communicate()[0]
       self.Error_Message.setText("Cuckoo Status is " + out_text)
       #self.log(Level.INFO, "Cuckoo Status is ==> " + out_text)

           
    # def onchange_cb(self, event):
        # self.local_settings.setComboBox(event.item) 

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Label_1 = JLabel("Protocol:")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Protocol_TF = JTextField(20) 
        self.Protocol_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Protocol_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Protocol_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_2 = JLabel("Cuckoo IP Address")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.IP_Address_TF = JTextField(20) 
        self.IP_Address_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.IP_Address_TF, self.gbcPanel0 ) 
        self.panel0.add( self.IP_Address_TF ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_2, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_2 ) 

        self.Label_3 = JLabel("Port Number")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 

        self.Port_Number_TF = JTextField(20) 
        self.Port_Number_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Port_Number_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Port_Number_TF ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        
        self.Save_Settings_BTN = JButton( "Save Setup", actionPerformed=self.SaveSettings) 
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Save_Settings_BTN ) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Save_Settings_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Save_Settings_BTN ) 

        self.Blank_4 = JLabel( " ") 
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_4, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_4 ) 

        self.Blank_5 = JLabel( "Tag to Choose: ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.find_tags()
        self.List_Box_LB = JList( self.tag_list, valueChanged=self.onchange_lb)
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 17 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_6, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Submit_File_CB = JCheckBox("Submit a File", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 21 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Submit_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Submit_File_CB ) 

        # self.Submit_URL_CB = JCheckBox("Submit a URL", actionPerformed=self.checkBoxEvent)
        # self.gbcPanel0.gridx = 2 
        # self.gbcPanel0.gridy = 23 
        # self.gbcPanel0.gridwidth = 1 
        # self.gbcPanel0.gridheight = 1 
        # self.gbcPanel0.fill = GridBagConstraints.BOTH 
        # self.gbcPanel0.weightx = 1 
        # self.gbcPanel0.weighty = 0 
        # self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        # self.gbPanel0.setConstraints( self.Submit_URL_CB, self.gbcPanel0 ) 
        # self.panel0.add( self.Submit_URL_CB ) 

        self.Check_Server_Status_BTN = JButton( "Check Server Status", actionPerformed=self.Check_Server) 
        self.Check_Server_Status_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Save_Settings_BTN ) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 25
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Check_Server_Status_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Server_Status_BTN ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 27
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 


        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        #self.Exclude_File_Sources_CB.setSelected(self.local_settings.getExclude_File_Sources())
        #self.Run_Cuckoo_CB.setSelected(self.local_settings.getRun_Cuckoo())
        #self.Import_Cuckoo_CB.setSelected(self.local_settings.getImport_Cuckoo())
        self.check_Database_entries()

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #16
0
class NewZoneDialog(JDialog, ActionListener, WindowListener):
    """Dialog for favourite zone editing
    """
    def __init__(self, parent, title, modal, app):
        from java.awt import CardLayout
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 7, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        self.FAVAREALAYERNAME = "Favourite zone editing"

        info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone"))
        info.setAlignmentX(Component.LEFT_ALIGNMENT)

        #Name
        nameLbl = JLabel(self.app.strings.getString("fav_zone_name"))
        self.nameTextField = JTextField(20)
        self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize())
        self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip"))
        namePanel = JPanel()
        namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS))
        namePanel.add(nameLbl)
        namePanel.add(Box.createHorizontalGlue())
        namePanel.add(self.nameTextField)

        #Country
        countryLbl = JLabel(self.app.strings.getString("fav_zone_country"))
        self.countryTextField = JTextField(20)
        self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize())
        self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip"))
        countryPanel = JPanel()
        countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS))
        countryPanel.add(countryLbl)
        countryPanel.add(Box.createHorizontalGlue())
        countryPanel.add(self.countryTextField)

        #Type
        modeLbl = JLabel(self.app.strings.getString("fav_zone_type"))
        RECTPANEL = "rectangle"
        POLYGONPANEL = "polygon"
        BOUNDARYPANEL = "boundary"
        self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL]
        modesComboModel = DefaultComboBoxModel()
        for i in (self.app.strings.getString("rectangle"),
                  self.app.strings.getString("delimited_by_a_closed_way"),
                  self.app.strings.getString("delimited_by_an_administrative_boundary")):
            modesComboModel.addElement(i)
        self.modesComboBox = JComboBox(modesComboModel,
                                       actionListener=self,
                                       editable=False)

        #- Rectangle
        self.rectPanel = JPanel()
        self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS))

        capturePane = JPanel()
        capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS))
        capturePane.setAlignmentX(Component.LEFT_ALIGNMENT)

        josmP = JPanel()
        self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area"))
        self.captureRBtn.addActionListener(self)
        self.captureRBtn.setSelected(True)
        self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"),
                                       actionPerformed=self.on_bboxFromJosmBtn_clicked)
        self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip"))
        josmP.add(self.bboxFromJosmBtn)
        capturePane.add(self.captureRBtn)
        capturePane.add(Box.createHorizontalGlue())
        capturePane.add(self.bboxFromJosmBtn)

        manualPane = JPanel()
        manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS))
        manualPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox"))
        self.manualRBtn.addActionListener(self)
        self.bboxTextField = JTextField(20)
        self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize())
        self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip"))
        self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder()
        self.bboxTextField.getDocument().addDocumentListener(TextListener(self))
        manualPane.add(self.manualRBtn)
        manualPane.add(Box.createHorizontalGlue())
        manualPane.add(self.bboxTextField)

        group = ButtonGroup()
        group.add(self.captureRBtn)
        group.add(self.manualRBtn)

        previewPane = JPanel()
        previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS))
        previewPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"),
                                     editable=0,
                                     border=None)
        bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize())
        self.bboxPreviewTextField = JTextField(20,
                                               editable=0,
                                               border=None)
        self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize())
        previewPane.add(bboxPreviewInfo)
        previewPane.add(Box.createHorizontalGlue())
        previewPane.add(self.bboxPreviewTextField)

        self.rectPanel.add(capturePane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.rectPanel.add(manualPane)
        self.rectPanel.add(Box.createRigidArea(Dimension(0, 20)))
        self.rectPanel.add(previewPane)

        #- Polygon (closed way) drawn by hand
        self.polygonPanel = JPanel(BorderLayout())
        self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS))

        polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info"))
        polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC))
        polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        editPolyPane = JPanel()
        editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"),
                              actionPerformed=self.create_new_zone_editing_layer)
        editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip"))
        editPolyPane.add(editPolyBtn)

        self.polygonPanel.add(polyInfo)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.polygonPanel.add(editPolyPane)
        self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15)))

        #- Administrative Boundary
        self.boundaryPanel = JPanel()
        self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS))

        boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info"))
        boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC))
        boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT)

        boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5))
        boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        boundaryTagsPanel.add(JLabel("name ="))
        self.nameTagTextField = JTextField(20)
        boundaryTagsPanel.add(self.nameTagTextField)
        boundaryTagsPanel.add(JLabel("admin_level ="))
        self.adminLevelTagTextField = JTextField(20)
        self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip"))
        boundaryTagsPanel.add(self.adminLevelTagTextField)
        boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag")))
        self.optionalTagTextField = JTextField(20)
        self.optionalTagTextField.setToolTipText("key=value")
        boundaryTagsPanel.add(self.optionalTagTextField)

        downloadBoundariesPane = JPanel()
        downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT)
        downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"),
                                        actionPerformed=self.on_downloadBoundariesBtn_clicked)
        downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip"))
        downloadBoundariesPane.add(downloadBoundariesBtn)

        self.boundaryPanel.add(boundaryInfo)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15)))
        self.boundaryPanel.add(boundaryTagsPanel)
        self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10)))
        self.boundaryPanel.add(downloadBoundariesPane)

        self.editingPanels = {"rectangle": self.rectPanel,
                              "polygon": self.polygonPanel,
                              "boundary": self.boundaryPanel}

        #Main buttons
        self.okBtn = JButton(self.app.strings.getString("OK"),
                             ImageProvider.get("ok"),
                             actionPerformed=self.on_okBtn_clicked)
        self.cancelBtn = JButton(self.app.strings.getString("cancel"),
                                 ImageProvider.get("cancel"),
                                 actionPerformed=self.close_dialog)
        self.previewBtn = JButton(self.app.strings.getString("Preview_zone"),
                                  actionPerformed=self.on_previewBtn_clicked)
        self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip"))
        okBtnSize = self.okBtn.getPreferredSize()
        viewBtnSize = self.previewBtn.getPreferredSize()
        viewBtnSize.height = okBtnSize.height
        self.previewBtn.setPreferredSize(viewBtnSize)

        #layout
        self.add(info)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        namePanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(namePanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(countryPanel)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(modeLbl)
        self.add(Box.createRigidArea(Dimension(0, 5)))

        self.add(self.modesComboBox)
        self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(Box.createRigidArea(Dimension(0, 15)))

        self.configPanel = JPanel(CardLayout())
        self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5))
        self.configPanel.add(self.rectPanel, RECTPANEL)
        self.configPanel.add(self.polygonPanel, POLYGONPANEL)
        self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL)
        self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(self.configPanel)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        buttonsPanel.add(self.previewBtn)
        buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT)
        self.add(buttonsPanel)

        self.addWindowListener(self)
        self.pack()

    def update_gui_from_preferences(self):
        self.nameTextField.setText(self.app.newZone.name)
        #Reset rectangle mode
        bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox])
        self.bboxTextField.setText(bboxStr)
        self.bboxPreviewTextField.setText(bboxStr)
        self.bboxFromJosmBtn.setEnabled(True)
        self.bboxTextField.setEnabled(False)

        #Reset polygon mode
        self.polygonAsString = ""

        #Reset boundary mode
        self.boundaryAsString = ""

        self.modesComboBox.setSelectedIndex(0)

    def actionPerformed(self, e):
        #Show the panel for configuring the favourite area of the
        #selected type
        if e.getSource() == self.modesComboBox:
            cl = self.configPanel.getLayout()
            selectedMode = self.modesStrings[self.modesComboBox.selectedIndex]
            cl.show(self.configPanel, selectedMode)
        #Activate bbox input for rectangular favourite zone mode
        elif e.getSource() == self.captureRBtn:
            self.bboxFromJosmBtn.setEnabled(True)
            self.bboxTextField.setEnabled(False)
        else:
            self.bboxFromJosmBtn.setEnabled(False)
            self.bboxTextField.setEnabled(True)

    def on_bboxFromJosmBtn_clicked(self, widget):
        """Read bbox currently shown in JOSM
        """
        bbox = self.app.get_frame_bounds()
        self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox]))

### Manage layer for creating a new favourite zone from polygon or boundary
    def create_new_zone_editing_layer(self, e=None):
        """Open a new dataset where the user can draw a closed way to
           delimit the favourite area
        """
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.setActiveLayer(layer)
        else:
            Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None))
        Main.main.parent.toFront()

    def get_new_zone_editing_layer(self):
        """Check if the layer for editing the favourite area yet exists
        """
        for layer in self.app.mv.getAllLayers():
            if layer.getName() == self.FAVAREALAYERNAME:
                return layer
        return None

    def remove_new_zone_editing_layer(self):
        layer = self.get_new_zone_editing_layer()
        if layer is not None:
            self.app.mv.removeLayer(layer)

    def on_zone_edited(self):
        """Read ways that delimit the favourite area and convert them to
           jts geometry
        """
        if self.modesComboBox.getSelectedIndex() == 0:
            mode = "rectangle"
        elif self.modesComboBox.getSelectedIndex() == 1:
            mode = "polygon"
        elif self.modesComboBox.getSelectedIndex() == 2:
            mode = "boundary"

        if mode in ("polygon", "boundary"):
            layer = self.get_new_zone_editing_layer()
            if layer is not None:
                self.app.mv.setActiveLayer(layer)
            else:
                if mode == "polygon":
                    msg = self.app.strings.getString("polygon_fav_layer_missing_msg")
                else:
                    msg = self.app.strings.getString("boundary_fav_layer_missing_msg")
                JOptionPane.showMessageDialog(self,
                                              msg,
                                              self.app.strings.getString("Warning"),
                                              JOptionPane.WARNING_MESSAGE)
                return

            dataset = self.app.mv.editLayer.data
            areaWKT = self.read_area_from_osm_ways(mode, dataset)
            if areaWKT is None:
                print "I could not read the new favourite area."
            else:
                if mode == "polygon":
                    self.polygonAsString = areaWKT
                else:
                    self.boundaryAsString = areaWKT
        return mode

    def read_area_from_osm_ways(self, mode, dataset):
        """Read way in favourite area editing layer and convert them to
           WKT
        """
        converter = JTSConverter(False)
        lines = [converter.convert(way) for way in dataset.ways]
        polygonizer = Polygonizer()
        polygonizer.add(lines)
        polygons = polygonizer.getPolygons()
        multipolygon = GeometryFactory().createMultiPolygon(list(polygons))
        multipolygonWKT = WKTWriter().write(multipolygon)
        if multipolygonWKT == "MULTIPOLYGON EMPTY":
            if mode == "polygon":
                msg = self.app.strings.getString("empty_ways_polygon_msg")
            else:
                msg = self.app.strings.getString("empty_ways_boundaries_msg")
            JOptionPane.showMessageDialog(self,
                msg,
                self.app.strings.getString("Warning"),
                JOptionPane.WARNING_MESSAGE)
            return
        return multipolygonWKT

    def on_downloadBoundariesBtn_clicked(self, e):
        """Download puter ways of administrative boundaries from
           Overpass API
        """
        adminLevel = self.adminLevelTagTextField.getText()
        name = self.nameTagTextField.getText()
        optional = self.optionalTagTextField.getText()
        if (adminLevel, name, optional) == ("", "", ""):
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("enter_a_tag_msg"),
                                          self.app.strings.getString("Warning"),
                                          JOptionPane.WARNING_MESSAGE)
            return
        optTag = ""
        if optional.find("=") != -1:
            if len(optional.split("=")) == 2:
                key, value = optional.split("=")
                optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"),
                                          URLEncoder.encode(value.replace(" ", "%20"), "UTF-8"))
        self.create_new_zone_editing_layer()
        overpassurl = 'http://127.0.0.1:8111/import?url='
        overpassurl += 'http://overpass-api.de/api/interpreter?data='
        overpassquery = 'relation["admin_level"="%s"]' % adminLevel
        overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8")
        overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag
        overpassurl += overpassquery.replace(" ", "%20")
        print overpassurl
        self.app.send_to_josm(overpassurl)

### Buttons ############################################################
    def create_new_zone(self, mode):
        """Read data entered on gui and create a new zone
        """
        name = self.nameTextField.getText()
        country = self.countryTextField.getText().upper()

        #error: name
        if name.replace(" ", "") == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("missing_name_warning"),
                                          self.app.strings.getString("missing_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False
        if name in [z.name for z in self.app.tempZones]:
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("duplicate_name_warning"),
                                          self.app.strings.getString("duplicate_name_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #zone type
        zType = mode
        #error: geometry type not defined
        if zType == "polygon" and self.polygonAsString == ""\
            or zType == "boundary" and self.boundaryAsString == "":
            JOptionPane.showMessageDialog(self,
                                          self.app.strings.getString("zone_not_correctly_build_warning"),
                                          self.app.strings.getString("zone_not_correctly_build_warning_title"),
                                          JOptionPane.WARNING_MESSAGE)
            return False

        #geometry string
        if zType == "rectangle":
            geomString = self.bboxPreviewTextField.getText()
        elif zType == "polygon":
            geomString = self.polygonAsString
        else:
            geomString = self.boundaryAsString

        self.app.newZone = Zone(self.app, name, zType, geomString, country)
        #self.app.newZone.print_info()
        return True

    def on_okBtn_clicked(self, event):
        """Add new zone to temp zones
        """
        mode = self.on_zone_edited()
        if self.create_new_zone(mode):
            self.app.tempZones.append(self.app.newZone)
            self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country,
                                                                    self.app.newZone.icon,
                                                                    self.app.newZone.name])
            maxIndex = len(self.app.tempZones) - 1
            self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex,
                                                                         maxIndex)
            self.close_dialog()
            self.app.preferencesFrame.check_removeBtn_status()
            self.app.preferencesFrame.zonesTable.scrollRectToVisible(
                self.app.preferencesFrame.zonesTable.getCellRect(
                    self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True))

    def on_previewBtn_clicked(self, e):
        """Show the favourite area on a map
        """
        mode = self.on_zone_edited()
        if not self.create_new_zone(mode):
            return
        zone = self.app.newZone

        if zone.zType == "rectangle":
            wktString = zone.bbox_to_wkt_string()
        else:
            wktString = zone.wktGeom
        script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/'
        script += '\nfunction init() {'
        script += '\n    var map = new OpenLayers.Map({'
        script += '\n        div: "map",'
        script += '\n        projection: new OpenLayers.Projection("EPSG:900913"),'
        script += '\n        displayProjection: new OpenLayers.Projection("EPSG:4326"),'
        script += '\n        layers: ['
        script += '\n            new OpenLayers.Layer.OSM()'
        script += '\n            ]'
        script += '\n    });'
        script += '\n    var wkt = new OpenLayers.Format.WKT();'
        script += '\n    var polygonFeature = wkt.read("%s");' % wktString
        script += '\n    var vectors = new OpenLayers.Layer.Vector("Favourite area");'
        script += '\n    map.addLayer(vectors);'
        script += '\n    polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());'
        script += '\n    vectors.addFeatures([polygonFeature]);'
        script += '\n    map.zoomToExtent(vectors.getDataExtent());'
        script += '\n};'
        scriptFile = open(File.separator.join([self.app.SCRIPTDIR,
                                              "html",
                                              "script.js"]), "w")
        scriptFile.write(script)
        scriptFile.close()
        OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR,
                                                   "html",
                                                   "favourite_area.html"]))

    def windowClosing(self, windowEvent):
        self.close_dialog()

    def close_dialog(self, e=None):
        #delete favourite zone editing layer if present
        self.remove_new_zone_editing_layer()
        self.dispose()
        self.app.preferencesFrame.setEnabled(True)
        self.app.preferencesFrame.toFront()
Beispiel #17
0
class BurpExtender(IBurpExtender, ITab):

    #
    # implement IBurpExtender
    #
    def hello(self):
        return "hello"

    def process_file(self, file):
        freshrows = []
        # return list of list of file parts
        for url in file:
            result = urlparse(url)
            scheme = result[0]
            domain = result[0]
            path = result[0]
            params = ''
            query = ''
            fragment = ''
            next = [scheme, domain, path, params, query, fragment]
            freshrows.append(next)
        return freshrows

    def registerExtenderCallbacks(self, callbacks):

        # set our extension name
        callbacks.setExtensionName("Hello world extension")

        # obtain our output and error streams
        stdout = PrintWriter(callbacks.getStdout(), True)
        stderr = PrintWriter(callbacks.getStderr(), True)

        # write a message to our output stream
        stdout.println("Hello output")

        # write a message to our error stream
        stderr.println("Hello errors")

        # write a message to the Burp alerts tab
        callbacks.issueAlert("Hello alerts")

        #create and populate a jtable:
        initial_row = [
            'http', 'www.meetup.com',
            'PyMNtos-Twin-Cities-Python-User-Group/events/267977020/', '', '',
            ''
        ]
        self.fileTable = JTable(ResourceTableModel(initial_row))
        # set up the Tab:

        self.infoPanel = JPanel()
        footerPanel = JPanel()

        footerPanel.add(JLabel("by mcgyver5 "))
        self._chooseFileButton = JButton("OPEN Local FILE",
                                         actionPerformed=self.fileButtonClick)
        self.infoPanel.add(JLabel("INFORMATION PANE"))

        self.infoPanel.add(self._chooseFileButton)
        scrollpane = JScrollPane(self.fileTable)
        ## this is a split inside the top component
        topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        topPane.setTopComponent(self.infoPanel)
        topPane.setBottomComponent(scrollpane)
        self._chooseFileButton.setEnabled(True)
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setTopComponent(topPane)
        self._splitpane.setBottomComponent(footerPanel)
        callbacks.addSuiteTab(self)

    def populateTableModel(self, results):
        tableModel = self.fileTable.getModel()
        for row in results:
            tableModel.addRow(row)

    def fileButtonClick(self, callbacks):
        fileTypeList = ["csv", "txt", "json"]
        txtFilter = FileNameExtensionFilter("txt", fileTypeList)
        fileChooser = JFileChooser()
        fileChooser.addChoosableFileFilter(txtFilter)
        result = fileChooser.showOpenDialog(self._splitpane)

        if result == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            fileName = f.getPath()
            self.populateTableModel(f)

    ## Implement ITab:
    def getTabCaption(self):
        return "Import URLs"

    def getUiComponent(self):
        return self._splitpane
Beispiel #18
0
myPanel.add(primaLabel)
myPanel.add(betaTextField)
myPanel.add(primaTextField)
myPanel.add(hackingHeader)
#myPanel.add(dekomposisiLabel)
#myPanel.add(dekomposisiList)
myPanel.add(FBSizeLabel)
myPanel.add(FBSize)
myPanel.add(myKey)
myPanel.add(myKeyLabel)
#myPanel.add(encryptedText)
myPanel.add(plainText)
myPanel.add(dekripsiLabel)
myPanel.add(pesanTerkunci)
myPanel.add(searchButton)
myPanel.add(namaFile)
myPanel.add(alamatFile)
myPanel.add(hDekripsiButton)
#myPanel.add(myScrollPane)
myPanel.add(myLabel)
myPanel.add(laporan)
myPanel.add(showReportButton)
myPanel.add(pemecahanKunci)
#here

if (betaTextField.getText() == "" or alphaTextField.getText() == ""
        or primaTextField.getText() == ""):
    hackButton.setEnabled(False)
mainForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
mainForm.visible = True
myPanel.visible = True
Beispiel #19
0
class ConfigurableConfigPanel(ConfigPanel, ActionListener, DocumentListener, ChangeListener):
    """ generated source for class ConfigurableConfigPanel """
    serialVersionUID = 1L
    associatedFile = File()
    associatedFileField = JTextField()
    params = JSONObject()
    savedParams = str()
    loadButton = JButton()
    saveAsButton = JButton()
    saveButton = JButton()
    name = JTextField()
    strategy = JComboBox()
    metagameStrategy = JComboBox()
    stateMachine = JComboBox()
    cacheStateMachine = JCheckBox()
    maxPlys = JSpinner()
    heuristicFocus = JSpinner()
    heuristicMobility = JSpinner()
    heuristicOpponentFocus = JSpinner()
    heuristicOpponentMobility = JSpinner()
    mcDecayRate = JSpinner()
    rightPanel = JPanel()

    def __init__(self):
        """ generated source for method __init__ """
        super(ConfigurableConfigPanel, self).__init__(GridBagLayout())
        leftPanel = JPanel(GridBagLayout())
        leftPanel.setBorder(TitledBorder("Major Parameters"))
        self.rightPanel = JPanel(GridBagLayout())
        self.rightPanel.setBorder(TitledBorder("Minor Parameters"))
        self.strategy = JComboBox([None]*)
        self.metagameStrategy = JComboBox([None]*)
        self.stateMachine = JComboBox([None]*)
        self.cacheStateMachine = JCheckBox()
        self.maxPlys = JSpinner(SpinnerNumberModel(1, 1, 100, 1))
        self.heuristicFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentFocus = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.heuristicOpponentMobility = JSpinner(SpinnerNumberModel(1, 0, 10, 1))
        self.mcDecayRate = JSpinner(SpinnerNumberModel(0, 0, 99, 1))
        self.name = JTextField()
        self.name.setColumns(20)
        self.name.setText("Player #" + Random().nextInt(100000))
        self.loadButton = JButton(loadButtonMethod())
        self.saveButton = JButton(saveButtonMethod())
        self.saveAsButton = JButton(saveAsButtonMethod())
        self.associatedFileField = JTextField()
        self.associatedFileField.setEnabled(False)
        buttons = JPanel()
        buttons.add(self.loadButton)
        buttons.add(self.saveButton)
        buttons.add(self.saveAsButton)
        nRow = 0
        leftPanel.add(JLabel("Name"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_0 = nRow
        nRow += 1
        leftPanel.add(self.name, GridBagConstraints(1, __nRow_0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Gaming Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_1 = nRow
        nRow += 1
        leftPanel.add(self.strategy, GridBagConstraints(1, __nRow_1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("Metagame Strategy"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_2 = nRow
        nRow += 1
        leftPanel.add(self.metagameStrategy, GridBagConstraints(1, __nRow_2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        leftPanel.add(JLabel("State Machine"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_3 = nRow
        nRow += 1
        leftPanel.add(self.stateMachine, GridBagConstraints(1, __nRow_3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, Insets(5, 5, 5, 5), 5, 5))
        __nRow_4 = nRow
        nRow += 1
        leftPanel.add(buttons, GridBagConstraints(1, __nRow_4, 2, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 0, 5), 0, 0))
        leftPanel.add(self.associatedFileField, GridBagConstraints(0, nRow, 2, 1, 1.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.HORIZONTAL, Insets(0, 5, 5, 5), 0, 0))
        layoutRightPanel()
        add(leftPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        add(self.rightPanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(5, 5, 5, 5), 5, 5))
        self.params = JSONObject()
        syncJSONtoUI()
        self.strategy.addActionListener(self)
        self.metagameStrategy.addActionListener(self)
        self.stateMachine.addActionListener(self)
        self.cacheStateMachine.addActionListener(self)
        self.maxPlys.addChangeListener(self)
        self.heuristicFocus.addChangeListener(self)
        self.heuristicMobility.addChangeListener(self)
        self.heuristicOpponentFocus.addChangeListener(self)
        self.heuristicOpponentMobility.addChangeListener(self)
        self.mcDecayRate.addChangeListener(self)
        self.name.getDocument().addDocumentListener(self)

    def layoutRightPanel(self):
        """ generated source for method layoutRightPanel """
        nRow = 0
        self.rightPanel.removeAll()
        self.rightPanel.add(JLabel("State machine cache?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_5 = nRow
        nRow += 1
        self.rightPanel.add(self.cacheStateMachine, GridBagConstraints(1, __nRow_5, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Heuristic":
        __nRow_6 = nRow
        nRow += 1
        __nRow_7 = nRow
        nRow += 1
        __nRow_8 = nRow
        nRow += 1
        __nRow_9 = nRow
        nRow += 1
        __nRow_10 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Max plys?"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.maxPlys, GridBagConstraints(1, __nRow_6, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicFocus, GridBagConstraints(1, __nRow_7, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicMobility, GridBagConstraints(1, __nRow_8, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Focus Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentFocus, GridBagConstraints(1, __nRow_9, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(JLabel("Opponent Mobility Heuristic Weight"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.heuristicOpponentMobility, GridBagConstraints(1, __nRow_10, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        if self.strategy.getSelectedItem().__str__() == "Monte Carlo":
        __nRow_11 = nRow
        nRow += 1
            self.rightPanel.add(JLabel("Goal Decay Rate"), GridBagConstraints(0, nRow, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
            self.rightPanel.add(self.mcDecayRate, GridBagConstraints(1, __nRow_11, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        __nRow_12 = nRow
        nRow += 1
        self.rightPanel.add(JLabel(), GridBagConstraints(2, __nRow_12, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(5, 5, 5, 5), 5, 5))
        self.rightPanel.repaint()

    @SuppressWarnings("unchecked")
    def getParameter(self, name, defaultValue):
        """ generated source for method getParameter """
        try:
            if self.params.has(name):
                return self.params.get(name)
            else:
                return defaultValue
        except JSONException as je:
            return defaultValue

    def actionPerformed(self, arg0):
        """ generated source for method actionPerformed """
        if arg0.getSource() == self.strategy:
            self.layoutRightPanel()
        syncJSONtoUI()

    def changedUpdate(self, e):
        """ generated source for method changedUpdate """
        syncJSONtoUI()

    def insertUpdate(self, e):
        """ generated source for method insertUpdate """
        syncJSONtoUI()

    def removeUpdate(self, e):
        """ generated source for method removeUpdate """
        syncJSONtoUI()

    def stateChanged(self, arg0):
        """ generated source for method stateChanged """
        syncJSONtoUI()

    def syncJSONtoUI(self):
        """ generated source for method syncJSONtoUI """
        if settingUI:
            return
        self.params = getJSONfromUI()
        self.saveButton.setEnabled(self.savedParams == None or not self.params.__str__() == self.savedParams)

    def getJSONfromUI(self):
        """ generated source for method getJSONfromUI """
        newParams = JSONObject()
        try:
            if not self.name.getText().isEmpty():
                newParams.put("name", self.name.getText())
            newParams.put("strategy", self.strategy.getSelectedItem().__str__())
            newParams.put("metagameStrategy", self.metagameStrategy.getSelectedItem().__str__())
            newParams.put("stateMachine", self.stateMachine.getSelectedItem().__str__())
            newParams.put("cacheStateMachine", self.cacheStateMachine.isSelected())
            newParams.put("maxPlys", self.maxPlys.getModel().getValue())
            newParams.put("heuristicFocus", self.heuristicFocus.getModel().getValue())
            newParams.put("heuristicMobility", self.heuristicMobility.getModel().getValue())
            newParams.put("heuristicOpponentFocus", self.heuristicOpponentFocus.getModel().getValue())
            newParams.put("heuristicOpponentMobility", self.heuristicOpponentMobility.getModel().getValue())
            newParams.put("mcDecayRate", self.mcDecayRate.getModel().getValue())
        except JSONException as je:
            je.printStackTrace()
        return newParams

    settingUI = False

    def setUIfromJSON(self):
        """ generated source for method setUIfromJSON """
        self.settingUI = True
        try:
            if self.params.has("name"):
                self.name.setText(self.params.getString("name"))
            if self.params.has("strategy"):
                self.strategy.setSelectedItem(self.params.getString("strategy"))
            if self.params.has("metagameStrategy"):
                self.metagameStrategy.setSelectedItem(self.params.getString("metagameStrategy"))
            if self.params.has("stateMachine"):
                self.stateMachine.setSelectedItem(self.params.getString("stateMachine"))
            if self.params.has("cacheStateMachine"):
                self.cacheStateMachine.setSelected(self.params.getBoolean("cacheStateMachine"))
            if self.params.has("maxPlys"):
                self.maxPlys.getModel().setValue(self.params.getInt("maxPlys"))
            if self.params.has("heuristicFocus"):
                self.heuristicFocus.getModel().setValue(self.params.getInt("heuristicFocus"))
            if self.params.has("heuristicMobility"):
                self.heuristicMobility.getModel().setValue(self.params.getInt("heuristicMobility"))
            if self.params.has("heuristicOpponentFocus"):
                self.heuristicOpponentFocus.getModel().setValue(self.params.getInt("heuristicOpponentFocus"))
            if self.params.has("heuristicOpponentMobility"):
                self.heuristicOpponentMobility.getModel().setValue(self.params.getInt("heuristicOpponentMobility"))
            if self.params.has("mcDecayRate"):
                self.mcDecayRate.getModel().setValue(self.params.getInt("mcDecayRate"))
        except JSONException as je:
            je.printStackTrace()
        finally:
            self.settingUI = False

    def loadParamsJSON(self, fromFile):
        """ generated source for method loadParamsJSON """
        if not fromFile.exists():
            return
        self.associatedFile = fromFile
        self.associatedFileField.setText(self.associatedFile.getPath())
        self.params = JSONObject()
        try:
            try:
                while (line = br.readLine()) != None:
                    pdata.append(line)
            finally:
                br.close()
            self.params = JSONObject(pdata.__str__())
            self.savedParams = self.params.__str__()
            self.setUIfromJSON()
            self.syncJSONtoUI()
        except Exception as e:
            e.printStackTrace()

    def saveParamsJSON(self, saveAs):
        """ generated source for method saveParamsJSON """
        try:
            if saveAs or self.associatedFile == None:
                fc.setFileFilter(PlayerFilter())
                if returnVal == JFileChooser.APPROVE_OPTION and fc.getSelectedFile() != None:
                    if toFile.__name__.contains("."):
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__.substring(0, toFile.__name__.lastIndexOf(".")) + ".player")
                    else:
                        self.associatedFile = File(toFile.getParentFile(), toFile.__name__ + ".player")
                    self.associatedFileField.setText(self.associatedFile.getPath())
                else:
                    return
            bw.write(self.params.__str__())
            bw.close()
            self.savedParams = self.params.__str__()
            self.syncJSONtoUI()
        except IOException as ie:
            ie.printStackTrace()

    def saveButtonMethod(self):
        """ generated source for method saveButtonMethod """
        return AbstractAction("Save")

    def saveAsButtonMethod(self):
        """ generated source for method saveAsButtonMethod """
        return AbstractAction("Save As")

    def loadButtonMethod(self):
        """ generated source for method loadButtonMethod """
        return AbstractAction("Load")

    class PlayerFilter(FileFilter):
        """ generated source for class PlayerFilter """
        def accept(self, f):
            """ generated source for method accept """
            if f.isDirectory():
                return True
            return f.__name__.endsWith(".player")

        def getDescription(self):
            """ generated source for method getDescription """
            return "GGP Players (*.player)"
Beispiel #20
0
    def _initializeGui(self, callbacks):
        tab = JPanel()

        jLabel1 = JLabel("Original Hash:")
        jLabel2 = JLabel("Original message:")
        jLabel3 = JLabel("Message to append:")
        jLabel5 = JLabel("Max key length:")
        jTextField1 = JTextField("")
        jTextField2 = JTextField("")
        jTextField3 = JTextField("")
        jTextField4 = JTextField("128")
        jLabel4 = JLabel("Hashing functions")
        jCheckBox1 = JCheckBox("MD4")
        jCheckBox2 = JCheckBox("MD5")
        jCheckBox3 = JCheckBox("SHA1")
        jCheckBox4 = JCheckBox("SHA256")
        jCheckBox5 = JCheckBox("SHA512")
        jCheckBox1.setEnabled(False)
        jCheckBox2.setEnabled(False)
        jCheckBox3.setEnabled(False)
        jCheckBox4.setEnabled(False)
        jCheckBox5.setEnabled(False)
        jScrollPane1 = JScrollPane()
        jTable1 = JTable()
        jButton1 = JButton("Generate", actionPerformed=self.generate_attack)
        jButton1.setEnabled(False)
        jButton2 = JButton("Copy messages", actionPerformed=self.copy_messages)
        jButton3 = JButton("Copy hashes", actionPerformed=self.copy_hashes)

        self._tab = tab
        self._textfields = {
            "original_hash": jTextField1,
            "original_msg": jTextField2,
            "append_msg": jTextField3,
            "max_key_len": jTextField4,
        }
        self._checkboxes = {
            md4: jCheckBox1,
            md5: jCheckBox2,
            sha1: jCheckBox3,
            sha256: jCheckBox4,
            sha512: jCheckBox5,
        }

        self._table = jTable1
        self._extensions = {}
        self._hashes, self._messages = [], []

        # Hash field change event
        jTextField1.getDocument().addDocumentListener(HashChangeListener(self._checkboxes, self._textfields['original_hash'], jButton1))

        # Table columns
        jTable1.setModel(DefaultTableModel([],["#", "Type","New Message", "Hash"]))
        jScrollPane1.setViewportView(jTable1)
        # Table column width
        jTable1.getColumnModel().getColumn(0).setMaxWidth(50)
        jTable1.getColumnModel().getColumn(1).setMaxWidth(60)

        layout = GroupLayout(tab)
        tab.setLayout(layout)

        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField3, GroupLayout.DEFAULT_SIZE, 425, 32767)
                    .addComponent(jTextField2)
                    .addComponent(jTextField1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField4, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, 32767)))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCheckBox1)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCheckBox2)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCheckBox3)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCheckBox4)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCheckBox5))
                    .addComponent(jLabel4)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addGap(167, 167, 167))
            .addComponent(jScrollPane1)
        )
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(jCheckBox2)
                        .addComponent(jCheckBox3)
                        .addComponent(jCheckBox1)
                        .addComponent(jCheckBox4)
                        .addComponent(jCheckBox5)))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton1))
                .addGap(13, 13, 13)
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 971, 32767))
        )

        callbacks.customizeUiComponent(tab)
        callbacks.addSuiteTab(self)
class Plaso_ImportSettingsWithUISettingsPanel(
        IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exclude_File_Sources_CB.isSelected():
            self.local_settings.setSetting('Exclude_File_Sources', 'true')
        else:
            self.local_settings.setSetting('Exclude_File_Sources', 'false')

    # When button to find file is clicked then open dialog to find the file and return it.
    def Find_Plaso_Dir(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("All", ["*.*"])
        chooseFile.addChoosableFileFilter(filter)
        chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

        ret = chooseFile.showDialog(self.panel0, "Find Plaso Directory")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            Canonical_file = file.getCanonicalPath()
            #text = self.readPath(file)
            self.local_settings.setSetting('Plaso_Directory', Canonical_file)
            self.Program_Executable_TF.setText(Canonical_file)

    def Find_Plaso_File(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("All", ["*.*"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.panel0, "Find Plaso Storage File")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            Canonical_file = file.getCanonicalPath()
            #text = self.readPath(file)
            self.local_settings.setSetting('Plaso_Storage_File',
                                           Canonical_file)
            self.Plaso_Storage_File_TF.setText(Canonical_file)

    def setPlasoDirectory(self, event):
        self.local_settings.setSetting('Plaso_Directory',
                                       self.Program_Executable_TF.getText())

    def setPlasoStorageFile(self, event):
        self.local_settings.setSetting('Plaso_Storage_File',
                                       self.Plaso_Storage_File_TF.getText())

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup()
        self.gbPanel0 = GridBagLayout()
        self.gbcPanel0 = GridBagConstraints()
        self.panel0.setLayout(self.gbPanel0)

        self.Label_1 = JLabel("Plaso Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0)
        self.panel0.add(self.Label_1)

        self.Program_Executable_TF = JTextField(
            20, focusLost=self.setPlasoDirectory)
        self.Program_Executable_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Program_Executable_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Program_Executable_TF)

        self.Find_Program_Exec_BTN = JButton(
            "Find Dir", actionPerformed=self.Find_Plaso_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Find_Program_Exec_BTN)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.Find_Program_Exec_BTN)

        self.Blank_1 = JLabel(" ")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0)
        self.panel0.add(self.Blank_1)

        self.Label_1 = JLabel("Plaso Storage File")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0)
        self.panel0.add(self.Label_1)

        self.Plaso_Storage_File_TF = JTextField(
            20, focusLost=self.setPlasoStorageFile)
        self.Plaso_Storage_File_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Plaso_Storage_File_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Plaso_Storage_File_TF)

        self.Find_Storage_BTN = JButton("Find Storage File",
                                        actionPerformed=self.Find_Plaso_File)
        self.Find_Storage_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Find_Storage_BTN)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Find_Storage_BTN, self.gbcPanel0)
        self.panel0.add(self.Find_Storage_BTN)

        self.Blank_3 = JLabel(" ")
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_3, self.gbcPanel0)
        self.panel0.add(self.Blank_3)

        self.Exclude_File_Sources_CB = JCheckBox(
            "Exclude File Source", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Exclude_File_Sources_CB,
                                     self.gbcPanel0)
        self.panel0.add(self.Exclude_File_Sources_CB)

        self.Blank_4 = JLabel(" ")
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 17
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_4, self.gbcPanel0)
        self.panel0.add(self.Blank_4)

        self.Label_3 = JLabel("Message:")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_3, self.gbcPanel0)
        self.panel0.add(self.Label_3)

        self.Error_Message = JLabel("")
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 23
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0)
        self.panel0.add(self.Error_Message)

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Exclude_File_Sources_CB.setSelected(
            self.local_settings.getSetting('Exclude_File_Sources') == 'true')
        self.Program_Executable_TF.setText(
            self.local_settings.getSetting('Plaso_Directory'))
        self.Plaso_Storage_File_TF.setText(
            self.local_settings.getSetting('Plaso_Storage_File'))

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #22
0
class CuckooSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.tag_list = []
        self.initComponents()
        self.customizeComponents()
        self.path_to_cuckoo_exe = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cuckoo_api.exe")
 
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Submit_File_CB.isSelected():
            self.local_settings.setSetting('Submit_File', 'true')
            self.local_settings.setSetting('Submit_URL', 'false')
        else:
            self.local_settings.setSetting('Submit_File', 'false')
            
    def onchange_lb(self, event):
        self.local_settings.cleartag_list()
        list_selected = self.List_Box_LB.getSelectedValuesList()
        self.local_settings.setSetting('tag_list', str(list_selected))      

    def find_tags(self):
        
        sql_statement = "SELECT distinct(display_name) u_tag_name FROM content_tags INNER JOIN tag_names ON " + \
                        " content_tags.tag_name_id = tag_names.tag_name_id;"
        skCase = Case.getCurrentCase().getSleuthkitCase()
        dbquery = skCase.executeQuery(sql_statement)
        resultSet = dbquery.getResultSet()
        while resultSet.next():
             self.tag_list.append(resultSet.getString("u_tag_name"))
        dbquery.close()

    # Check to see if the Cuckoo server is available and you can talk to it
    def Check_Server(self, e):

       pipe = Popen([self.path_to_cuckoo_exe, self.Protocol_TF.getText(),self.IP_Address_TF.getText(), self.Port_Number_TF.getText(), "cuckoo_status" ], stdout=PIPE, stderr=PIPE)
        
       out_text = pipe.communicate()[0]
       self.Error_Message.setText("Cuckoo Status is " + out_text)
       #self.log(Level.INFO, "Cuckoo Status is ==> " + out_text)

           
    def setIPAddress(self, event):
        self.local_settings.setSetting('IP_Address', self.IP_Address_TF.getText()) 

    def setProtocol(self, event):
        self.local_settings.setSetting('Protocol', self.Protocol_TF.getText()) 

    def setPortNumber(self, event):
        self.local_settings.setSetting('Port_Number', self.Port_Number_TF.getText()) 

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Label_1 = JLabel("Protocol:")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Protocol_TF = JTextField(20, focusLost=self.setProtocol) 
        self.Protocol_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Protocol_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Protocol_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Label_2 = JLabel("Cuckoo IP Address")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.IP_Address_TF = JTextField(20, focusLost=self.setIPAddress) 
        self.IP_Address_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.IP_Address_TF, self.gbcPanel0 ) 
        self.panel0.add( self.IP_Address_TF ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_2, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_2 ) 

        self.Label_3 = JLabel("Port Number")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 

        self.Port_Number_TF = JTextField(20, focusLost=self.setPortNumber) 
        self.Port_Number_TF.setEnabled(True)
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 9 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Port_Number_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Port_Number_TF ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        
        self.Blank_5 = JLabel( "Tag to Choose: ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.find_tags()
        self.List_Box_LB = JList( self.tag_list, valueChanged=self.onchange_lb)
        self.List_Box_LB.setVisibleRowCount( 3 ) 
        self.scpList_Box_LB = JScrollPane( self.List_Box_LB ) 
        self.gbcPanel0.gridx = 4 
        self.gbcPanel0.gridy = 13 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpList_Box_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpList_Box_LB ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_6, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Submit_File_CB = JCheckBox("Submit a File", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Submit_File_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Submit_File_CB ) 

        # self.Submit_URL_CB = JCheckBox("Submit a URL", actionPerformed=self.checkBoxEvent)
        # self.gbcPanel0.gridx = 2 
        # self.gbcPanel0.gridy = 23 
        # self.gbcPanel0.gridwidth = 1 
        # self.gbcPanel0.gridheight = 1 
        # self.gbcPanel0.fill = GridBagConstraints.BOTH 
        # self.gbcPanel0.weightx = 1 
        # self.gbcPanel0.weighty = 0 
        # self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        # self.gbPanel0.setConstraints( self.Submit_URL_CB, self.gbcPanel0 ) 
        # self.panel0.add( self.Submit_URL_CB ) 

        self.Check_Server_Status_BTN = JButton( "Check Server Status", actionPerformed=self.Check_Server) 
        self.Check_Server_Status_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Check_Server_Status_BTN ) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Check_Server_Status_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Server_Status_BTN ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 21
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 


        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        #self.Exclude_File_Sources_CB.setSelected(self.local_settings.getExclude_File_Sources())
        #self.Run_Cuckoo_CB.setSelected(self.local_settings.getSetting('Submit_File') == 'true')
        #self.Import_Cuckoo_CB.setSelected(self.local_settings.getImport_Cuckoo())
        self.Port_Number_TF.setText(self.local_settings.getSetting('Port_Number'))
        self.IP_Address_TF.setText(self.local_settings.getSetting('IP_Address'))
        self.Protocol_TF.setText(self.local_settings.getSetting('Protocol'))
        

    # Return the settings used
    def getSettings(self):
        return self.local_settings
    def show_detectable_objects_dialog(self, e):
        parentComponent = SwingUtilities.windowForComponent(self.panel0)
        self.detectable_obejcts_dialog = JDialog(
            parentComponent, "List of Objects to Detect",
            ModalityType.APPLICATION_MODAL)
        panel = JPanel()
        self.detectable_obejcts_dialog.add(panel)
        gbPanel = GridBagLayout()
        gbcPanel = GridBagConstraints()
        panel.setLayout(gbPanel)

        y = 0
        x = 0
        for line in self.local_settings.getClassesOfInterest():
            if y > 15:
                y = 0
                x = x + 1

            class_check_box = JCheckBox(line['name'])
            self.classes_of_interest_checkboxes.append(class_check_box)
            class_check_box.setEnabled(True)
            class_check_box.setSelected(line['enabled'])
            class_check_box.addItemListener(self.on_class_checkbox_clicked)
            gbcPanel.gridx = x
            gbcPanel.gridy = y
            gbcPanel.gridwidth = 1
            gbcPanel.gridheight = 1
            gbcPanel.fill = GridBagConstraints.BOTH
            gbcPanel.weightx = 1
            gbcPanel.weighty = 1
            gbcPanel.anchor = GridBagConstraints.NORTH
            gbPanel.setConstraints(class_check_box, gbcPanel)
            panel.add(class_check_box)
            y = y + 1

        blank_1_L = JLabel(" ")
        blank_1_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 1
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_1_L, gbcPanel)
        panel.add(blank_1_L)

        deselect_all_button = JButton("Deselect all")
        deselect_all_button.setEnabled(True)
        deselect_all_button.addActionListener(self.on_deselect_all_clicked)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(deselect_all_button, gbcPanel)
        panel.add(deselect_all_button)

        select_all_button = JButton("Select all")
        select_all_button.setEnabled(True)
        select_all_button.addActionListener(self.on_select_all_clicked)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(select_all_button, gbcPanel)
        panel.add(select_all_button)

        blank_2_L = JLabel(" ")
        blank_2_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 3
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_2_L, gbcPanel)
        panel.add(blank_2_L)

        cancel_button = JButton("Cancel")
        cancel_button.setEnabled(True)
        cancel_button.addActionListener(
            self.on_cancel_classes_of_interest_click)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(cancel_button, gbcPanel)
        panel.add(cancel_button)

        save_button = JButton("Save")
        save_button.setEnabled(True)
        save_button.addActionListener(self.on_save_classes_of_interest_click)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(save_button, gbcPanel)
        panel.add(save_button)

        blank_3_L = JLabel(" ")
        blank_3_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 5
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_3_L, gbcPanel)
        panel.add(blank_3_L)

        self.detectable_obejcts_dialog.pack()
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        self.detectable_obejcts_dialog.setLocation(
            int((screenSize.getWidth() / 2) -
                (self.detectable_obejcts_dialog.getWidth() / 2)),
            int((screenSize.getHeight() / 2) -
                (self.detectable_obejcts_dialog.getHeight() / 2)))
        self.detectable_obejcts_dialog.setVisible(True)
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SPA Explorer')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        self.crawlingEvent = Event()
        self.crawlerThread = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))

        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(JLabel("Target:", SwingConstants.LEFT),
                            BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton('Start crawling',
                                    actionPerformed=self.toggleCrawl)
        self.setupPanel.add(self.toggleButton)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)

        # Options Panel :    [Buttons]  [          RegEx           ]
        self.optionsPanel = JPanel()
        self.optionsPanel.setLayout(
            BoxLayout(self.optionsPanel, BoxLayout.LINE_AXIS))

        # Button options panel :    [Add][Edit][Up][Down][Remove]

        self.buttonOptionsPanel = JPanel()
        self.buttonOptionsPanel.setLayout(
            BoxLayout(self.buttonOptionsPanel, BoxLayout.PAGE_AXIS))

        self.addRegexButton = JButton('Add', actionPerformed=self.addRegex)
        self.buttonOptionsPanel.add(self.addRegexButton)

        self.editRegexButton = JButton('Edit', actionPerformed=self.editRegex)
        self.buttonOptionsPanel.add(self.editRegexButton)

        self.moveRegexUpButton = JButton('Move up',
                                         actionPerformed=self.moveRegexUp)
        self.buttonOptionsPanel.add(self.moveRegexUpButton)

        self.moveRegexDownButton = JButton('Move down',
                                           actionPerformed=self.moveRegexDown)
        self.buttonOptionsPanel.add(self.moveRegexDownButton)

        self.removeRegexButton = JButton('Remove',
                                         actionPerformed=self.removeRegex)
        self.buttonOptionsPanel.add(self.removeRegexButton)

        self.buttonOptionsPanel.add(Box.createVerticalGlue())

        self.optionsPanel.add(self.buttonOptionsPanel)

        self.optionsPanel.add(Box.createHorizontalStrut(20))

        self.regexTableModel = RegexTableModel([x for x in regex])
        self.regexTable = Table(self.regexTableModel)
        self.regexScrollPane = JScrollPane(self.regexTable)

        self.optionsPanel.add(self.regexScrollPane)

        self._topPanel.add(self.optionsPanel, BorderLayout.CENTER)
        self._splitpane.setTopComponent(self._topPanel)

        # Bottom Panel
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        #self._bottomPanel.setLayout(BoxLayout(self._bottomPanel,BoxLayout.PAGE_AXIS))

        # Status bar
        self.crawlStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.crawlStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.crawlStatusLabel = JLabel("Ready to crawl", SwingConstants.LEFT)
        self.crawlStatusPanel.add(self.crawlStatusLabel)

        # Result Table
        self.resultTableModel = Result([])
        self.resultTable = Table(self.resultTableModel)
        self.resultTable.setAutoCreateRowSorter(True)
        self.resultScrollPane = JScrollPane(self.resultTable)

        # Result Table popup menu
        def selectWhenRightClickEvent(event):
            def select(e):
                rowAtPoint = self.resultTable.rowAtPoint(
                    SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                                Point(0, 0), self.resultTable))
                if rowAtPoint > -1:
                    self.resultTable.setRowSelectionInterval(
                        rowAtPoint, rowAtPoint)

            SwingUtilities.invokeLater(CrawlerRunnable(select, (event, )))

        self.resultTablePopupMenu = JPopupMenu(
            popupMenuWillBecomeVisible=selectWhenRightClickEvent)
        self.resultTablePopupMenu.add(
            JMenuItem("Send to scanner", actionPerformed=self.sendToScanner))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to repeater", actionPerformed=self.sendToRepeater))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to intruder", actionPerformed=self.sendToIntruder))
        self.resultTablePopupMenu.add(
            JMenuItem("Send to spider", actionPerformed=self.sendToSpider))

        self.resultTable.setComponentPopupMenu(self.resultTablePopupMenu)

        self._bottomPanel.add(self.resultScrollPane, BorderLayout.CENTER)
        self._bottomPanel.add(self.crawlStatusPanel, BorderLayout.SOUTH)

        self._splitpane.setBottomComponent(self._bottomPanel)
        self._splitpane.setDividerLocation(300 +
                                           self._splitpane.getInsets().left)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)

        explorerMenu = ExplorerMenu(self)
        callbacks.registerContextMenuFactory(explorerMenu)
        print "SPA Explorer custom menu loaded"

        #print "Loading chrome driver"
        #a = Test(os.path.dirname(os.path.realpath('selenium-client.jar')) + '/chromedriver.exe')
        #print "Chrome driver started"

        print "Burp SPA Explorer loaded"

    # Button Actions

    def getURLComponents(self, url):
        return (url.getHost(), (443 if url.getProtocol() == 'https' else 80)
                if url.getPort() == -1 else url.getPort(),
                url.getProtocol() == 'https')

    def sendToScanner(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.doActiveScan(urlComp[0], urlComp[1], urlComp[2],
                                     self._helpers.buildHttpRequest(url))

    def sendToRepeater(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.sendToRepeater(urlComp[0], urlComp[1], urlComp[2],
                                       self._helpers.buildHttpRequest(url),
                                       None)

    def sendToIntruder(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        urlComp = self.getURLComponents(url)
        self._callbacks.sendToIntruder(urlComp[0], urlComp[1], urlComp[2],
                                       self._helpers.buildHttpRequest(url))

    def sendToSpider(self, event):
        url = URL(
            self.resultTable.getValueAt(self.resultTable.getSelectedRow(), 1))
        self._callbacks.sendToSpider(url)

    def addRegex(self, event):
        optionPane = JOptionPane()
        dialog = optionPane.createDialog(self._splitpane, "Add RegEx")

        panel = JPanel(GridLayout(0, 2))
        panel.setBorder(EmptyBorder(10, 10, 10, 10))

        nameField = JTextField('', 15)
        panel.add(JLabel("Name:", SwingConstants.LEFT))
        panel.add(nameField)

        regexField = JTextField('', 15)
        panel.add(JLabel("RegEx:", SwingConstants.LEFT))
        panel.add(regexField)

        crawlField = JCheckBox()
        panel.add(JLabel("Crawl:", SwingConstants.LEFT))
        panel.add(crawlField)

        def closeDialog(event):
            if len(nameField.text) == 0 or len(regexField.text) == 0:
                JOptionPane.showMessageDialog(self._splitpane,
                                              "Name or RegEx can't be empty",
                                              "Error",
                                              JOptionPane.ERROR_MESSAGE)
                return
            self.regexTableModel.addRow(
                [nameField.text, regexField.text,
                 crawlField.isSelected()])
            dialog.hide()

        addButton = JButton('OK', actionPerformed=closeDialog)
        panel.add(addButton)

        dialog.setSize(600, 200)
        dialog.setContentPane(panel)
        self._callbacks.customizeUiComponent(dialog)
        dialog.show()

        return True

    def editRegex(self, event):
        selectedRowIdx = self.regexTable.getSelectedRow()
        if selectedRowIdx == -1: return False
        selectedRow = self.regexTableModel.data[selectedRowIdx]

        optionPane = JOptionPane()
        dialog = optionPane.createDialog(self._splitpane, "Edit RegEx")

        panel = JPanel(GridLayout(0, 2))
        panel.setBorder(EmptyBorder(10, 10, 10, 10))

        nameField = JTextField('', 15)
        nameField.text = selectedRow[0]
        panel.add(JLabel("Name:", SwingConstants.LEFT))
        panel.add(nameField)

        regexField = JTextField('', 15)
        regexField.text = selectedRow[1]
        panel.add(JLabel("RegEx:", SwingConstants.LEFT))
        panel.add(regexField)

        crawlField = JCheckBox()
        crawlField.setSelected(selectedRow[2])
        panel.add(JLabel("Crawl:", SwingConstants.LEFT))
        panel.add(crawlField)

        def closeDialog(event):
            if len(nameField.text) == 0 or len(regexField.text) == 0:
                JOptionPane.showMessageDialog(self._splitpane,
                                              "Name or RegEx can't be empty",
                                              "Error",
                                              JOptionPane.ERROR_MESSAGE)
                return
            self.regexTableModel.editRow(
                selectedRowIdx,
                [nameField.text, regexField.text,
                 crawlField.isSelected()])
            dialog.hide()

        editButton = JButton('OK', actionPerformed=closeDialog)
        panel.add(editButton)

        dialog.setSize(600, 200)
        dialog.setContentPane(panel)
        self._callbacks.customizeUiComponent(dialog)
        dialog.show()
        return True

    def moveRegexDown(self, event):
        idxs = self.regexTable.getSelectedRows()
        if self.regexTableModel.getRowCount() - 1 in idxs: return False

        self.regexTable.clearSelection()
        for i in sorted(idxs)[::-1]:
            self.regexTableModel.moveDown(i)
            self.regexTable.addRowSelectionInterval(i + 1, i + 1)
        return True

    def moveRegexUp(self, event):
        idxs = self.regexTable.getSelectedRows()
        if 0 in idxs: return False

        self.regexTable.clearSelection()
        for i in sorted(idxs):
            self.regexTableModel.moveUp(i)
            self.regexTable.addRowSelectionInterval(i - 1, i - 1)
        return True

    def removeRegex(self, event):
        idx = self.regexTable.getSelectedRows()
        for i in sorted(idx)[::-1]:
            self.regexTableModel.removeRow(i)
        return True

    # Implement ITab

    def getTabCaption(self):
        return "SPA Explorer"

    def getUiComponent(self):
        return self._splitpane

    def crawl(self, event):
        print("Starting")

        host = self.hostField.text

        if host.find("://") == -1:
            host = "http://" + host

        try:
            self._callbacks.includeInScope(URL(host))
        except:
            JOptionPane.showMessageDialog(self._splitpane,
                                          "Can't add host to scope", "Error",
                                          JOptionPane.ERROR_MESSAGE)
            return

        self.resultTableModel.clearAllRow()

        self.crawlingEvent.set()
        self.crawlerThread = Thread(target=self.crawl_thread, args=(host, ))
        self.crawlerThread.start()
        print("Started")

    def stopCrawling(self, event):
        print("Clear event")
        self.crawlingEvent.clear()

        # Disable button
        if self.toggleButton.text == "Stop crawling":  # If button is still "Stop crawling" (Thread still running), disable button
            self.toggleButton.setEnabled(False)

    def toggleCrawl(self, event):
        if (self.crawlerThread == None or not self.crawlerThread.is_alive()):
            self.crawl(event)
            #self.toggleButton.setText("Start crawling")
        else:
            self.stopCrawling(event)
            #self.toggleButton.setText("Stop crawling")

    def crawl_thread(self, host):
        # print(self, host)
        print("Crawl thread started")

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setText, ("Stop crawling", )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.addRegexButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.editRegexButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexUpButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexDownButton.setEnabled, (False, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.removeRegexButton.setEnabled, (False, )))

        pageType = {}  # url -> type
        pageContentHash = {}  # hash -> url list

        def concatURL(baseURL, link):
            return URL(URL(baseURL), link).toString()

        def makeRequest(url):
            url = URL(url)

            if not self._callbacks.isInScope(url):
                #self.logger.addRow(url.toString()+" is out of scope")
                raise ValueError("URL is out of scope")

            prot = url.getProtocol()
            host = url.getHost()
            port = url.getPort()
            if port == -1:
                port = 80 if prot == "http" else 443

            httpService = self._helpers.buildHttpService(host, port, prot)

            reqRes = self._callbacks.makeHttpRequest(
                httpService, self._helpers.buildHttpRequest(url))
            self._callbacks.addToSiteMap(reqRes)
            resp = reqRes.getResponse()
            respInfo = self._helpers.analyzeResponse(resp)

            respBody = self._helpers.bytesToString(
                resp[respInfo.getBodyOffset():])
            return respBody

        def matchRegex(baseURL, res):
            toRet = []
            for (name, regStr, ret) in self.regexTableModel.data:
                matchObj = re.findall(regStr, res, re.M | re.I)
                for i in matchObj:
                    try:
                        if i.find('http://') == 0 or i.find('https://') == 0:
                            url = i
                        elif i[0] == '/':
                            url = host + i
                        else:
                            url = host + '/' + i

                        if url not in pageType:
                            pageType[url] = name
                            SwingUtilities.invokeLater(
                                CrawlerRunnable(self.resultTableModel.addRow,
                                                ([name, url], )))

                            if ret:
                                toRet.append(url)
                    except:
                        print("Error when trying to save result ", i,
                              sys.exc_info()[0],
                              sys.exc_info()[1])
            return toRet

        def getAllLink(url):
            toRet = []
            try:
                print("Making request", url)
                r = makeRequest(url)
                print("Done request", len(r))
                hash = hashlib.sha256(r.encode('utf-8')).hexdigest()
                #print(r.text)
                if hash in pageContentHash:
                    print("Content hash is the same as ",
                          pageContentHash[hash][0])
                    pageContentHash[hash].append(url)
                    return toRet
                else:
                    pageContentHash[hash] = [url]

                toRet += matchRegex(url, r)
            except BaseException as e:
                print("Error while making request to ", url, e)
            except:
                print("Error while making request to ", url,
                      sys.exc_info()[0],
                      sys.exc_info()[1])
            return toRet

        crawledPage = [host]
        crawledNow = 0

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.resultTableModel.addRow,
                            (["TARGET", host], )))

        while crawledNow < len(crawledPage):
            if self.crawlingEvent.is_set():
                print("Crawling", crawledPage[crawledNow])
                SwingUtilities.invokeLater(
                    CrawlerRunnable(self.crawlStatusLabel.setText,
                                    ("Crawling " + crawledPage[crawledNow], )))
                for i in getAllLink(crawledPage[crawledNow]):
                    if i not in crawledPage:
                        print("ADD:", i)
                        crawledPage.append(i)
                crawledNow += 1
            else:
                print("Stop Requested")
                break

        print(crawledNow, crawledPage)
        output = []

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setText, ("Start crawling", )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.toggleButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.addRegexButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.editRegexButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexUpButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.moveRegexDownButton.setEnabled, (True, )))
        SwingUtilities.invokeLater(
            CrawlerRunnable(self.removeRegexButton.setEnabled, (True, )))

        SwingUtilities.invokeLater(
            CrawlerRunnable(self.crawlStatusLabel.setText,
                            ("Ready to crawl", )))

        self.crawlingEvent.clear()
        print("Completed")
Beispiel #25
0
class BurpExtender(IBurpExtender, IHttpListener, ITab, IContextMenuFactory):

    #
    # implement IBurpExtender
    #

    def	registerExtenderCallbacks(self, callbacks):
        self.isLock = False
        self.magicParam = None
        self.scanMagicParam = None
        self.scanMessageInfo = None
        self.repeaterMessageInfo = None
        self.currentScanItem = None
        self.scanInsertionPoint = {}

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        self._callbacks = callbacks
        # set our extension name
        callbacks.setExtensionName("ZIP File Raider")
        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
        # register context menu
        callbacks.registerContextMenuFactory(self)

        self.initGUI()
        callbacks.addSuiteTab(self)
        print "[+]Init burp extender"

    ## implement IContextMenuFactory
    def createMenuItems(self, invocation):
        #get only  selected message
        self.messageInfo = invocation.getSelectedMessages()[0]
        menuItemList = ArrayList()
        menuItemList.add(JMenuItem("Send request to ZIP File Raider extender Repeater", actionPerformed = self.contextRepeaterClick))
        menuItemList.add(JMenuItem("Send request to ZIP File Raider extender Scanner", actionPerformed = self.contextScannerClick))
        return menuItemList

    def contextRepeaterClick(self, event):
        self.sendRequestToExtender("Repeater")

    def contextScannerClick(self, event):
        self.sendRequestToExtender("Scanner")

    def sendRequestToExtender(self, tab):
        #get filename
        zipfilename = "Archive(default_name).zip"
        filenameParam = self._helpers.getRequestParameter(self.messageInfo.getRequest(), "filename")
        if filenameParam == None:
            print "This request is not contain upload file"
            return
        if filenameParam.getType() == IParameter.PARAM_MULTIPART_ATTR:
            zipfilename = filenameParam.getValue()

        #get magicparam
        requestString = self._helpers.bytesToString(self.messageInfo.getRequest())
        magicParamStart, magicParamEnd = None, None

        initialIndex = filenameParam.getValueStart() - 12
        for i in range(initialIndex, 0 , -1):
            if requestString[i] == '"' :
                if magicParamEnd == None:
                    magicParamEnd = i
                elif requestString[i-6:i] == " name=":
                    magicParamStart = i + 1
                    break

        if magicParamStart == None:
            print "[-]Cannot detect file parameter name"
            return
        else:
            magicparam = requestString[magicParamStart:magicParamEnd]

        dataParameter = self._helpers.getRequestParameter(self.messageInfo.getRequest(), magicparam)
        #Check is zip upload or not
        if not dataParameter is None:
            value = dataParameter.getValue()
            if tab == "Repeater":
                self.repeaterMessageInfo = self.messageInfo
                self.extractZipFile(value, TEMP_PATH)
                self.showListFileDir(TEMP_PATH)
                self.repeaterZipFilename = zipfilename
                self.magicParam = magicparam
            else:
                self.removeDirectory(RUNNING_SCAN_PATH)
                self.scanTemplateFileName = []
                self.insertionPointCount = 0
                self.scanMessageInfo = self.messageInfo
                self.extractZipFile(value, SCAN_TEMP_PATH)
                self.showScanListFileDir(SCAN_TEMP_PATH)
                self.scanZipFilename = zipfilename
                self.scanMagicParam = magicparam
        else:
            print "no data param"

    ## implement IHttpListener
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        # only process requests
        if not messageIsRequest:
            return

        extenderFlag = self._helpers.getRequestParameter(messageInfo.getRequest(), EXTENDER_FLAG)

        if not extenderFlag is None:

            while self.isLock:
                sleep(0.5)
                # print "sleep"
                pass 
            self.isLock = True

            payloads = []

            for i in range(0, self.insertionPointCount):
                paramData = self._helpers.getRequestParameter(messageInfo.getRequest(), PAYLOAD_PARAM_NAME % i)
                try:
                    payloads.append(paramData.getValue())
                except Exception as e :
                    payloads.append("")

            payloadsIndex = 0

            for template in self.scanTemplateFileName:
                newFileContent = ""

                fileContentString = self._helpers.bytesToString(self.runningScanTemplate[template])
                contentStrings = fileContentString.split(INSETION_POINT_SYMBOL)
                for i, s in enumerate(contentStrings):
                    newFileContent += s
                    if i == len(contentStrings) - 1:
                        break
                    else:
                        newFileContent += payloads[payloadsIndex]
                        payloadsIndex += 1

                newFileContent = self._helpers.stringToBytes(newFileContent)
                try:
                    self.writeFile(RUNNING_SCAN_PATH + os.sep + template, newFileContent)
                except Exception as e :
                    print "Error1 %s" % e

            # ZipAndGo
            try:
                self.compressToZip(SCAN_ZIP_NAME, RUNNING_SCAN_PATH + os.sep + SCAN_TEMP_PATH)
                zipContent = self.readFile(SCAN_ZIP_NAME + ".zip")
                newRequest = self._helpers.updateParameter(messageInfo.getRequest(), self._helpers.buildParameter(self.scanMagicParam, zipContent, IParameter.PARAM_BODY))

                # add filename
                if self.isScanZipFilename:
                    filenamePayload = self._helpers.getRequestParameter(messageInfo.getRequest(), PAYLOAD_FILENAME).getValue()
                    newRequest = self.addMultipartFilenameParam(filenamePayload ,newRequest, self.scanMagicParam)
                    newRequest = self._helpers.removeParameter(newRequest, self._helpers.buildParameter(PAYLOAD_FILENAME, "none", IParameter.PARAM_BODY))
                else:
                    newRequest = self.addMultipartFilenameParam(self.scanZipFilename ,newRequest, self.scanMagicParam)
                
                #remove unnecessary param
                for i in range(0, self.insertionPointCount):
                    newRequest = self._helpers.removeParameter(newRequest, self._helpers.buildParameter(PAYLOAD_PARAM_NAME%i, "none", IParameter.PARAM_BODY))
                newRequest = self._helpers.removeParameter(newRequest, self._helpers.buildParameter(EXTENDER_FLAG, "none", IParameter.PARAM_BODY))
                
                # set to newRequest
                messageInfo.setRequest(newRequest)
            except Exception as e :
                print "Error2 %s" % e

            # print "[+]request sent"
            self.isLock = False
            return

        else:
            # not from our extender
            return

    def extractZipFile(self, data, des_path):
        b = base64.b64encode(data)
        zipfile = ZipFile(StringIO(base64.b64decode(b)))
        # remove tmp folder
        self.removeDirectory(des_path)
        zipfile.extractall(des_path)
        print "[*]extract done"

    def compressToZip(self, zipnName, zipDirPath):
        make_archive(zipnName, "zip", zipDirPath)
        return

    def removeDirectory(self, rm_path):
        if not os.path.exists(rm_path):
            return
        try:
            rmtree(rm_path)
        except Exception as e :
            print "[-]Error while remove %s folder %s" % (rm_path, e)

    def showListFileDir(self, mypath):
        self.filename = []
        self.fileDirList = []
        self.absFilePath = {}
        for root, dirs, files in os.walk(mypath):
            path = root.split(os.sep)
            fname = os.path.basename(root)
            dirPath = (len(path) - 3) * "---" + fname
            self.fileDirList.append(dirPath)
            self.filename.append(fname)
            for file in files:
                filePath = (len(path)-2) * "---" + file
                self.fileDirList.append(filePath)
                self.filename.append(file)
                self.absFilePath[filePath] = root + os.sep + file
        self.fileDirList.remove(TEMP_PATH.split(os.sep)[1])
        self.filename.remove(TEMP_PATH.split(os.sep)[1])
        self.dirList.setListData(self.fileDirList)

    def showScanListFileDir(self, mypath):
        self.scanFilename = []
        self.scanFileDirList = []
        self.scanAbsFilePath = {}
        for root, dirs, files in os.walk(mypath):
            path = root.split(os.sep)
            fname = os.path.basename(root)
            dirPath = (len(path) - 3) * "---" + fname
            self.scanFileDirList.append(dirPath)
            self.scanFilename.append(fname)
            for file in files:
                filePath = (len(path)-2) * "---" + file
                self.scanFileDirList.append(filePath)
                self.scanFilename.append(file)
                self.scanAbsFilePath[filePath] = root + os.sep + file
        self.scanFileDirList.remove(SCAN_TEMP_PATH.split(os.sep)[1])
        self.scanFilename.remove(SCAN_TEMP_PATH.split(os.sep)[1])
        self.scanDirList.setListData(self.scanFileDirList)

    def listSelect(self, event):
        index = self.dirList.selectedIndex
        key = self.fileDirList[index]
        self.lblFilename.text = self.filename[index]
        if key in self.absFilePath:
            self.editField.setMessage(self.readFile(self.absFilePath[key]), False)
        else:
            #dir
            self.editField.setMessage("/*Directory*/", False)

    def scanListSelect(self, event):
        index = self.scanDirList.selectedIndex
        key = self.scanFileDirList[index]
        self.scanLblFilename.text = self.scanFilename[index]
        if key in self.scanAbsFilePath:
            #file
            if self.scanAbsFilePath[key] in self.scanTemplateFileName:
                content = self.readFile(self.scanAbsFilePath[key])
                for idx, el in enumerate(self.scanInsertionPoint[self.scanAbsFilePath[key]]):
                    # print el
                    content = self.setInsertionMark(content, el[0] + idx*2, el[1] + idx*2)
                self.scanEditField.setMessage(content, False)
            else:
                self.scanEditField.setMessage(self.readFile(self.scanAbsFilePath[key]), False)
        else:
            #dir
            self.scanEditField.setMessage("/*Directory*/", False)

    def readFile(self, path):
        file = open(path, "rb")
        fileContent = file.read()
        file.close()
        return fileContent

    def writeFile(self, path, content):
        file = open(path, "wb")
        file.write(content)
        file.close()

    def updateContentLength(self, request):
        request = self._helpers.addParameter(request, self._helpers.buildParameter("dump", "none", IParameter.PARAM_BODY))
        request = self._helpers.removeParameter(request, self._helpers.buildParameter("dump", "none", IParameter.PARAM_BODY))
        return request

    def addMultipartFilenameParam(self, zipfilename, request, magicparam):
        dataParameter = self._helpers.getRequestParameter(request, magicparam)
        getFilenameOffset = dataParameter.getNameEnd() + 1

        filename = '; filename="%s"' % zipfilename
        try:
            requestString = self._helpers.bytesToString(request)
            requestString = requestString[:getFilenameOffset] + filename + requestString[getFilenameOffset:]
            request = self._helpers.stringToBytes(requestString)
            request = self.updateContentLength(request)
            return request
        except Exception as e :
            print(e)
            return

    def makeRequest(self, zipContent):
        print "[+]thread is running (making request)"
        request = self.repeaterMessageInfo.getRequest()
        request = self._helpers.updateParameter(request, self._helpers.buildParameter(self.magicParam, zipContent, IParameter.PARAM_BODY))
        
        # add filename
        request = self.addMultipartFilenameParam(self.repeaterZipFilename ,request, self.magicParam)

        # sending request
        result = self._callbacks.makeHttpRequest(self.repeaterMessageInfo.getHttpService(), request)
        self.requestPanel.setMessage(result.getRequest(), True)
        try:
            self.responsePanel.setMessage(result.getResponse(), False)
        except Exception as e :
            self.responsePanel.setMessage("An error occured", False)
        print "[+]done"

    def btnGoClick(self, event):
        if self.repeaterMessageInfo == None:
            return
        self.saveEditFile()
        self.compressToZip(ZIP_NAME, TEMP_PATH)
        zipContent = self.readFile(ZIP_NAME + ".zip")

        t1 = threading.Thread(target=self.makeRequest, args=[zipContent])
        t1.start()
        # print "[+]thread start"

    def saveEditFile(self):
        if self.repeaterMessageInfo == None:
            return
        index = self.dirList.selectedIndex
        key = self.fileDirList[index]

        if key in self.absFilePath:
            #file
            content = self.editField.getMessage()
            self.writeFile(self.absFilePath[key], content)

    def btnSaveClick(self, event):
        self.saveEditFile()

    def btnClearClick(self, event):
        self.dirList.setListData([])
        self.editField.setMessage("", False)
        self.lblFilename.text = "File name"
        self.requestPanel.setMessage("", True)
        self.responsePanel.setMessage("", False)
        self.repeaterMessageInfo = None
        self.removeDirectory(TEMP_PATH)

    def btnResetRepeaterClick(self, event):
        print "btnClick"
        if self.repeaterMessageInfo == None:
            print "return"
            return
        dataParameter = self._helpers.getRequestParameter(self.repeaterMessageInfo.getRequest(), self.magicParam)
        value = dataParameter.getValue()
        # print value
        self.extractZipFile(value, TEMP_PATH)
        # self.sendRequestToExtender("Repeater")
        self.listSelect(event)

    def scanBtnClearClick(self, event):
        self.scanTemplateFileName = []
        self.scanInsertionPoint = {}
        self.insertionPointCount = 0
        self.scanDirList.setListData([])
        self.scanEditField.setMessage("", False)
        self.scanLblFilename.text = "File name"
        self.scanMessageInfo = None
        self.removeDirectory(SCAN_TEMP_PATH)
        self.removeDirectory(RUNNING_SCAN_PATH)

    def scanBtnClearInsClick(self, event):
        self.scanTemplateFileName = []
        self.scanInsertionPoint = {}
        self.insertionPointCount = 0
        self.removeDirectory(RUNNING_SCAN_PATH)
        self.scanListSelect(event)

    def addInsertionPoint(self, insStart, insEnd):
        index = self.scanDirList.selectedIndex
        key = self.scanFileDirList[index]

        if key in self.scanAbsFilePath:
            #file
            if not self.scanAbsFilePath[key] in self.scanTemplateFileName:
                self.scanTemplateFileName.append(self.scanAbsFilePath[key])
                self.scanInsertionPoint[self.scanAbsFilePath[key]] = [[insStart, insEnd]]
            else:
                offset = len(self.scanInsertionPoint[self.scanAbsFilePath[key]]) * 2
                self.scanInsertionPoint[self.scanAbsFilePath[key]].append([insStart - offset, insEnd - offset])

    def btnSetInsertionPointClick(self, event):
        if self.scanMessageInfo == None:
            return
        # show in UI
        insertionPointChar = u"§"

        selectedText = self.scanEditField.getSelectedData()
        if selectedText == None:
            print "[-]No selected area"
            return
        start = self.scanEditField.getSelectionBounds()[0]
        end = start + len(selectedText)

        requestString = self.scanEditField.getMessage()

        newRequestString = self.setInsertionMark(requestString, start, end)

        self.scanEditField.setMessage(newRequestString, False)

        #save insertion point
        self.addInsertionPoint(start, end)
        self.insertionPointCount += 1

    def setInsertionMark(self, requestString, start, end):
        insertionPointChar = u"§"
        selectedText = requestString[start:end]
        newRequestString = self._helpers.bytesToString(requestString[:start]) + insertionPointChar + self._helpers.bytesToString(selectedText) + insertionPointChar + self._helpers.bytesToString(requestString[end:])
        newRequestString = self._helpers.stringToBytes(newRequestString)
        return newRequestString

    def prepareScanRequest(self, request):
        for i in range(0, self.insertionPointCount):
            param = self._helpers.buildParameter(PAYLOAD_PARAM_NAME % i, self.runningScanDefaultPayload[i], IParameter.PARAM_BODY)
            request = self._helpers.addParameter(request, param)
        # add flag
        param = self._helpers.buildParameter(EXTENDER_FLAG, "1", IParameter.PARAM_BODY)
        request = self._helpers.addParameter(request, param)
        # add filename scan
        if self.checkboxScanFilename.isSelected():
            self.isScanZipFilename = True
            param = self._helpers.buildParameter(PAYLOAD_FILENAME, self.scanZipFilename, IParameter.PARAM_BODY)
            request = self._helpers.addParameter(request, param)
        else:
            self.isScanZipFilename = False
        return request

    def prepareScanInsertionOffset(self, request, paramName):
        param = self._helpers.getRequestParameter(request, paramName)
        startOffset = param.getValueStart()
        endOffset = param.getValueEnd()
        return array([startOffset, endOffset], 'i')

    def btnScanClick(self, event):
        if self.scanMessageInfo == None:
            return
        self.runningScanTemplate = {}
        self.runningScanDefaultPayload = []
        self.removeDirectory(RUNNING_SCAN_PATH)

        os.makedirs(RUNNING_SCAN_PATH)
        copytree(SCAN_TEMP_PATH, RUNNING_SCAN_PATH + os.sep + SCAN_TEMP_PATH)

        # self.insertionPointCount = 3
        insertionPointNo = 0

        # read template
        for template in self.scanTemplateFileName:
            t = self._helpers.bytesToString(self.readFile(template))
            temp = ""
            insertionPointNoOfFile = 0
            # point to begin of file
            insPoint = []
            for el in self.scanInsertionPoint[template]:
                insPoint.append(el[0])
                insPoint.append(el[1])
            insPoint.sort()
            currentPoint = 0
            for i in xrange(0, len(insPoint) - 1, 2):
                # print p
                temp += t[currentPoint:insPoint[i]] + INSETION_POINT_SYMBOL
                currentPoint = insPoint[i + 1]
                self.runningScanDefaultPayload.append(t[insPoint[i]:insPoint[i + 1]])
                insertionPointNo += 1
            temp += t[currentPoint:]
            temp = self._helpers.stringToBytes(temp)

            self.runningScanTemplate[template] = temp

        if insertionPointNo != self.insertionPointCount:
            print "[-]Error while parsing template"
            return

        #send to scanner
        httpService = self.scanMessageInfo.getHttpService()
        # request = self.scanMessageInfo.getRequest()
        request = self.prepareScanRequest(self.scanMessageInfo.getRequest())
        isHttps = True if httpService.getProtocol() == 'https' else False
        insertionOffset = []

        for i in range(0, self.insertionPointCount):
            insertionOffset.append(self.prepareScanInsertionOffset(request,PAYLOAD_PARAM_NAME % i))
        if self.isScanZipFilename:
            insertionOffset.append(self.prepareScanInsertionOffset(request,PAYLOAD_FILENAME))
        self.currentScanItem = self._callbacks.doActiveScan(httpService.getHost(), httpService.getPort(), isHttps, request, insertionOffset)
        print "[*]Scanner is running"
        self._callbacks.issueAlert("Send to Active Scanner")
        t = threading.Thread(target=self.checkScannerStatus)
        t.start()
        
    def checkScannerStatus(self):
        self.disableScanUi()
        while True:
            if self.currentScanItem == None:
                self.scannerStatusLabel.text = "<html><i style='color:grey'> Canceled</i></html>"
                self.enableScanUi()
                return
            else:
                status = self.currentScanItem.getStatus()
                if status == "finished":
                    self.scannerStatusLabel.text = "<html><i style='color:green'> Complete</i></html>"
                    self.enableScanUi()
                    self._callbacks.issueAlert("Scan Complete")
                    return
                self.scannerStatusLabel.text = "<html><i style='color:orange'> %s</i></html>" % (status)
            #schedule run every 1 sec
            sleep(1)

    def cancelScan(self, event):
        self.currentScanItem.cancel()
        self.currentScanItem = None
        self.enableScanUi()

    def disableScanUi(self):
        self.scanBtnCancel.setEnabled(True)
        self.scanBtnGo.setEnabled(False)
        self.scanBtnSave.setEnabled(False)
        self.scanBtnClearInsertionPoint.setEnabled(False)
        self.scanBtnClear.setEnabled(False)
        self.scanDirList.setEnabled(False)
    
    def enableScanUi(self):
        self.scanBtnCancel.setEnabled(False)
        self.scanBtnGo.setEnabled(True)
        self.scanBtnSave.setEnabled(True)
        self.scanBtnClearInsertionPoint.setEnabled(True)
        self.scanBtnClear.setEnabled(True)
        self.scanEditField.setMessage("", False)
        self.scanDirList.setEnabled(True)

    #init extender GUI
    def initGUI(self):
        #
        # Manual tab
        #
        tabPane = JTabbedPane(JTabbedPane.TOP)
        reqRestabPane = JTabbedPane(JTabbedPane.TOP)
        splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        tabPane.addTab("Repeater", splitPane)
        splitPane2 = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        splitPane.setLeftComponent(splitPane2)

        panel1 = JPanel()
        panel2 = JPanel()

        splitPane2.setLeftComponent(panel1)
        splitPane2.setRightComponent(panel2)
        splitPane.setRightComponent(reqRestabPane)

        panel1.setLayout(BoxLayout(panel1,BoxLayout.Y_AXIS))
        panel2.setLayout(BoxLayout(panel2,BoxLayout.Y_AXIS))

        self.requestPanel = self._callbacks.createMessageEditor(None, False)
        self.responsePanel = self._callbacks.createMessageEditor(None, False)

        label1 = JLabel("files and folders")
        self.lblFilename = JLabel("File name")
        label3 = JLabel("Response")
        self.editField = self._callbacks.createMessageEditor(None, True)
        self.dirList = JList([], valueChanged = self.listSelect)

        listFileDirPane = JScrollPane(self.dirList)

        ## Set left align
        listFileDirPane.setAlignmentX(Component.LEFT_ALIGNMENT)

        btnPanel = JPanel()
        btnGo = JButton("Compress & Go", actionPerformed = self.btnGoClick)
        btnSave = JButton("Save", actionPerformed = self.btnSaveClick)
        btnClear = JButton("Clear", actionPerformed = self.btnClearClick)
        btnReset = JButton("Reset", actionPerformed = self.btnResetRepeaterClick)
        btnPanel.add(btnGo)
        btnPanel.add(btnSave)
        btnPanel.add(btnReset)
        btnPanel.add(btnClear)
        btnPanel.setLayout(BoxLayout(btnPanel,BoxLayout.X_AXIS))

        panel1.add(label1)
        panel1.add(listFileDirPane)

        panel2.add(self.lblFilename)
        panel2.add(self.editField.getComponent())
        panel2.add(btnPanel)

        reqRestabPane.addTab("Response",self.responsePanel.getComponent())
        reqRestabPane.addTab("Request",self.requestPanel.getComponent())

        splitPane.setResizeWeight(0.6)

        #
        # Scanner tab
        #
        scanSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        tabPane.addTab("Scanner", scanSplitPane)
        scanSplitPane2 = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        scanSplitPane.setLeftComponent(scanSplitPane2)

        scanPanel1 = JPanel()
        scanPanel2 = JPanel()
        scanPanel3 = JPanel()
        scanSplitPane2.setLeftComponent(scanPanel1)
        scanSplitPane2.setRightComponent(scanPanel2)
        scanSplitPane.setRightComponent(scanPanel3)

        scanPanel1.setLayout(BoxLayout(scanPanel1,BoxLayout.Y_AXIS))
        scanPanel2.setLayout(BoxLayout(scanPanel2,BoxLayout.Y_AXIS))
        scanPanel3.setLayout(BoxLayout(scanPanel3,BoxLayout.Y_AXIS))

        scanLabel1 = JLabel("files and folders")
        self.scanLblFilename = JLabel("File name")
        scanLabel3 = JLabel("<html><h3>Config scanner</h3></html>")
        scanLabel4 = JLabel("<html><h3>Scanner status</h3></html>")
        scanLabel5 = JLabel("""<html>
                                <div>
                                    <h3>Notice</h3>
                                    <ul>
                                        <li>Possible to run only a scan at time</li>
                                        <li>Work with .zip file only</li>
                                        <li>Cannot continue after exit Burp</li>
                                    </ul>
                                </div>
                            </html>""")
        self.scannerStatusLabel = JLabel("<html><i style='color:grey'> Not Running</i></html>")
        self.checkboxScanFilename = JCheckBox("Also scan zip filename (this may be upload several files to server)")
        self.scanEditField = self._callbacks.createMessageEditor(None, False)
        self.scanDirList = JList([], valueChanged = self.scanListSelect)

        scanListFileDirPane = JScrollPane(self.scanDirList)

        ## Set left align
        scanListFileDirPane.setAlignmentX(Component.LEFT_ALIGNMENT)

        scanBtnPanel = JPanel()
        self.scanBtnGo = JButton("Set insertion point", actionPerformed = self.btnSetInsertionPointClick)
        self.scanBtnSave = JButton("Send to scanner", actionPerformed = self.btnScanClick)
        self.scanBtnClearInsertionPoint = JButton("Clear insertion points", actionPerformed = self.scanBtnClearInsClick)
        self.scanBtnClear = JButton("Clear", actionPerformed = self.scanBtnClearClick)
        self.scanBtnCancel = JButton("Cancel", actionPerformed = self.cancelScan)
        scanBtnPanel.add(self.scanBtnGo)
        scanBtnPanel.add(self.scanBtnSave)
        scanBtnPanel.add(self.scanBtnClearInsertionPoint)
        scanBtnPanel.add(self.scanBtnClear)
        scanBtnPanel.setLayout(BoxLayout(scanBtnPanel,BoxLayout.X_AXIS))

        scanPanel1.add(scanLabel1)
        scanPanel1.add(scanListFileDirPane)

        scanPanel2.add(self.scanLblFilename)
        scanPanel2.add(self.scanEditField.getComponent())
        scanPanel2.add(scanBtnPanel)
        
        scanPanel3.add(scanLabel3)
        scanPanel3.add(self.checkboxScanFilename)
        scanPanel3.add(scanLabel4)
        scanPanel3.add(self.scannerStatusLabel)
        scanPanel3.add(self.scanBtnCancel)
        self.scanBtnCancel.setEnabled(False)
        scanPanel3.add(scanLabel5)

        scanSplitPane.setResizeWeight(0.6)

        self.tab = tabPane

    # implement ITab
    def getTabCaption(self):
        return "ZIP File Raider"

    def getUiComponent(self):
        return self.tab
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel
                                            ):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exclude_File_Sources_CB.isSelected():
            self.local_settings.setExclude_File_Sources(True)
        else:
            self.local_settings.setExclude_File_Sources(False)

    # Check to see if there are any entries that need to be populated from the database.
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;'
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString(
                        "Setting_Name") == "Volatility_Executable_Directory":
                    self.Program_Executable_TF.setText(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Directory(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setVolatility_Dir_Found(True)
                if resultSet.getString("Setting_Name") == "Volatility_Version":
                    self.Version_CB.setSelectedItem(
                        resultSet.getString("Setting_Value"))
            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):

        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = ""
            if (self.local_settings.getVolatility_Dir_Found()):
                SQL_Statement = 'Update settings set Setting_Value = "' + self.Program_Executable_TF.getText() + '"' + \
                                ' where setting_name = "Volatility_Executable_Directory";'
                SQL_Statement2 = 'Update settings set Setting_Value = "' + self.Version_CB.getSelectedItem() + '"' + \
                                ' where setting_name = "Volatility_Version";'
            else:
                SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Executable_Directory", "' +  \
                                self.Program_Executable_TF.getText() + '");'
                SQL_Statement2 = 'Insert into settings (Setting_Name, Setting_Value) values ("Volatility_Version", "' +  \
                                self.Version_CB.getSelectedItem() + '");'

            stmt.execute(SQL_Statement)
            stmt.execute(SQL_Statement2)
            self.Error_Message.setText("Volatility Executable Directory Saved")
            self.local_settings.setVolatility_Directory(
                self.Program_Executable_TF.getText())
        except SQLException as e:
            self.Error_Message.setText(e.getMessage())
        stmt.close()
        dbConn.close()

    def get_plugins(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = "select plugin_name from plugins where volatility_version = '" + self.Version_CB.getSelectedItem() + "' and " + \
                             " plugin_name in ('dumpcerts', 'dumpfiles', 'dumpregistry', 'linux_librarydump', 'linux_procdump', 'mac_dump_file', 'mac_procdump', 'moddump', 'procdump', 'vaddump');"
            resultSet = stmt.executeQuery(SQL_Statement)
            plugin_list = []
            while resultSet.next():
                plugin_list.append(resultSet.getString("plugin_name"))

            stmt.close()
            dbConn.close()
            return plugin_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    def get_profiles(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = head + "\\GUI_Settings.db3"
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = "select profile_name from profiles where volatility_version = '" + self.Version_CB.getSelectedItem(
            ) + "';"
            resultSet = stmt.executeQuery(SQL_Statement)
            profile_list = []
            while resultSet.next():
                profile_list.append(resultSet.getString("profile_name"))

            stmt.close()
            dbConn.close()
            return profile_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    # When button to find file is clicked then open dialog to find the file and return it.
    def Find_Dir(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("All", ["*.*"])
        chooseFile.addChoosableFileFilter(filter)
        #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

        ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            Canonical_file = file.getCanonicalPath()
            #text = self.readPath(file)
            self.local_settings.setVolatility_Directory(Canonical_file)
            self.Program_Executable_TF.setText(Canonical_file)

    def keyPressed(self, event):
        self.local_settings.setProcessIDs(
            self.Process_Ids_To_Dump_TF.getText())
        #self.Error_Message.setText(self.Process_Ids_To_Dump_TF.getText())

    def onchange_version(self, event):
        self.local_settings.setVersion(event.item)
        plugin_list = self.get_plugins()
        profile_list = self.get_profiles()
        self.Profile_CB.removeAllItems()
        self.Plugin_LB.clearSelection()
        self.Plugin_LB.setListData(plugin_list)
        for profile in profile_list:
            self.Profile_CB.addItem(profile)
        #self.Profile_CB.addItems(profile)
        self.panel0.repaint()

    def onchange_plugins_lb(self, event):
        self.local_settings.clearPluginListBox()
        list_selected = self.Plugin_LB.getSelectedValuesList()
        self.local_settings.setPluginListBox(list_selected)

    def onchange_profile_cb(self, event):
        self.local_settings.setProfile(event.item)

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup()
        self.gbPanel0 = GridBagLayout()
        self.gbcPanel0 = GridBagConstraints()
        self.panel0.setLayout(self.gbPanel0)

        self.Error_Message = JLabel("")
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0)
        self.panel0.add(self.Error_Message)

        self.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0)
        self.panel0.add(self.Label_1)

        self.Program_Executable_TF = JTextField(10)
        self.Program_Executable_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Program_Executable_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Program_Executable_TF)

        self.Find_Program_Exec_BTN = JButton("Find Dir",
                                             actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Find_Program_Exec_BTN)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.Find_Program_Exec_BTN)

        self.Blank_1 = JLabel(" ")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0)
        self.panel0.add(self.Blank_1)

        self.Save_Settings_BTN = JButton("Save Volatility Exec Dir",
                                         actionPerformed=self.SaveSettings)
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Save_Settings_BTN)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0)
        self.panel0.add(self.Save_Settings_BTN)

        self.Blank_2 = JLabel(" ")
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0)
        self.panel0.add(self.Blank_2)

        self.Version_Label_1 = JLabel("Version:")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Version_Label_1, self.gbcPanel0)
        self.panel0.add(self.Version_Label_1)

        self.Version_List = ("2.5", "2.6")
        self.Version_CB = JComboBox(self.Version_List)
        self.Version_CB.itemStateChanged = self.onchange_version
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Version_CB, self.gbcPanel0)
        self.panel0.add(self.Version_CB)

        self.Blank_3 = JLabel(" ")
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_3, self.gbcPanel0)
        self.panel0.add(self.Blank_3)

        self.Plugin_Label_1 = JLabel("Plugins:")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Plugin_Label_1, self.gbcPanel0)
        self.panel0.add(self.Plugin_Label_1)

        self.Plugin_list = self.get_plugins()
        self.Plugin_LB = JList(self.Plugin_list,
                               valueChanged=self.onchange_plugins_lb)
        self.Plugin_LB.setVisibleRowCount(3)
        self.scpPlugin_LB = JScrollPane(self.Plugin_LB)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 1
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.scpPlugin_LB, self.gbcPanel0)
        self.panel0.add(self.scpPlugin_LB)

        self.Blank_4 = JLabel(" ")
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 17
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_4, self.gbcPanel0)
        self.panel0.add(self.Blank_4)

        self.Profile_Label_1 = JLabel("Profile:")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Profile_Label_1, self.gbcPanel0)
        self.panel0.add(self.Profile_Label_1)

        self.Profile_List = self.get_profiles()
        self.Profile_CB = JComboBox(self.Profile_List)
        self.Profile_CB.itemStateChanged = self.onchange_profile_cb
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 1
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Profile_CB, self.gbcPanel0)
        self.panel0.add(self.Profile_CB)

        self.Blank_5 = JLabel(" ")
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 21
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_5, self.gbcPanel0)
        self.panel0.add(self.Blank_5)

        self.Label_2 = JLabel("Process ids to dump (comma seperated list):")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 23
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_2, self.gbcPanel0)
        self.panel0.add(self.Label_2)

        self.Process_Ids_To_Dump_TF = JTextField(10, focusLost=self.keyPressed)
        #self.Process_Ids_To_Dump_TF.getDocument().addDocumentListener()
        self.Process_Ids_To_Dump_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 25
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Process_Ids_To_Dump_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Process_Ids_To_Dump_TF)

        self.Blank_6 = JLabel(" ")
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 27
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_6, self.gbcPanel0)
        self.panel0.add(self.Blank_6)

        self.Label_3 = JLabel("Message:")
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 29
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_3, self.gbcPanel0)
        self.panel0.add(self.Label_3)

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        #self.Exclude_File_Sources_CB.setSelected(self.local_settings.getExclude_File_Sources())
        #self.Run_Plaso_CB.setSelected(self.local_settings.getRun_Plaso())
        #self.Import_Plaso_CB.setSelected(self.local_settings.getImport_Plaso())
        self.check_Database_entries()
        #pass

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #27
0
class Pipeline():
    def __init__(self):
        #If a swing interface is asked for this will be the JFrame.
        self.frame = None
        #Keeps track of the number of queries processed.
        self.jobCount = 0
        #Keeps track of the query currently being processed.
        self.currentJob = ""
        #Keeps track of the massage to be displayed.
        self.message = 0
        #Messages to be displayed at each stage in the processing of a single query.
        self.messages = [
            "Searching for genes via genemark",
            "Extending genes found via genemark",
            "Searching for intergenic genes", "Removing overlapping genes",
            "Searching for promoters", "Using transterm to find terminators",
            "Removing transcription signals which conflict with genes",
            "Writing Artemis file", "Writing summary file"
        ]
        self.exception = None

    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)

    def updateProgress(self, job):
        """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is incremented.
    """
        if self.exception:
            raise self.exception

        if self.frame:
            if job != self.currentJob:
                self.currentProgress.setValue(
                    self.currentProgress.getMaximum())
                self.globalLabel.setText(job)
                self.globalProgress.setValue(self.jobCount)
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))
            self.currentProgress.setValue(self.message)
            self.currentLabel.setText(self.messages[self.message])
        else:
            if job != self.currentJob:
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))

    def finished(self):
        """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
        print "Processing 100.00% done"
        if self.frame:
            self.globalLabel.setText("Finished")
            self.globalProgress.setValue(self.globalProgress.getMaximum())
            self.currentLabel.setText(" ")
            self.currentProgress.setValue(self.currentProgress.getMaximum())
            self.doneButton.setEnabled(True)
            while self.frame.isVisible():
                pass

    def run(self,
            blastLocation,
            genemarkLocation,
            transtermLocation,
            database,
            eValue,
            matrix,
            minLength,
            scaffoldingDistance,
            ldfCutoff,
            queries,
            swing=False,
            email=""):
        """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    ldfCutoff:           Minimum LDF allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  The local machine will be used as
                         an SMTP server and this will not work if it isn't.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory
    of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes.
    """
        self.initializeDisplay(queries, swing)

        try:
            for query in queries:
                name = os.path.splitext(query)[0]
                queryDirectory, name = os.path.split(name)

                genome = utils.loadGenome(query)
                swapFileName = "query" + str(id(self)) + ".fas"
                queryFile = open(swapFileName, "w")
                queryFile.write(">" + name + "\n")
                for i in range(0, len(genome), 50):
                    queryFile.write(genome[i:min(i + 50, len(genome))] + "\n")
                queryFile.close()

                self.updateProgress(query)
                initialGenes = genemark.findGenes(swapFileName, name,
                                                  blastLocation, database,
                                                  eValue, genemarkLocation,
                                                  matrix, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values())

                self.updateProgress(query)
                extendedGenes = extend.extendGenes(swapFileName, initialGenes,
                                                   name, blastLocation,
                                                   database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values())

                self.updateProgress(query)
                intergenicGenes = intergenic.findIntergenics(
                    swapFileName, extendedGenes, name, minLength,
                    blastLocation, database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values())
                genes = {}
                for k, v in extendedGenes.items() + intergenicGenes.items():
                    genes[k] = v

                self.updateProgress(query)
                scaffolded = scaffolds.refineScaffolds(genes,
                                                       scaffoldingDistance)

                self.updateProgress(query)
                initialPromoters = promoters.findPromoters(swapFileName, name)

                self.updateProgress(query)
                initialTerminators = terminators.findTerminators(
                    swapFileName, name, genes.values(), transtermLocation)

                self.updateProgress(query)
                filteredSignals = signals.filterSignals(
                    scaffolded.values(), initialPromoters + initialTerminators)
                filteredPromoters = filter(
                    lambda x: isinstance(x, promoters.Promoter),
                    filteredSignals)
                filteredTerminators = filter(
                    lambda x: isinstance(x, terminators.Terminator),
                    filteredSignals)

                self.updateProgress(query)
                artemis.writeArtemisFile(
                    os.path.splitext(query)[0] + ".art", genome,
                    scaffolded.values(), filteredPromoters,
                    filteredTerminators)

                self.updateProgress(query)
                report.report(name, scaffolded, os.path.splitext(query)[0])

            if email:
                message = MIMEText("Your genome has been annotated.")
                message["Subject"] = "Annotation complete"
                message["From"] = "Neofelis"
                message["To"] = email

                smtp = smtplib.SMTP("tmpl.arizona.edu", 587)
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo
                smtp.sendmail("Neofelis", [email], message.as_string())
                smtp.close()

            self.finished()
        except PipelineException:
            return
class GUI_Test_SQLSettingsWithUISettingsPanel(
        IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exec_Program_CB.isSelected():
            self.local_settings.setSetting('Exec_Prog_Flag', 'true')
            self.Program_Executable_TF.setEnabled(True)
            self.Find_Program_Exec_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Exec_Prog_Flag', 'false')
            self.Program_Executable_TF.setText("")
            self.Program_Executable_TF.setEnabled(False)
            self.Find_Program_Exec_BTN.setEnabled(False)

    # Check to see if there are any entries that need to be populated from the database.
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;'
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString("Setting_Name") == "Program_Exec_Name":
                    self.Program_Executable_TF.setText(
                        resultSet.getString("Setting_Value"))
                    self.local_settings.setSetting(
                        'ExecFile', resultSet.getString("Setting_Value"))
                    self.local_settings.setSetting('Exec_Prog_Flag', 'true')
                    self.Exec_Program_CB.setSelected(True)
                    self.Program_Executable_TF.setEnabled(True)
                    self.Find_Program_Exec_BTN.setEnabled(True)
            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):

        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try:
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s" %
                                                 settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' +  \
                            self.Program_Executable_TF.getText() + '");'

            resultSet = stmt.executeQuery(SQL_Statement)
            self.Error_Message.setText("Settings Saved")
        except SQLException as e:
            self.Error_Message.setText("Error Inserting Settings " + str(e))
        stmt.close()
        dbConn.close()

    # When button to find file is clicked then open dialog to find the file and return it.
    def onClick(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("SQLite", ["sqlite"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.panel0, "Select SQLite")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            Canonical_file = file.getCanonicalPath()
            #text = self.readPath(file)
            self.local_settings.setSetting('ExecFile', Canonical_file)
            self.Program_Executable_TF.setText(Canonical_file)

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup()
        self.gbPanel0 = GridBagLayout()
        self.gbcPanel0 = GridBagConstraints()
        self.panel0.setLayout(self.gbPanel0)

        self.Exec_Program_CB = JCheckBox("Execute Program",
                                         actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 1
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Exec_Program_CB, self.gbcPanel0)
        self.panel0.add(self.Exec_Program_CB)

        self.Program_Executable_TF = JTextField(20)
        self.Program_Executable_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Program_Executable_TF,
                                     self.gbcPanel0)
        self.panel0.add(self.Program_Executable_TF)

        self.Find_Program_Exec_BTN = JButton("Find Exec",
                                             actionPerformed=self.onClick)
        self.Find_Program_Exec_BTN.setEnabled(False)
        self.rbgPanel0.add(self.Find_Program_Exec_BTN)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 3
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Find_Program_Exec_BTN,
                                     self.gbcPanel0)
        self.panel0.add(self.Find_Program_Exec_BTN)

        self.Blank_1 = JLabel(" ")
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_1, self.gbcPanel0)
        self.panel0.add(self.Blank_1)

        self.Save_Settings_BTN = JButton("Save Settings",
                                         actionPerformed=self.SaveSettings)
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add(self.Save_Settings_BTN)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Save_Settings_BTN, self.gbcPanel0)
        self.panel0.add(self.Save_Settings_BTN)

        self.Blank_2 = JLabel(" ")
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Blank_2, self.gbcPanel0)
        self.panel0.add(self.Blank_2)

        self.Label_1 = JLabel("Error Message:")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Label_1, self.gbcPanel0)
        self.panel0.add(self.Label_1)

        self.Error_Message = JLabel("")
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1
        self.gbcPanel0.gridheight = 1
        self.gbcPanel0.fill = GridBagConstraints.BOTH
        self.gbcPanel0.weightx = 1
        self.gbcPanel0.weighty = 0
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints(self.Error_Message, self.gbcPanel0)
        self.panel0.add(self.Error_Message)

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Exec_Program_CB.setSelected(
            self.local_settings.getSetting('Exec_Prog_Flag') == 'true')
        self.check_Database_entries()

    # Return the settings used
    def getSettings(self):
        return self.local_settings
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
           
    # When button to find file is clicked then open dialog to find the file and return it.       
    def Find_Dir(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("All", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)
       #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

       ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('Volatility_Directory', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)

    def keyPressed(self, event):
        self.local_settings.setProcessIDs(self.Process_Ids_To_Dump_TF.getText()) 
        #self.Error_Message.setText(self.Process_Ids_To_Dump_TF.getText())
        
    def checkBoxEvent(self, event):
        if self.Check_Box.isSelected():
            self.local_settings.setSetting('Flag', 'true')
        else:
            self.local_settings.setSetting('Flag', 'False')
        
    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

        self.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Program_Executable_TF = JTextField(10) 
        self.Program_Executable_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        self.Check_Box = JCheckBox("Extract and Create Memory Image from Hiberfile", actionPerformed=self.checkBoxEvent) 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Check_Box, self.gbcPanel0 ) 
        self.panel0.add( self.Check_Box ) 

        self.Blank_4 = JLabel( " ") 
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_4, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_4 ) 

        self.Label_3 = JLabel( "Message:") 
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 
		
        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Check_Box.setSelected(self.local_settings.getSetting('Flag') == 'true')
        self.Program_Executable_TF.setText(self.local_settings.getSetting('Volatility_Directory'))
        #pass
        
    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #30
0
resumeButton.setBounds(1400, 0, 150, 50)
layout.add(resumeButton)
box.pack()
box.setSize(1800, 100)
box.setLocation(0, 0)
box.visible = True

# ============================== DÉBUT DU PROGRAMME =========================================================
current_world = 0
POMO_skip = 0
next_run = .25
clearlog()
clearRemote()

while 1:
    resumeButton.setEnabled(True)
    status.setText(" ")
    while next_run > 0:
        countdown = min(60, 60 * next_run)
        while countdown > 0:
            if next_run > 1:
                msg.setBackground(JC.green)
                msg.setText("SCRIPT EN VEILLE - Prochaine execution dans " +
                            str(next_run) + " minutes.")
            else:
                msg.setBackground(JC.yellow)
                msg.setText("ATTENTION ! LE SCRIPT SE LANCERA DANS " +
                            str(countdown) + " SECONDES.")
            wait(1)
            countdown -= 1
            with open("D:\Dropbox\Fun\FOE\Macro\FOE_Robot.sikuli\ifttt.txt",
class GUI_Test_SQLSettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exec_Program_CB.isSelected():
            self.local_settings.setSetting('Exec_Prog_Flag', 'true')
            self.Program_Executable_TF.setEnabled(True)
            self.Find_Program_Exec_BTN.setEnabled(True)
        else:
            self.local_settings.setSetting('Exec_Prog_Flag', 'false')
            self.Program_Executable_TF.setText("")
            self.Program_Executable_TF.setEnabled(False)
            self.Find_Program_Exec_BTN.setEnabled(False)

    # Check to see if there are any entries that need to be populated from the database.        
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' 
           resultSet = stmt.executeQuery(SQL_Statement)
           while resultSet.next():
               if resultSet.getString("Setting_Name") == "Program_Exec_Name":
                   self.Program_Executable_TF.setText(resultSet.getString("Setting_Value"))
                   self.local_settings.setSetting('ExecFile', resultSet.getString("Setting_Value"))
                   self.local_settings.setSetting('Exec_Prog_Flag', 'true')
                   self.Exec_Program_CB.setSelected(True)
                   self.Program_Executable_TF.setEnabled(True)
                   self.Find_Program_Exec_BTN.setEnabled(True)
           self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = 'Insert into settings (Setting_Name, Setting_Value) values ("Program_Exec_Name", "' +  \
                           self.Program_Executable_TF.getText() + '");' 
           
           resultSet = stmt.executeQuery(SQL_Statement)
           self.Error_Message.setText("Settings Saved")
        except SQLException as e:
           self.Error_Message.setText("Error Inserting Settings " + str(e))
        stmt.close()
        dbConn.close()
           
    # When button to find file is clicked then open dialog to find the file and return it.       
    def onClick(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("SQLite", ["sqlite"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Select SQLite")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('ExecFile', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Exec_Program_CB = JCheckBox("Execute Program", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Exec_Program_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Exec_Program_CB ) 

        self.Program_Executable_TF = JTextField(20) 
        self.Program_Executable_TF.setEnabled(False)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Exec", actionPerformed=self.onClick)
        self.Find_Program_Exec_BTN.setEnabled(False)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Save_Settings_BTN = JButton( "Save Settings", actionPerformed=self.SaveSettings) 
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Save_Settings_BTN ) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 7
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Save_Settings_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Save_Settings_BTN ) 

        self.Blank_2 = JLabel( " ") 
        self.Blank_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 9
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_2, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_2 ) 

        self.Label_1 = JLabel( "Error Message:") 
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 
		
        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Exec_Program_CB.setSelected(self.local_settings.getSetting('Exec_Prog_Flag') == 'true')
        self.check_Database_entries()

    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #32
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
Beispiel #33
0
class BurpExtender(IBurpExtender, ITab):
    def registerExtenderCallbacks(self, callbacks):
        print "Loading..."

        self._callbacks = callbacks
        self._callbacks.setExtensionName('Burp SSL Scanner')
        # self._callbacks.registerScannerCheck(self)
        # self._callbacks.registerExtensionStateListener(self)
        self._helpers = callbacks.getHelpers()

        # initialize the main scanning event and thread
        self.scanningEvent = Event()
        self.scannerThread = None
        self.targetURL = None

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setBorder(EmptyBorder(20, 20, 20, 20))
        
        # sub split pane (top)
        self._topPanel = JPanel(BorderLayout(10, 10))
        self._topPanel.setBorder(EmptyBorder(0, 0, 10, 0))

        # Setup Panel :    [Target: ] [______________________] [START BUTTON]
        self.setupPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.setupPanel.add(
            JLabel("Target:", SwingConstants.LEFT), BorderLayout.LINE_START)

        self.hostField = JTextField('', 50)
        self.setupPanel.add(self.hostField)

        self.toggleButton = JButton(
            'Start scanning', actionPerformed=self.startScan)
        self.setupPanel.add(self.toggleButton)

        if 'Professional' in callbacks.getBurpVersion()[0] :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap', True)
        else :
            self.addToSitemapCheckbox = JCheckBox('Add to sitemap (requires Professional version)', False)
            self.addToSitemapCheckbox.setEnabled(False)
        self.setupPanel.add(self.addToSitemapCheckbox)

        self.scanSiteMapHostCheckbox = JCheckBox('Scan sitemap hosts', True)
        self.setupPanel.add(self.scanSiteMapHostCheckbox)

        self._topPanel.add(self.setupPanel, BorderLayout.PAGE_START)
        
        # Status bar
        self.scanStatusPanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))

        self.scanStatusPanel.add(JLabel("Status: ", SwingConstants.LEFT))

        self.scanStatusLabel = JLabel("Ready to scan", SwingConstants.LEFT)
        self.scanStatusPanel.add(self.scanStatusLabel)

        self._topPanel.add(self.scanStatusPanel, BorderLayout.LINE_START)

        self._splitpane.setTopComponent(self._topPanel)

        # bottom panel 
        self._bottomPanel = JPanel(BorderLayout(10, 10))
        self._bottomPanel.setBorder(EmptyBorder(10, 0, 0, 0))

        self.initialText = ('<h1 style="color: red;">Burp SSL Scanner<br />'
                            'Please note that TLS1.3 is still not supported by this extension.</h1>')
        self.currentText = self.initialText

        self.textPane = JTextPane()
        self.textScrollPane = JScrollPane(self.textPane)
        self.textPane.setContentType("text/html")
        self.textPane.setText(self.currentText)
        self.textPane.setEditable(False)

        self._bottomPanel.add(self.textScrollPane, BorderLayout.CENTER)

        self.savePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))
        self.saveButton = JButton('Save to file', actionPerformed=self.saveToFile)
        self.saveButton.setEnabled(False)
        self.savePanel.add(self.saveButton)

        self.clearScannedHostButton = JButton('Clear scanned host', actionPerformed=self.clearScannedHost)
        self.savePanel.add(self.clearScannedHostButton)
        self.savePanel.add(JLabel("Clear hosts that were scanned by active scan to enable rescanning", SwingConstants.LEFT))

        self._bottomPanel.add(self.savePanel, BorderLayout.PAGE_END)

        self._splitpane.setBottomComponent(self._bottomPanel)

        callbacks.customizeUiComponent(self._splitpane)

        callbacks.addSuiteTab(self)
        
        print "SSL Scanner tab loaded"


        self.scannerMenu = ScannerMenu(self)
        callbacks.registerContextMenuFactory(self.scannerMenu)
        print "SSL Scanner custom menu loaded"


        self.scannerCheck = ScannerCheck(self, self.scanSiteMapHostCheckbox.isSelected)
        callbacks.registerScannerCheck(self.scannerCheck)
        print "SSL Scanner check registered"

        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
        scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']

        print(scanAccuracy, scanSpeed)

        self.scannedHost = []

        print 'SSL Scanner loaded'
        
    def startScan(self, ev) :

        host = self.hostField.text
        self.scanningEvent.set()
        if(len(host) == 0):
            return
        if host.find("://") == -1:
            host = "https://" + host 
        try:
            self.targetURL = URL(host)
            if(self.targetURL.getPort() == -1):
                self.targetURL = URL("https", self.targetURL.getHost(), 443, "/")
            self.hostField.setEnabled(False)
            self.toggleButton.setEnabled(False)
            self.saveButton.setEnabled(False)
            self.addToSitemapCheckbox.setEnabled(False)
            self.currentText = self.initialText
            self.textPane.setText(self.currentText)
            self.updateText("<h2>Scanning %s:%d</h2>" % (self.targetURL.getHost(), self.targetURL.getPort()))
            print("Scanning %s:%d" % (self.targetURL.getHost(), self.targetURL.getPort()))
            self.scannerThread = Thread(target=self.scan, args=(self.targetURL, ))
            self.scannerThread.start()
        except BaseException as e:
            self.saveButton.setEnabled(False)
            print(e)
            return

    def scan(self, url, usingBurpScanner=False):

        def setScanStatusLabel(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.scanStatusLabel.setText, 
                                    (text,)))
                                
        def updateResultText(text) :
            if not usingBurpScanner :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.updateText, (text, )))

        if usingBurpScanner :
            res = result.Result(url, self._callbacks, self._helpers, False)
        else :
            res = result.Result(url, self._callbacks, self._helpers, self.addToSitemapCheckbox.isSelected())

        host, port = url.getHost(), url.getPort()

        ### Get project configuration
        projectConfig = json.loads(self._callbacks.saveConfigAsJson())
        if 'scanner' in projectConfig:
            # scanAccuracy: minimise_false_negatives, normal, minimise_false_positives
            scanAccuracy = projectConfig['scanner']['active_scanning_optimization']['scan_accuracy']
            # scanSpeed: fast, normal, thorough
            scanSpeed = projectConfig['scanner']['active_scanning_optimization']['scan_speed']
        else:
            scanAccuracy = 'normal'
            scanSpeed = 'normal'

        updateResultText('<h2>Scanning speed: %s</h2> %s' % (scanSpeed, test_details.SCANNING_SPEED_INFO[scanSpeed]))
        updateResultText('<h2>Scanning accuracy: %s</h2> %s' % (scanAccuracy, test_details.SCANNING_ACCURACY_INFO[scanAccuracy]))

        try :
            setScanStatusLabel("Checking for supported SSL/TLS versions")
            con = connection_test.ConnectionTest(res, host, port, scanSpeed, scanAccuracy)
            con.start()
            conResultText = '<hr /><br /><h3>' + res.printResult('connectable') + '</h3>' + \
                '<ul><li>' + res.printResult('offer_ssl2') + '</li>' + \
                '<li>' + res.printResult('offer_ssl3') + '</li>' + \
                '<li>' + res.printResult('offer_tls10') + '</li>' + \
                '<li>' + res.printResult('offer_tls11') + '</li>' + \
                '<li>' + res.printResult('offer_tls12') + '</li></ul>'
            updateResultText(conResultText)

            
            if not res.getResult('connectable') :
                updateResultText("<h2>Scan terminated (Connection failed)</h2>")
                raise BaseException('Connection failed')

            setScanStatusLabel("Checking for supported cipher suites (This can take a long time)")
            supportedCipher = supportedCipher_test.SupportedCipherTest(res, host, port, scanSpeed, scanAccuracy)
            supportedCipher.start()

            
            setScanStatusLabel("Checking for Cipherlist")
            cipher = cipher_test.CipherTest(res, host, port, scanSpeed, scanAccuracy)
            cipher.start()
            cipherResultText = '<h3>Available ciphers:</h3>' + \
                '<ul><li>' + res.printResult('cipher_NULL') + '</li>' + \
                '<li>' + res.printResult('cipher_ANON') + '</li>' + \
                '<li>' + res.printResult('cipher_EXP') + '</li>' + \
                '<li>' + res.printResult('cipher_LOW') + '</li>' + \
                '<li>' + res.printResult('cipher_WEAK') + '</li>' + \
                '<li>' + res.printResult('cipher_3DES') + '</li>' + \
                '<li>' + res.printResult('cipher_HIGH') + '</li>' + \
                '<li>' + res.printResult('cipher_STRONG') + '</li></ul>' 
            updateResultText(cipherResultText)
            

            setScanStatusLabel("Checking for Heartbleed")
            heartbleed = heartbleed_test.HeartbleedTest(res, host, port, scanSpeed, scanAccuracy)
            heartbleed.start()
            heartbleedResultText = res.printResult('heartbleed')
            updateResultText(heartbleedResultText)
            

            setScanStatusLabel("Checking for CCS Injection")
            ccs = ccs_test.CCSTest(res, host, port, scanSpeed, scanAccuracy)
            ccs.start()
            ccsResultText = res.printResult('ccs_injection')
            updateResultText(ccsResultText)

            
            setScanStatusLabel("Checking for TLS_FALLBACK_SCSV")
            fallback = fallback_test.FallbackTest(res, host, port, scanSpeed, scanAccuracy)
            fallback.start()
            fallbackResultText = res.printResult('fallback_support')
            updateResultText(fallbackResultText)


            setScanStatusLabel("Checking for POODLE (SSLv3)")
            poodle = poodle_test.PoodleTest(res, host, port, scanSpeed, scanAccuracy)
            poodle.start()
            poodleResultText = res.printResult('poodle_ssl3')
            updateResultText(poodleResultText)
            

            setScanStatusLabel("Checking for SWEET32")
            sweet32 = sweet32_test.Sweet32Test(res, host, port, scanSpeed, scanAccuracy)
            sweet32.start()
            sweet32ResultText = res.printResult('sweet32')
            updateResultText(sweet32ResultText)
            

            setScanStatusLabel("Checking for DROWN")
            drown = drown_test.DrownTest(res, host, port, scanSpeed, scanAccuracy)
            drown.start()
            drownResultText = res.printResult('drown')
            updateResultText(drownResultText)
            

            setScanStatusLabel("Checking for FREAK")
            freak = freak_test.FreakTest(res, host, port, scanSpeed, scanAccuracy)
            freak.start()
            freakResultText = res.printResult('freak')
            updateResultText(freakResultText)
            

            setScanStatusLabel("Checking for LUCKY13")
            lucky13 = lucky13_test.Lucky13Test(res, host, port, scanSpeed, scanAccuracy)
            lucky13.start()
            lucky13ResultText = res.printResult('lucky13')
            updateResultText(lucky13ResultText)
            

            setScanStatusLabel("Checking for CRIME")
            crime = crime_test.CrimeTest(res, host, port, scanSpeed, scanAccuracy)
            crime.start()
            crimeResultText = res.printResult('crime_tls')
            updateResultText(crimeResultText)
            

            setScanStatusLabel("Checking for BREACH")
            breach = breach_test.BreachTest(res, host, port, scanSpeed, scanAccuracy)
            breach.start(self._callbacks, self._helpers)
            breachResultText = res.printResult('breach')
            updateResultText(breachResultText)


            setScanStatusLabel("Checking for BEAST")
            beast = beast_test.BeastTest(res, host, port, scanSpeed, scanAccuracy)
            beast.start()
            beastResultText = res.printResult('beast')
            updateResultText(beastResultText)


            setScanStatusLabel("Checking for LOGJAM")
            logjam = logjam_test.LogjamTest(res, host, port, scanSpeed, scanAccuracy)
            logjam.start()
            logjamResultText = res.printResult('logjam_export') + '<br />' + res.printResult('logjam_common') 
            updateResultText(logjamResultText)
            

            updateResultText('<h2>Finished scanning</h2><br /><hr /><br /><h2>Summary</h2>')

            updateResultText('<h2>Supported ciphers (by Protocol)</h2>')
            updateResultText(res.printCipherList())
            updateResultText('<h2>Supported ciphers (by Vulnerability)</h2>')
            updateResultText(res.printCipherListByVulns())

            updateResultText('<h2>Issues found</h2>')
            updateResultText(res.printAllIssue())

        except BaseException as e :
            print(e)
            setScanStatusLabel("An error occurred. Please refer to the output/errors tab for more information.")
            time.sleep(2)

        if usingBurpScanner :
            return res.getAllIssue()
        else :
            self.scanningEvent.clear()
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.toggleButton.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.hostField.setEnabled, (True, ))
            )
            SwingUtilities.invokeLater(
                    ScannerRunnable(self.saveButton.setEnabled, (True, ))
            )
            if 'Professional' in self._callbacks.getBurpVersion()[0] :
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.addToSitemapCheckbox.setEnabled, (True, ))
                )
            setScanStatusLabel("Ready to scan")
        print("Finished scanning")

    def updateText(self, stringToAppend):
        self.currentText += ('<br />' + stringToAppend)
        self.textPane.setText(self.currentText)

    def saveToFile(self, event):
        fileChooser = JFileChooser()
        if not (self.targetURL is None):
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result_%s.html" \
                % (self.targetURL.getHost())))
        else:
            fileChooser.setSelectedFile(File("Burp_SSL_Scanner_Result.html"))
        if (fileChooser.showSaveDialog(self.getUiComponent()) == JFileChooser.APPROVE_OPTION):
            fw = FileWriter(fileChooser.getSelectedFile())
            fw.write(self.textPane.getText())
            fw.flush()
            fw.close()
            print "Saved results to disk"

    def clearScannedHost(self, event) :
        self.scannedHost = []

    def addHostToScannedList(self, host, port) :
        self.scannedHost.append([host, port])

    def getTabCaption(self):
        return "SSL Scanner"

    def getUiComponent(self):
        return self._splitpane
Beispiel #34
0
# Function for the button to enable editing the note for the selected table row
def clickEditButton(event):
    edit_note.setEnabled(False)
    save_note.setEnabled(True)
    note_status.setText("Editing...")
    textarea.setEditable(True)
    textarea.requestFocus()


# 2nd-to-last Bottom right button for editing the note text in the middle-right text area
c.gridx = 2
c.gridy = 2
c.weightx = 0.0
c.anchor = GridBagConstraints.NORTHEAST
edit_note = JButton("Edit note", actionPerformed=clickEditButton)
edit_note.setEnabled(False)
gb.setConstraints(edit_note, c)
all.add(edit_note)


# Function for the bottom right button to request saving the text note to the CSV file
def requestSave(event):
    # Update table model data
    rowIndex = getSelectedRowIndex()
    table_entries[rowIndex][-1] = textarea.getText()
    # Signal synchronize to disk next time the scheduled thread wakes up
    requested_save_csv.set(True)


# Bottom right button for requesting that the text note in the text area be saved to the CSV file
c.gridx = 3
Beispiel #35
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                "tools",
                                                                "data",
                                                                "Favourites",
                                                                "icons",
                                                                "tool_16.png"])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                   "tools",
                                                                   "data",
                                                                   "Favourites",
                                                                   "icons",
                                                                   "black_tool_16.png"])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                 "images",
                                                                 "icons",
                                                                 "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(ChecksTableClickListener(app,
            self.checkPopup,
            self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(errorInfoBtnIcon,
                                    actionPerformed=app.on_errorInfoBtn_clicked,
                                    enabled=0)
        notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(notErrorIcon,
                                   actionPerformed=app.on_falsePositiveBtn_clicked,
                                   enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(correctedIcon,
                                    actionPerformed=app.on_correctedBtn_clicked,
                                    enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"),
                               None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = ["",
                   self.app.strings.getString("Check"),
                   self.app.strings.getString("Errors")]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {"white": (255, 255, 255),
                  "black": (0, 0, 0),
                  "green": (100, 200, 0),
                  "red": (200, 0, 0)}
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"),
                                       None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                         self.app.strings.getString("to_do"),
                         self.app.selectedChecks[0].toDo,
                         len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                        errorInfo,
                        self.app.strings.getString("to_do"),
                        self.app.selectedChecks[0].toDo,
                        len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)
Beispiel #36
0
class AmcacheScanWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Private_API_Key_CB.isSelected():
            self.local_settings.setPrivate(True)
            self.local_settings.setAPI_Key(self.API_Key_TF.getText())
        else:
            self.local_settings.setPrivate(False)
            self.local_settings.setAPI_Key(self.API_Key_TF.getText())

    # Check to see if there are any entries that need to be populated from the database.        
    def check_Database_entries(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'Select Setting_Name, Setting_Value from settings;' 
            resultSet = stmt.executeQuery(SQL_Statement)
            while resultSet.next():
                if resultSet.getString("Setting_Name") == "API_Key":
                    self.local_settings.setAPI_Key(resultSet.getString("Setting_Value"))
                    self.API_Key_TF.setText(resultSet.getString("Setting_Value"))
                if resultSet.getString("Setting_Name") == "Private":
                    private = resultSet.getString("Setting_Value")
                    if private == "1":
                        self.local_settings.setPrivate(True)
                    else:
                        self.local_settings.setPrivate(False)

            self.Error_Message.setText("Settings Read successfully!")
        except SQLException as e:
            self.Error_Message.setText("Error Reading Settings Database")

        stmt.close()
        dbConn.close()

    # Save entries from the GUI to the database.
    def SaveSettings(self, e):
        
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = head + "\\GUI_Settings.db3"
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings")

        try:
            stmt = dbConn.createStatement()
            SQL_Statement = 'UPDATE settings SET Setting_Value = "' + self.API_Key_TF.getText() + '" WHERE Setting_Name = "API_Key";'
            resultSet = stmt.executeQuery(SQL_Statement)
        except:
            pass
        try:
            if self.local_settings.getPrivate():
                SQL_Statement = 'UPDATE settings SET Setting_Value = "1" WHERE Setting_Name = "Private";' 
                resultSet = stmt.executeQuery(SQL_Statement)
            else:
                SQL_Statement = 'UPDATE settings SET Setting_Value = "0" WHERE Setting_Name = "Private";'  
                resultSet = stmt.executeQuery(SQL_Statement)
        except:
            pass

        self.Error_Message.setText("Settings Saved")
        stmt.close()
        dbConn.close()


    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.LabelA = JLabel("VirusTotal API Key:")
        self.LabelA.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.LabelA, self.gbcPanel0 ) 
        self.panel0.add( self.LabelA ) 

        self.API_Key_TF = JTextField(20) 
        self.API_Key_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.API_Key_TF, self.gbcPanel0 ) 
        self.panel0.add( self.API_Key_TF ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 6
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Private_API_Key_CB = JCheckBox("Private API Key?", actionPerformed=self.checkBoxEvent)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Private_API_Key_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Private_API_Key_CB )

        self.Save_Settings_BTN = JButton( "Save Settings", actionPerformed=self.SaveSettings) 
        self.Save_Settings_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Save_Settings_BTN ) 
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 8
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Save_Settings_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Save_Settings_BTN ) 

        self.Label_1 = JLabel( "Error Message:") 
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 6
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.check_Database_entries()
        self.Private_API_Key_CB.setSelected(self.local_settings.getPrivate())

    # Return the settings used
    def getSettings(self):
        return self.local_settings
class PyNewsGUI:
    def __init__(self):
        self.guiFrame()

    articles = []

    def pyNewsSearch(self, event):
        self.articles = pn.googleNews(self.input_field.getText())
        print("got through search")
        #self.exp_button.setEnabled(True)
        #self.opn_button.setEnabled(True)
        #self.wrt_button.setEnabled(True)
        time.sleep(2000)

    def expandNews(self):
        pass

    def openNews(self):
        pass

    def openHTML(self):
        pass

    def writeToCSV(self):
        #if .isSelected():
        pass

    def guiFrame(self):

        frame = JFrame("PyNews")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setLocationRelativeTo(None)
        frame.setSize(600, 200)
        frame.setResizable(False)

        frame.setLayout(GridLayout(5, 3, 10, 10))

        # logo
        self.logo = JLabel("  PyNews")

        # query input
        self.input_field = JTextField(30)

        # search button
        self.src_button = JButton("Search!", actionPerformed=self.pyNewsSearch)

        # expand button
        self.exp_button = JButton("Expand!", actionPerformed=self.expandNews)
        self.exp_button.setEnabled(False)

        # open button
        self.opn_button = JButton("Open!", actionPerformed=self.openNews)
        self.opn_button.setEnabled(False)

        # open html button
        self.htm_button = JButton("HTML-Open!", actionPerformed=self.openHTML)
        self.htm_button.setEnabled(False)

        # write to file button
        self.wrt_button = JButton("CSV-Write!",
                                  actionPerformed=self.writeToCSV)
        self.wrt_button.setEnabled(False)

        # checkboxes
        self.categories = [
            "authors", "publish_date", "top_image", "movies", "text",
            "article_html", "summary", "keywords"
        ]
        self.checkboxes = []

        for cat in self.categories:
            self.checkboxes.append(JCheckBox(cat))

        # add to frame

        frame.add(self.logo)
        frame.add(self.input_field)
        frame.add(self.src_button)
        frame.add(self.exp_button)
        for cb in self.checkboxes[:2]:
            frame.add(cb)
        frame.add(self.opn_button)
        for cb in self.checkboxes[2:4]:
            frame.add(cb)
        frame.add(self.htm_button)
        for cb in self.checkboxes[4:6]:
            frame.add(cb)
        frame.add(self.wrt_button)
        for cb in self.checkboxes[6:8]:
            frame.add(cb)
        print("got to end ")
        frame.setVisible(True)
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
Beispiel #39
0
class VolatilitySettingsWithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'
    
    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    
    _logger = Logger.getLogger(VolatilityIngestModuleFactory.moduleName)

    def log(self, level, msg):
        self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg)

    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()
    
    # Check the checkboxs to see what actions need to be taken
    def checkBoxEvent(self, event):
        if self.Exclude_File_Sources_CB.isSelected():
            self.local_settings.setSetting('Exclude_File_Sources', 'true')
        else:
            self.local_settings.setSetting('Exclude_File_Sources', 'false')

    def get_plugins(self):
        head, tail = os.path.split(os.path.abspath(__file__))
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = "select plugin_name from plugins where volatility_version = '" + self.Version_CB.getSelectedItem() + "';" 
           resultSet = stmt.executeQuery(SQL_Statement)
           plugin_list = []
           while resultSet.next():
              plugin_list.append(resultSet.getString("plugin_name"))

           stmt.close()
           dbConn.close()
           return plugin_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    def get_profiles(self):
        head, tail = os.path.split(os.path.abspath(__file__)) 
        settings_db = os.path.join(head, "GUI_Settings.db3")
        try: 
            Class.forName("org.sqlite.JDBC").newInstance()
            dbConn = DriverManager.getConnection("jdbc:sqlite:%s"  % settings_db)
            self.Error_Message.setText("Database opened")
        except SQLException as e:
            self.Error_Message.setText("Error Opening Settings DB!")
 
        try:
           stmt = dbConn.createStatement()
           SQL_Statement = "select profile_name from profiles where volatility_version = '" + self.Version_CB.getSelectedItem() + "';" 
           resultSet = stmt.executeQuery(SQL_Statement)
           profile_list = []
           while resultSet.next():
              profile_list.append(resultSet.getString("profile_name"))

           stmt.close()
           dbConn.close()
           return profile_list
        except SQLException as e:
            self.Error_Message.setText("Error Reading plugins")
            stmt.close()
            dbConn.close()
            return "Error"

    # When button to find file is clicked then open dialog to find the file and return it.       
    def Find_Dir(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("All", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)
       #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

       ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('Volatility_Directory', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)

    def keyPressed(self, event):
        self.local_settings.setSetting('AdditionalParms', self.Additional_Parms_TF.getText()) 
        #self.Error_Message.setText(self.Additional_Parms_TF.getText())
        
    def onchange_version(self, event):
        self.local_settings.setSetting('Version', event.item)        
        plugin_list = self.get_plugins()
        profile_list = self.get_profiles()
        self.Profile_CB.removeAllItems()
        self.Plugin_LB.clearSelection()
        self.Plugin_LB.setListData(plugin_list)
        for profile in profile_list:
            self.Profile_CB.addItem(profile)
        #self.Profile_CB.addItems(profile)
        self.panel0.repaint()
        
    def onchange_plugins_lb(self, event):
        self.local_settings.setSetting('PluginListBox' , '')
        list_selected = self.Plugin_LB.getSelectedValuesList()
        self.local_settings.setSetting('PluginListBox', str(list_selected))      
 
    def onchange_profile_cb(self, event):
        self.local_settings.setSetting('Profile', event.item) 

    # Create the initial data fields/layout in the UI
    def initComponents(self):
        self.panel0 = JPanel()

        self.rbgPanel0 = ButtonGroup() 
        self.gbPanel0 = GridBagLayout() 
        self.gbcPanel0 = GridBagConstraints() 
        self.panel0.setLayout( self.gbPanel0 ) 

        self.Error_Message = JLabel( "") 
        self.Error_Message.setEnabled(True)
        self.gbcPanel0.gridx = 2
        self.gbcPanel0.gridy = 31
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH
        self.gbPanel0.setConstraints( self.Error_Message, self.gbcPanel0 ) 
        self.panel0.add( self.Error_Message ) 

        self.Label_1 = JLabel("Volatility Executable Directory")
        self.Label_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 1 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Label_1 ) 

        self.Program_Executable_TF = JTextField(10) 
        self.Program_Executable_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Program_Executable_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Program_Executable_TF ) 

        self.Find_Program_Exec_BTN = JButton( "Find Dir", actionPerformed=self.Find_Dir)
        self.Find_Program_Exec_BTN.setEnabled(True)
        self.rbgPanel0.add( self.Find_Program_Exec_BTN ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 3 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Find_Program_Exec_BTN, self.gbcPanel0 ) 
        self.panel0.add( self.Find_Program_Exec_BTN ) 

        self.Blank_1 = JLabel( " ") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 5
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_1, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_1 ) 

        self.Version_Label_1 = JLabel( "Version:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 11
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Version_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Version_Label_1 ) 
        
        self.Version_List = ("2.5", "2.6") 
        self.Version_CB = JComboBox( self.Version_List)
        self.Version_CB.itemStateChanged = self.onchange_version        
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 11 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Version_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Version_CB ) 

        self.Blank_3 = JLabel( " ") 
        self.Blank_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 13
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_3, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_3 ) 

        self.Plugin_Label_1 = JLabel( "Plugins:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 15
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Plugin_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Plugin_Label_1 ) 
        
        self.Plugin_list = self.get_plugins()
        self.Plugin_LB = JList( self.Plugin_list, valueChanged=self.onchange_plugins_lb)
        self.Plugin_LB.setVisibleRowCount( 3 ) 
        self.scpPlugin_LB = JScrollPane( self.Plugin_LB ) 
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 15 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.scpPlugin_LB, self.gbcPanel0 ) 
        self.panel0.add( self.scpPlugin_LB ) 

        self.Blank_4 = JLabel( " ") 
        self.Blank_4.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 17
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_4, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_4 ) 

        self.Profile_Label_1 = JLabel( "Profile:") 
        self.Blank_1.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 19
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Profile_Label_1, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_Label_1 ) 
        
        self.Profile_List = self.get_profiles()
        self.Profile_CB = JComboBox( self.Profile_List)
        self.Profile_CB.itemStateChanged = self.onchange_profile_cb        
        self.gbcPanel0.gridx = 6 
        self.gbcPanel0.gridy = 19 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 1 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Profile_CB, self.gbcPanel0 ) 
        self.panel0.add( self.Profile_CB ) 

        self.Blank_5 = JLabel( " ") 
        self.Blank_5.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 21
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_5, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_5 ) 

        self.Label_2 = JLabel("Additional Parameters To Run With:")
        self.Label_2.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 23 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_2, self.gbcPanel0 ) 
        self.panel0.add( self.Label_2 ) 

        self.Additional_Parms_TF = JTextField(10,focusLost=self.keyPressed) 
        #self.Additional_Parms_TF.getDocument().addDocumentListener()
        self.Additional_Parms_TF.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 25 
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Additional_Parms_TF, self.gbcPanel0 ) 
        self.panel0.add( self.Additional_Parms_TF ) 

        self.Blank_6 = JLabel( " ") 
        self.Blank_6.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 27
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Blank_6, self.gbcPanel0 ) 
        self.panel0.add( self.Blank_6 ) 

        self.Label_3 = JLabel( "Message:") 
        self.Label_3.setEnabled(True)
        self.gbcPanel0.gridx = 2 
        self.gbcPanel0.gridy = 29
        self.gbcPanel0.gridwidth = 1 
        self.gbcPanel0.gridheight = 1 
        self.gbcPanel0.fill = GridBagConstraints.BOTH 
        self.gbcPanel0.weightx = 1 
        self.gbcPanel0.weighty = 0 
        self.gbcPanel0.anchor = GridBagConstraints.NORTH 
        self.gbPanel0.setConstraints( self.Label_3, self.gbcPanel0 ) 
        self.panel0.add( self.Label_3 ) 
		
        self.add(self.panel0)

    # Custom load any data field and initialize the values
    def customizeComponents(self):
        self.Program_Executable_TF.setText(self.local_settings.getSetting('Volatility_Directory'))
        #pass
        
    # Return the settings used
    def getSettings(self):
        return self.local_settings
Beispiel #40
0
class AccountManagementGUI:
    def __init__(self):
        self.acctmanager = AccountManager()
        self.mainframe = JFrame("Account Manager")
        self.chatui = None
        self.headers = ["Account Name", "Status", "Autologin", "Gateway"]
        self.data = UneditableTableModel([], self.headers)
        self.table = JTable(self.data)
        self.table.columnSelectionAllowed = 0  #cannot select columns
        self.table.selectionMode = ListSelectionModel.SINGLE_SELECTION

        self.connectbutton = JButton("Connect", actionPerformed=self.connect)
        self.dconnbutton = JButton("Disconnect",
                                   actionPerformed=self.disconnect)
        self.deletebutton = JButton("Delete",
                                    actionPerformed=self.deleteAccount)
        self.buildpane()
        self.mainframe.pack()
        self.mainframe.show()

    def buildpane(self):
        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(self.connectbutton)
        buttons.add(self.dconnbutton)
        buttons.add(JButton("New", actionPerformed=self.addNewAccount))
        buttons.add(self.deletebutton)
        buttons.add(JButton("Quit", actionPerformed=self.quit))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(JScrollPane(self.table))
        mainpane.add(buttons)
        self.update()

    def update(self):
        self.data.setDataVector(self.acctmanager.getSnapShot(), self.headers)
        if self.acctmanager.isEmpty():
            self.deletebutton.setEnabled(0)
            self.connectbutton.setEnabled(0)
            self.dconnbutton.setEnabled(0)
        else:
            self.deletebutton.setEnabled(1)
            if not 1 in self.acctmanager.getConnectionInfo(
            ):  #all disconnected
                self.dconnbutton.setEnabled(0)
                self.connectbutton.setEnabled(1)
            elif not 0 in self.acctmanager.getConnectionInfo():  #all connected
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(0)
            else:
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(1)

    #callable button actions
    def connect(self, ae):
        print "Trying to connect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to connect to an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            if not self.chatui:
                self.chatui = twisted.words.im.jychat.JyChatUI()
            self.acctmanager.connect(acctname, self.chatui)
            self.update()

    def disconnect(self, ae):
        print "Trying to disconnect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to logoff an account but no account was selected."
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.disconnect(acctname)
            self.update()

    def addNewAccount(self, ae):
        print "Starting new account creation"
        NewAccountGUI(self).show()

    def deleteAccount(self, ae):
        print "Deleting account"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to delete an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.delAccount(acctname)
            self.update()

    def quit(self, ae):
        self.acctmanager.quit()
        sys.exit()
Beispiel #41
0
    class PositionsController(IMessageEditorController):
        def __init__(self, parent):
            self._parent = parent

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            #Left panel
            self._leftPanel = JPanel(BorderLayout())
            self._leftPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Left subpanel - Positions editor
            self._positionsEditor = Utils.callbacks.createTextEditor()
            #TODO Remove a normal editor?  self._positionsEditor = Utils.callbacks.createMessageEditor(self, True)
            self._positionsEditor.getComponent().setBorder(BorderFactory.createLineBorder(Color.BLACK))
            #Left subpanel - Title pane
            self._leftTitlePanel = JPanel(GridLayout(0, 1))
            self._leftTitlePanel.setBorder(EmptyBorder(0, 10, 10, 10))
            self._titleText = JLabel("Commands Position")
            self._titleText.setForeground(COLOR_BURP_TITLE_ORANGE)
            self._titleText.setFont(self._titleText.getFont().deriveFont(16.0))
            self._titleSubtitleText = JTextArea("Configure the position where commands will be inserted into the base request. Select the requests that were send Shell in the dropdown, then select the part of the request where commands need to be inserted and click the 'Add $' button.")
            self._titleSubtitleText.setEditable(False)
            self._titleSubtitleText.setLineWrap(True)
            self._titleSubtitleText.setWrapStyleWord(True)
            self._titleSubtitleText.setHighlighter(None)
            self._titleSubtitleText.setBorder(None)
            self._leftTitlePanel.add(self._titleText)
            self._leftTitlePanel.add(self._titleSubtitleText)
            #Left subpanel - Add positions editor and title
            self._leftPanel.add(self._leftTitlePanel, BorderLayout.NORTH)
            self._leftPanel.add(self._positionsEditor.getComponent(), BorderLayout.CENTER)
            #Right panel
            #self._rightPanel = JPanel(GridLayout(20, 1))
            self._rightPanel = JPanel()
            self._rightPanel.setLayout(BoxLayout(self._rightPanel, BoxLayout.Y_AXIS))
            #self._rightPanel.setPreferredSize(Dimension(150, 30))
            self._rightPanel.setBorder(EmptyBorder(10, 10, 10, 10))
            #Right panel - buttons
            self._buttonAdd = JButton("        Add $        ", actionPerformed=self.buttonAddClick)
            self._buttonClear = JButton("       Clear $       ", actionPerformed=self.buttonClearClick) #, actionPerformed=None
            # Right panel - add components
            self._rightPanel.add(self._buttonAdd)
            self._rightPanel.add(self._buttonClear)

            self._mainPanel.add(self._rightPanel, BorderLayout.EAST)
            self._mainPanel.add(self._leftPanel, BorderLayout.CENTER)

            return self._mainPanel

        def buttonAddClick(self, e):
            Utils.out("Button Add click")
            if self._positionsEditor.getSelectedText():
                #TODO: For if it's a messageeditor in stead of texteditor Utils.out(self._positionsEditor.getSelectedData())
                self.addPosition(self._positionsEditor.getSelectionBounds())
                self._parent._consoleController.startSession()
                self._buttonAdd.setEnabled(False)

        def buttonClearClick(self, e):
            Utils.out("Button Clear click")
            self.setEditor(self._parent.currentRequestRaw())
            self._buttonAdd.setEnabled(True)

        def setEditor(self, request_in_bytes):
            self._positionsEditor.setText(request_in_bytes)
            #TODO: for if I make the positions a messageExitor: self._positionsEditor.setMessage(iHttpRequestResponse.getRequest(), True)

        def addPosition(self, boundsArray):
            if len(boundsArray) == 2:
                self._parent.setCurrentRequestBounds(boundsArray[0], boundsArray[1])
                modified_request = Utils.wrapRawData(self._parent.currentRequestRaw(), boundsArray[0], boundsArray[1], "$", "$")
                self.setEditor(modified_request)
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
Beispiel #43
0
class BurpExtender(IBurpExtender, ITab):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):

        # set our extension name
        callbacks.setExtensionName("War Story")

        # obtain our output stream
        self._stdout = PrintWriter(callbacks.getStdout(), True)

        # write a message to our output stream
        self._stdout.println("Loading WarStory")

        # write a message to the Burp alerts tab
        callbacks.issueAlert("Hello alerts")
        label = JLabel("INFO PANEL")
        self.infoPanel = JPanel()
        footerPanel = JPanel()
        footerPanel.add(JLabel("by Tim mcgyver5 McGuire"))
        self._chooseFileButton = JButton("OPEN WAR FILE",
                                         actionPerformed=self.fileButtonClick)
        self.infoPanel.add(JLabel("THIS IS INFORMATION PANE"))
        self.infoPanel.add(self._chooseFileButton)
        # iaap.war|web.xml|axServlet|/skuppy/axservlet.do|
        self._chooseFileButton.setEnabled(True)
        initial_row = ['a', 'bb', 'ccc', 'ddd', 'eeee']
        self.fileTable = JTable(ResourceTableModel(initial_row))
        scrollpane = JScrollPane(self.fileTable)

        ## this is a split inside the top component
        topPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        topPane.setTopComponent(self.infoPanel)
        topPane.setBottomComponent(scrollpane)

        # split the top panel into a Panel and a JScrollPane

        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._splitpane.setTopComponent(topPane)
        self._splitpane.setBottomComponent(footerPanel)

        callbacks.addSuiteTab(self)

    def populateJTable(self, f):
        filename = f.getPath()
        tableModel = self.fileTable.getModel()
        test_row = ["a", "b", "doo", "dah", "dob"]
        re = Resource("Servlet", "bingServlet", "bingservlet.do", [], [],
                      "GET")
        self._stdout.println("populatin table model")
        tableModel.addRow(test_row)

    def fileButtonClick(self, e):

        fileTypeList = ["war", "ear", "zip"]
        warFilter = FileNameExtensionFilter("war", fileTypeList)
        fileChooser = JFileChooser()
        fileChooser.addChoosableFileFilter(warFilter)
        result = fileChooser.showOpenDialog(self._splitpane)

        if result == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            fileName = f.getPath()
            self.populateJTable(f)

    # Implement ITab
    def getTabCaption(self):
        return "War Story"

    def getUiComponent(self):
        return self._splitpane
class DetermineCookieFrame(JFrame):
    """ This is the GUI for for the user to control the actions when
        determining which cookie is the session cookie.
    """
    def __init__(self, callbacks, selected_message):
        super(DetermineCookieFrame, self).__init__()
        self.callbacks = callbacks
        self.selected_message = selected_message
        self.windowClosing = self.close

    def loadPanel(self):
        panel = JPanel()

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

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

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

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

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

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

        bottom.add(self.progressBar)

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

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

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

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

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

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

    def close(self, event):
        global cancelThread
        cancelThread = True
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame
    def __init__(self):
        self.mainDir = ""

        self.setTitle("Dots Quality Check")
        self.setSize(250, 300)
        self.setLocation(20,120)
        self.addWindowFocusListener(self)
        
        self.Panel = JPanel(GridLayout(0,1))
        self.add(self.Panel)
        self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom)
        self.Panel.add(self.openNextButton)
        self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False)
        self.Panel.add(self.saveButton)
        self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals)
        self.Panel.add(self.cropButton)
        self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell)
        self.Panel.add(self.DiscardButton)
        self.quitButton = JButton("Quit script",actionPerformed=self.quit)
        self.Panel.add(self.quitButton)

        annoPanel = JPanel()
        #add gridlayout
        self.wtRButton = JRadioButton("wt", actionCommand="wt")
        self.wtRButton.addActionListener(self)
        self.defectRButton = JRadioButton("Defect", actionCommand="defect")
        self.defectRButton.addActionListener(self)
        annoPanel.add(self.wtRButton)
        annoPanel.add(self.defectRButton)
        self.aButtonGroup = ButtonGroup()
        self.aButtonGroup.add(self.wtRButton)
        self.aButtonGroup.add(self.defectRButton)
      
        self.Panel.add(annoPanel)

        self.ProgBar = JProgressBar()
        self.ProgBar.setStringPainted(True)
        self.ProgBar.setValue(0)
        self.Panel.add(self.ProgBar)

        self.pathLabel = JLabel("-- No main directory chosen --")
        self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
        self.Panel.add(self.pathLabel)
      
        WindowManager.addWindow(self)
        self.show()

    # - - - -   B U T T O N   M E T H O D S  - - - -
    # - - - - - -  - - - - - - - - - - - - - - - - -
    def openRandom(self, event):      # when click here: get random cell and meas.measure(csv, tif, savePath)
        if self.mainDir == "":
            self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory()
            self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
        try:
            # should be complete disposal!
            self.cT.closeWindows()
        finally:
            inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv"))  # glob.glob returns list of paths
            uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False]
            if len(uncheckedCells) > 0:
                self.cell = random.choice(uncheckedCells)
                #update progressbar
                self.ProgBar.setMaximum(len(inFiles)-1)
                self.ProgBar.setValue(len(inFiles)-len(uncheckedCells))
                # open imp and resultstable
                self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF
                self.RBActionListener.setCell(self.cell)
                # delete previous Radiobutton annotation
                self.wtRButton.setSelected(False)
                self.defectRButton.setSelected(True)
            else:
                print "All cells measured!"

    def save(self, event):
        savepath = self.cell.getQcCsvPath()
        anaphase = self.cell.getAnOn()
        timeInterval = self.cT.getImp().getCalibration().frameInterval
        annotation = self.getAnnotation()
        position = str(self.cell.position)
        cellIndex = str(self.cell.cellNo)
        if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present.
            os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present
        f = open(savepath, "w")
        # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        for i in range(self.cT.getLineCount()):
            frame, distance, a = self.cT.getLine(i).split("\t")
            corrFrame = str(int(frame)-int(anaphase))
            time = "%.f" % (round(timeInterval) * int(corrFrame))
            if distance == "NA":
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",")
            else:
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i]
            f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol)
        f.close()
        print "Successfully saved!"

    def cropVals(self, event): #"this function deletes all values with frame > current cursor"   
        for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1):
            frame, distance, AOCol = self.cT.getLine(line).split("\t")
            self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol)

    def discardCell(self, event):
        if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present.
            os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present.
        f = open(self.cell.getQcCsvPath() ,"w")
        # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        f.close()
        print "Discarded cell - saved dummy" 

    def quit(self, event):
        try:
            self.cT.closeWindows()
        finally:
            WindowManager.removeWindow(self)
            self.dispose()

    # Methods implementing ActionListener interfaces:
    def actionPerformed(self, e):
        # this function is called when RadioButtons are changed
        self.cell.annotate( e.getSource().getActionCommand() )
        self.setSaveActive()

    def windowGainedFocus(self, e):
        pass

    def windowLostFocus(self, e):
        pass
        

    # - - - - - - - - - - - - -
    # - get and set methods - -
    # - - - - - - - - - - - - -
    def getAnnotation(self):
        return self.aButtonGroup.getSelection().getActionCommand()

    def getMainDir(self):
        return self.mainDir

    def setSaveActive(self):
        if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None):
            self.saveButton.setEnabled(True)
            self.show()

    def setSaveInactive(self):
        self.saveButton.setEnabled(False)
        self.show()

    def setMainDir(self, path):
        self.mainDir = path
        self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))