def updateTable(self):
     model = DefaultTableModel()  #self.tblMunicipalities.getModel()
     manager = DALLocator.getDataManager()
     model.addColumn("CODMUN")
     model.addColumn("MUN")
     model.addColumn("FECHA")
     storeParameters = manager.createStoreParameters("H2Spatial")
     database_file = gvsig.getResource(__file__, "data",
                                       "municipalities.mv.db")
     storeParameters.setDynValue("database_file", database_file)
     storeParameters.setDynValue("Table", "Muni")
     storeH2 = manager.openStore("H2Spatial", storeParameters)
     muns = {}
     for f in storeH2:
         if not f.get("CODMUN") in muns.keys():
             muns[f.get("CODMUN")] = [f.get("MUN"), f.get("CODMUN"), '']
     for k in muns.keys():
         model.addRow(muns[k])
     storeH2.dispose()
     self.tblMunicipalities.setModel(model)
Esempio n. 2
0
 def lstPreviewForms_change(self, event):
     if event.getValueIsAdjusting():
         return
     form = self.lstPreviewForms.getSelectedValue()
     if form == None or form.isEmpty():
         self.tableSetVisible(self.tblPreviewForm, False)
         return
     model = DefaultTableModel()
     model.addColumn("")
     for item in form:
         row = jarray.array((item, ), Object)
         model.addRow(row)
     self.tblPreviewForm.setModel(model)
     renderer = FormItemPreviewCellRenderer()
     renderer.setForm(form)
     editor = FormItemPreviewCellEditor()
     editor.setForm(form)
     model = DefaultTableColumnModel()
     model.addColumn(TableColumn(0, 100, renderer, editor))
     self.tblPreviewForm.setColumnModel(model)
     self.tblPreviewForm.getTableHeader().setUI(None)
     self.tableSetVisible(self.tblPreviewForm, True)
     self.cboForms.setSelectedItem(form)
Esempio n. 3
0
class Mi_Extension(IHttpListener, IScannerCheck):
    def __init__(self, extender):
        self._callbacks = extender._callbacks
        self._helpers = extender._callbacks.getHelpers()
        self._callbacks.registerScannerCheck(self)
        # Creamos el contenedor de paneles.
        self.contenedor = JTabbedPane()

        # Campos del sub-tab 1 (mash up)
        self._tab1_nombre = JTextField()
        self._tab1_apellido = JTextField()
        self._tab1_FNacimiento = JTextField()
        self._tab1_mascota = JTextField()
        self._tab1_otro = JTextField()

        self._tab1_feedback_ta = JTextArea('This may take a while . . .')
        self._tab1_feedback_ta.setEditable(False)
        self._tab1_feedback_sp = JScrollPane(self._tab1_feedback_ta)

        self._tab1_minsize = JSlider(4, 16, 6)
        self._tab1_minsize.setMajorTickSpacing(1)
        self._tab1_minsize.setPaintLabels(True)

        self._tab1_maxsize = JSlider(4, 16, 10)
        self._tab1_maxsize.setMajorTickSpacing(1)
        self._tab1_maxsize.setPaintLabels(True)

        self._tab1_specialchars = JTextField('!,@,#,$,&,*')
        self._tab1_transformations = JCheckBox('1337 mode')
        self._tab1_firstcapital = JCheckBox('first capital letter')

        # Campos del sub-tab 2 (redirect)
        self._tab2_JTFa = JTextField()
        self._tab2_JTFaa = JTextField()
        self._tab2_JTFb = JTextField()
        self._tab2_JTFbb = JTextField()
        self._tab2_boton = JButton(' Redirect is Off ',
                                   actionPerformed=self.switch_redirect)
        self._tab2_boton.background = Color.lightGray
        self._tab2_encendido = False

        # Campos del sub-tab 3 (loader)
        self._tab3_urls_ta = JTextArea(15, 5)
        self._tab3_urls_sp = JScrollPane(self._tab3_urls_ta)

        # Campos del sub-tab 4 (headers)
        self._tab4_tabla_model = DefaultTableModel()
        self._tab4_headers_dict = {}

        # Campos del sub-tab 5 (reverse ip)
        self._tab5_target = JTextArea(15, 5)
        self._tab5_target_sp = JScrollPane(self._tab5_target)

    def create(self):

        # Estilo general para todas las sub-tab.
        gBC = GridBagConstraints()
        gBC.fill = GridBagConstraints.BOTH
        gBC.ipadx = 5
        gBC.ipady = 5
        gBC.insets = Insets(0, 5, 5, 5)
        gBC.weightx = 0.5
        #gBC.weighty = 0.7

        #######################################
        ###   Creamos la primera sub-tab. (MASHUP)
        #######################################
        tab_1 = JPanel(GridBagLayout())
        tab_1_jlabelAyuda = JLabel(
            '<html><i>&#8226Tip: This Mashup receive one or more keywords in order to generate a list of possible passwords</i></html>'
        )
        tab_1_jlabelAyuda.setFont(Font("Serif", 0, 12))

        gBC.gridx = 0
        gBC.gridy = 0
        tab_1.add(
            JLabel('<html><font color=green><i>Income:</i></font></html>'),
            gBC)

        gBC.gridy = 1
        tab_1.add(JLabel('<html><b>&#8226 Name:</b></html>'), gBC)
        gBC.gridy = 2
        tab_1.add(self._tab1_nombre, gBC)

        gBC.gridy = 3
        tab_1.add(JLabel('<html><b>&#8226 Surname:</b></html>'), gBC)
        gBC.gridy = 4
        tab_1.add(self._tab1_apellido, gBC)

        gBC.gridy = 5
        tab_1.add(JLabel('<html><b>&#8226 Birthdate: (DDMMYYYY)</b></html>'),
                  gBC)
        gBC.gridy = 6
        tab_1.add(self._tab1_FNacimiento, gBC)

        gBC.gridy = 7
        tab_1.add(JLabel('<html><b>&#8226 Pet:</b></html>'), gBC)
        gBC.gridy = 8
        tab_1.add(self._tab1_mascota, gBC)

        gBC.gridy = 9
        tab_1.add(JLabel('<html><b>&#8226 Anyother:</b></html>'), gBC)
        gBC.gridy = 10
        tab_1.add(self._tab1_otro, gBC)

        gBC.gridy = 11
        tab_1.add(JLabel('<html><b>&#8226 Passwd Min Size:</b></html>'), gBC)
        gBC.gridy = 12
        tab_1.add(self._tab1_minsize, gBC)

        gBC.gridy = 13
        tab_1.add(JLabel('<html><b>&#8226 Passwd Max Size:</b></html>'), gBC)
        gBC.gridy = 14
        tab_1.add(self._tab1_maxsize, gBC)

        gBC.gridy = 15
        tab_1.add(
            JLabel(
                '<html><b>&#8226 Especial Chars: (comma separated)</b></html>'
            ), gBC)
        gBC.gridy = 16
        tab_1.add(self._tab1_specialchars, gBC)

        gBC.gridy = 17
        tab_1.add(self._tab1_transformations, gBC)

        gBC.gridy = 18
        tab_1.add(self._tab1_firstcapital, gBC)

        gBC.gridy = 19
        tab_1.add(JButton('Mashup!', actionPerformed=self.mashup), gBC)

        gBC.gridy = 20
        gBC.gridwidth = 3
        tab_1.add(JSeparator(), gBC)
        gBC.gridwidth = 1

        gBC.gridy = 21
        gBC.gridwidth = 3
        tab_1.add(tab_1_jlabelAyuda, gBC)
        gBC.gridwidth = 1

        gBC.gridx = 1
        gBC.gridy = 0
        gBC.gridheight = 20
        gBC.weightx = 0
        tab_1.add(JSeparator(SwingConstants.VERTICAL), gBC)
        gBC.gridheight = 1
        gBC.weightx = 0.5

        gBC.gridx = 2
        gBC.gridy = 0
        tab_1.add(
            JLabel('<html><font color=green><i>Outcome:</i></font></html>'),
            gBC)

        gBC.gridy = 1
        gBC.gridwidth = 2
        gBC.gridheight = 18
        tab_1.add(self._tab1_feedback_sp, gBC)
        gBC.gridwidth = 1
        gBC.gridheight = 1

        gBC.gridy = 19
        tab_1.add(
            JButton('Copy to clipboard!', actionPerformed=self.cpy_clipboard),
            gBC)

        #######################################
        ###   Creamos la segunda sub-tab. (REDIRECT)
        #######################################
        tab_2 = JPanel(GridBagLayout())
        tab_2_jlabelAyuda = JLabel(
            '<html><i>&#8226Tip: This Redirect receive a pair of hosts x,y in order to redirect from x to y.</i></html>'
        )
        tab_2_jlabelAyuda.setFont(Font("Serif", 0, 12))

        gBC.gridx = 0
        gBC.gridy = 0
        tab_2.add(
            JLabel('<html><b>&#8226 From: (i.e. www.facebook.com)</b></html>'),
            gBC)
        gBC.gridx = 1
        gBC.gridy = 0
        tab_2.add(self._tab2_JTFa, gBC)

        gBC.gridx = 2
        gBC.gridy = 0
        tab_2.add(
            JLabel('<html><b>&#8226 To: (i.e. www.myhomepage.es)</b></html>'),
            gBC)
        gBC.gridx = 3
        gBC.gridy = 0
        tab_2.add(self._tab2_JTFaa, gBC)

        gBC.gridx = 0
        gBC.gridy = 1
        gBC.gridwidth = 4
        tab_2.add(JSeparator(), gBC)
        gBC.gridwidth = 1

        gBC.gridx = 0
        gBC.gridy = 2
        tab_2.add(JLabel('<html><b>&#8226 From:</b></html>'), gBC)
        gBC.gridx = 1
        gBC.gridy = 2
        tab_2.add(self._tab2_JTFb, gBC)

        gBC.gridx = 2
        gBC.gridy = 2
        tab_2.add(JLabel('<html><b>&#8226 To:</b></html>'), gBC)
        gBC.gridx = 3
        gBC.gridy = 2
        tab_2.add(self._tab2_JTFbb, gBC)

        gBC.gridx = 0
        gBC.gridy = 3
        gBC.gridwidth = 4
        tab_2.add(self._tab2_boton, gBC)
        gBC.gridwidth = 1

        gBC.gridx = 0
        gBC.gridy = 4
        gBC.gridwidth = 4
        gBC.insets = Insets(100, 10, 5, 10)
        tab_2.add(JSeparator(), gBC)
        gBC.gridwidth = 1
        gBC.insets = Insets(5, 10, 5, 10)

        gBC.gridx = 0
        gBC.gridy = 5
        gBC.gridwidth = 4
        tab_2.add(tab_2_jlabelAyuda, gBC)
        gBC.gridwidth = 1

        #######################################
        ###   Creamos la tercera sub-tab. (LOADER)
        #######################################
        tab_3 = JPanel(GridBagLayout())
        tab_3_jlabelAyuda = JLabel(
            '<html><i>&#8226Tip: This Loader receive a list of Hosts or IPs that will be added to the Burp Scope.</i></html>'
        )
        tab_3_jlabelAyuda.setFont(Font("Serif", 0, 12))

        gBC.gridx = 0
        gBC.gridy = 0
        tab_3.add(
            JLabel(
                '<html><font color=green><i>List of targets: (i.e. http://www.mytargetweb.com)</i></font></html>'
            ), gBC)
        gBC.gridy = 1
        gBC.gridheight = 10
        gBC.weighty = 0.5
        tab_3.add(self._tab3_urls_sp, gBC)
        gBC.gridheight = 1
        gBC.weighty = 0
        gBC.gridy = 11
        tab_3.add(
            JButton('Load Into Target => Scope!', actionPerformed=self.loader),
            gBC)

        gBC.gridy = 12
        gBC.gridwidth = 5
        gBC.insets = Insets(100, 10, 5, 10)
        tab_3.add(JSeparator(), gBC)
        gBC.gridwidth = 1
        gBC.insets = Insets(5, 10, 5, 10)

        gBC.gridy = 13
        tab_3.add(tab_3_jlabelAyuda, gBC)

        #######################################
        ###   Creamos la cuarta sub-tab. (HEADERS)
        #######################################
        tab_4_jlabelAyuda = JLabel(
            "<html><i>&#8226Tip: This Headers records all unique headers that appear in every host, check out the security headers.</i></html>"
        )
        tab_4_jlabelAyuda.setFont(Font("Serif", 0, 12))

        tab_4_jLabelRecomendacion = JLabel(
            "<html>&#8226<b>Server</b>: Don't give away much information.<br> &#8226<b>Content-Security-Policy</b>: Protect your site from XSS attacks by whitelisting sources of approved content.<br> &#8226<b>Strict-Transport-Security</b>: Enforce the browser to use HTTPS.<br> &#8226<b>Public-Key-Pins</b>: Protect your site from MITM attacks.<br> &#8226<b>X-Content-Type-Options</b>: the valid value is -> nosniff .<br> &#8226<b>X-Frame-Options</b>: tells the browser whether you want to allow your site to be framed or not.<br> &#8226<b>X-XSS-Protection</b>: the best value is -> 1; mode=block .</html>"
        )
        tab_4_jLabelRecomendacion.setFont(Font("Dialog", 0, 13))

        tab_4 = JPanel(GridBagLayout())
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        tab_4_top = JPanel(GridBagLayout())
        tab_4_bottom = JPanel(GridBagLayout())

        gBC_table = GridBagConstraints()
        gBC_table.fill = GridBagConstraints.BOTH
        gBC_table.ipadx = 5
        gBC_table.ipady = 5
        gBC_table.insets = Insets(5, 10, 5, 10)
        gBC_table.weightx = 1
        gBC_table.weighty = 1

        tabla_datos = []
        tabla_headers = ('Severity', 'Header', 'Value', 'Host')
        self._tab4_tabla_model = DefaultTableModel(tabla_datos, tabla_headers)
        tabla_ej = JTable(self._tab4_tabla_model)
        tabla_example = JScrollPane(tabla_ej,
                                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)

        gBC_table.gridx = 0
        gBC_table.gridy = 0
        gBC_table.gridheight = 5
        tab_4_top.add(tabla_example, gBC_table)
        gBC_table.gridheight = 1

        gBC_table.weightx = 0.5
        gBC_table.weighty = 0
        gBC_table.gridwidth = 2
        gBC_table.gridx = 0
        gBC_table.gridy = 0
        tab_4_bottom.add(JSeparator(), gBC_table)
        gBC_table.gridy = 1
        tab_4_bottom.add(tab_4_jlabelAyuda, gBC_table)
        gBC_table.gridy = 2
        tab_4_bottom.add(tab_4_jLabelRecomendacion, gBC_table)

        splitpane.setTopComponent(tab_4_top)
        splitpane.setBottomComponent(tab_4_bottom)
        gBC_table.weightx = 1
        gBC_table.weighty = 1
        gBC_table.gridx = 0
        gBC_table.gridy = 0
        tab_4.add(splitpane, gBC_table)

        #######################################
        ###   Creamos la quinta sub-tab. (ACTIVE SCAN)
        #######################################
        tab_5 = JPanel(GridBagLayout())
        tab_5_jlabelAyuda = JLabel(
            '<html><i>&#8226Tip: This Quick Scan receive a list of targets and launch an active scan.</i></html>'
        )
        tab_5_jlabelAyuda.setFont(Font("Serif", 0, 12))
        tab_5_jlabelWarning = JLabel(
            '<html><font color=red><i>&#8226Warning: Active scanning generates large numbers of requests which are malicious in form and which may result in compromise of the application. You should use this scanning mode with caution, only with the explicit permission of the application owner. For more information, read the documentation of active scan, Burp Suite.</font></i></html>'
        )
        tab_5_jlabelWarning.setFont(Font("Dialog", 0, 13))

        gBC.gridx = 0
        gBC.gridy = 0
        tab_5.add(
            JLabel(
                '<html><font color=green><i>List of targets: (i.e. http://192.168.1.1/index.html)</i></font></html>'
            ), gBC)
        gBC.gridy = 1
        gBC.gridheight = 8
        gBC.weighty = 0.5
        tab_5.add(self._tab5_target_sp, gBC)
        gBC.gridheight = 1
        gBC.weighty = 0
        gBC.gridy = 9
        tab_5.add(JButton('Launch Scan!', actionPerformed=self.do_active_scan),
                  gBC)

        gBC.gridy = 10
        gBC.gridwidth = 5
        gBC.insets = Insets(100, 10, 5, 10)
        tab_5.add(JSeparator(), gBC)
        gBC.gridwidth = 1
        gBC.insets = Insets(5, 10, 5, 10)

        gBC.gridy = 11
        tab_5.add(tab_5_jlabelAyuda, gBC)
        gBC.gridy = 12
        tab_5.add(tab_5_jlabelWarning, gBC)

        #######################################
        ###   Creamos la ultima sub-tab.
        #######################################
        tab_about = JPanel(GridBagLayout())

        gBC_about = GridBagConstraints()
        gBC_about.fill = GridBagConstraints.HORIZONTAL
        gBC_about.ipadx = 5
        gBC_about.ipady = 5
        gBC_about.insets = Insets(5, 10, 5, 10)
        gBC_about.weightx = 1
        gBC_about.weighty = 1

        Jlabel1 = JLabel('<html><b>Plug-in L-Tools</b></html>')
        Jlabel1.setFont(Font("Dialog", 1, 18))
        jlabel2 = JLabel(
            '<html>This Plug-in provides utilities for pentesters, researchers and developers, in order to support their work.</html>'
        )
        jlabel3 = JLabel('<html><b>CC-BY 4.0, 2017. Gino Angles</b></html>')
        jlabel3.setFont(Font("Dialog", 1, 14))
        jlabel4 = JLabel('<html><b>License</b></html>')
        jlabel4.setFont(Font("Dialog", 1, 14))
        jlabel5 = JLabel(
            '<html><img alt="Licensed under a Creative Commons BY" style="border-width:0" src="https://licensebuttons.net/l/by/4.0/88x31.png"></html>'
        )
        jlabel6 = JLabel(
            '<html>This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>.</html>'
        )
        jlabel7 = JLabel('<html><b>Dependencies</b></html>')
        jlabel7.setFont(Font("Dialog", 1, 14))
        jlabel8 = JLabel('Jython +2.7')
        jlabel9 = JLabel('http://www.jython.org')

        gBC_about.gridx = 0
        gBC_about.gridy = 0
        tab_about.add(Jlabel1, gBC_about)
        gBC_about.gridy = 1
        tab_about.add(jlabel2, gBC_about)
        gBC_about.gridy = 2
        tab_about.add(jlabel3, gBC_about)

        gBC_about.gridy = 3
        gBC_about.gridwidth = 5
        tab_about.add(JSeparator(), gBC_about)
        gBC_about.gridwidth = 1

        gBC_about.gridy = 4
        tab_about.add(jlabel4, gBC_about)
        gBC_about.gridy = 5
        tab_about.add(jlabel5, gBC_about)
        gBC_about.gridy = 6
        tab_about.add(jlabel6, gBC_about)

        gBC_about.gridy = 7
        gBC_about.gridwidth = 5
        tab_about.add(JSeparator(), gBC_about)
        gBC_about.gridwidth = 1

        gBC_about.gridy = 8
        tab_about.add(jlabel7, gBC_about)
        gBC_about.gridy = 9
        tab_about.add(jlabel8, gBC_about)
        gBC_about.gridy = 10
        tab_about.add(jlabel9, gBC_about)

        # Añadimos los sub-tab al contenedor y lo devolvemos.
        self.contenedor.addTab('Mashup', tab_1)
        self.contenedor.addTab('Redirect', tab_2)
        self.contenedor.addTab('Loader', tab_3)
        self.contenedor.addTab('Headers', tab_4)
        self.contenedor.addTab('Quick Scan', tab_5)
        self.contenedor.addTab('About', tab_about)

        return self.contenedor

    # Funcion que copia el contenido de texto al clipboard.
    def cpy_clipboard(self, event):
        toolkit = Toolkit.getDefaultToolkit()
        clipboard = toolkit.getSystemClipboard()
        clipboard.setContents(StringSelection(self._tab1_feedback_ta.text),
                              None)
        JOptionPane.showMessageDialog(self.contenedor,
                                      "Output copied to clipboard",
                                      "Information",
                                      JOptionPane.INFORMATION_MESSAGE)
        return

    # Funcion que instancia la clase Masher() y hace el mashup del sub-tab1 (mashup).
    def mashup(self, event):
        if self._tab1_minsize.value > self._tab1_maxsize.value:
            self._callbacks.issueAlert(
                'Mashup=> min size have to be bigger than max size.')
        else:
            estado_JCH_trans = self._tab1_transformations.isSelected()
            especial_chars = self._tab1_specialchars.text.split(",")
            mymash = Masher(self._tab1_minsize.value, self._tab1_maxsize.value,
                            especial_chars, estado_JCH_trans)
            reverse_name = self._tab1_nombre.text[::-1]
            if self._tab1_firstcapital.isSelected():
                lista_palabras = [
                    self._tab1_nombre.text.title(),
                    self._tab1_apellido.text.title(),
                    self._tab1_FNacimiento.text,
                    self._tab1_mascota.text.title(),
                    self._tab1_otro.text.title(),
                    reverse_name.title()
                ]
            else:
                lista_palabras = [
                    self._tab1_nombre.text, self._tab1_apellido.text,
                    self._tab1_FNacimiento.text, self._tab1_mascota.text,
                    self._tab1_otro.text, reverse_name
                ]

            while "" in lista_palabras:
                lista_palabras.remove("")
            rdo_rdo = mymash.mashup(lista_palabras,
                                    self._tab1_FNacimiento.text)
            self._tab1_feedback_ta.text = "\n".join(rdo_rdo)
        return

    # Funcion que activa/desactiva el redirect.
    def switch_redirect(self, event):
        if not self._tab2_encendido:
            self._tab2_boton.text = ' Redirect is On '
            self._tab2_boton.background = Color.gray
            self._tab2_encendido = True
            # Registramos la instancia del escuchador http.
            self._callbacks.registerHttpListener(self)
        else:
            self._tab2_boton.text = ' Redirect is Off '
            self._tab2_boton.background = Color.lightGray
            self._tab2_encendido = False
            # Borramos la instancia del escuchador http.
            self._callbacks.removeHttpListener(self)
        return

    # @override
    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if messageIsRequest and self._tab2_encendido:
            serviceHttp = messageInfo.getHttpService()
            if messageInfo.getHttpService().getHost() == self._tab2_JTFa.text:
                if self._tab2_JTFaa.text == '':
                    self._tab2_JTFaa.text = 'localhost'
                messageInfo.setHttpService(
                    self._helpers.buildHttpService(self._tab2_JTFaa.text,
                                                   serviceHttp.getPort(),
                                                   serviceHttp.getProtocol()))
            elif messageInfo.getHttpService().getHost(
            ) == self._tab2_JTFb.text:
                if self._tab2_JTFbb.text == '':
                    self._tab2_JTFbb.text = 'localhost'
                messageInfo.setHttpService(
                    self._helpers.buildHttpService(self._tab2_JTFbb.text,
                                                   serviceHttp.getPort(),
                                                   serviceHttp.getProtocol()))
        return

    # Funcion que carga el textArea de URL a Scope.
    def loader(self, event):
        lista_url = self._tab3_urls_ta.text.split("\n")
        for newUrl in lista_url:
            self._callbacks.includeInScope(URL(newUrl))
        return

    # @override
    def doPassiveScan(self, request_response):
        _response = request_response.getResponse()
        _request = request_response.getRequest()
        _httpService = request_response.getHttpService()
        _url = request_response.getHttpService().getHost()
        info_response = self._helpers.analyzeResponse(_response)
        info_request = self._helpers.analyzeRequest(_httpService, _request)
        headers = info_response.getHeaders()
        _fullUrl = info_request.getUrl().toString()

        for head in headers:
            head_w1 = head.split("\n")
            for head_w2 in head_w1:
                head_w3 = head_w2.split(":")
                if len(head_w3) > 1:
                    head_w3[0].encode('ascii', 'ignore')
                    head_w3[1].encode('ascii', 'ignore')

                    key = "%s-%s" % (_url, head_w3[0])

                    if key not in self._tab4_headers_dict:
                        critical = self.analizeHeader(head_w3[0])

                        fila_tabla = [
                            critical, head_w3[0], head_w3[1], _fullUrl
                        ]

                        self._tab4_headers_dict[key] = fila_tabla
                        self._tab4_tabla_model.addRow(fila_tabla)
        return

    # devuelve cuan importante es la cabecera HTTP.
    def analizeHeader(self, header):
        if header == "Content-Security-Policy":
            return "High"
        elif header == "X-Content-Type-Options":
            return "High"
        elif header == "X-Frame-Options":
            return "High"
        elif header == "X-XSS-Protection":
            return "High"
        elif header == "Strict-Transport-Security":
            return "High"
        elif header == "Public-Key-Pins":
            return "High"
        elif header == "Access-Control-Allow-Origin":
            return "High"
        elif header == "X-Permitted-Cross-Domain-Policies":
            return "High"
        elif header == "X-Powered-By":
            return "Information"
        elif header == "Server":
            return "Information"
        elif header == "Referrer-Policy":
            return "Medium"
        else:
            return " "

    # realiza un escaner al host/s apuntado.
    def do_active_scan(self, event):
        _lista_urls = self._tab5_target.text.split("\n")
        for _x_url in _lista_urls:
            _target_url = URL(_x_url)
            _target_request = self._helpers.buildHttpRequest(_target_url)

            _host = _target_url.getHost()
            _port = _target_url.getDefaultPort()
            _isHttps = True if _target_url.getProtocol() == "https" else False

            try:
                self._callbacks.doActiveScan(_host, _port, _isHttps,
                                             _target_request)
            except:
                pass
        return
Esempio n. 4
0
class PropertyEditor(WindowAdapter):
    """
    Edits Tabular Properties of a given WindowAdapter
    """
    instances = {}
    last_location = None
    locations = {}
    last_size = None
    sizes = {}

    NEW_WINDOW_OFFSET = 32
    offset = NEW_WINDOW_OFFSET

    @staticmethod
    def get_instance(text="Property Editor",
                     columns=None,
                     data=None,
                     empty=None,
                     add_actions=True,
                     actions=None):
        """
        Singleton Method based on the text property. It tries to generate only one property configuration page per text.

        :param text: getinstance key
        :param columns: proparty columns it should be an array alike
        :param data: it contains the current property rows
        :param empty: empty row property when adding a new one
        :param add_actions: include or not new actions
        :param actions: default set of actions to be appended to Add and Delete Rows
        :return: a new instance of PropertyEditor or a reused one.
        """
        if not actions: actions = []
        if not columns: columns = []
        if data == None: data = []
        if not empty: empty = []
        try:
            PropertyEditor.instances[text]
        except KeyError:
            PropertyEditor.instances[text] = \
                PropertyEditor().__private_init__(text, columns, data, empty, add_actions, actions)
            try:
                PropertyEditor.instances[text].this.setLocation(
                    PropertyEditor.locations[text])
            except KeyError:
                if PropertyEditor.last_location:
                    PropertyEditor.instances[text].this.setLocation(
                        PropertyEditor.last_location.x + PropertyEditor.offset,
                        PropertyEditor.last_location.y + PropertyEditor.offset)
                    PropertyEditor.offset = PropertyEditor.NEW_WINDOW_OFFSET
            try:
                PropertyEditor.instances[text].this.setSize(
                    PropertyEditor.sizes[text])
            except KeyError:
                if PropertyEditor.last_size:
                    PropertyEditor.instances[text].this.setSize(
                        PropertyEditor.last_size)
            PropertyEditor.last_location = PropertyEditor.instances[
                text].this.getLocation()
            PropertyEditor.last_size = PropertyEditor.instances[
                text].this.getSize()
        ## Hack ON: Bring on Front
        PropertyEditor.instances[text].this.setAlwaysOnTop(True)
        PropertyEditor.instances[text].this.setAlwaysOnTop(False)
        ## Hack OFF
        return PropertyEditor.instances[text]

    def __private_init__(self,
                         text="Property Editor",
                         columns=None,
                         data=None,
                         empty=None,
                         add_actions=True,
                         actions=None):
        if not actions: actions = []
        if not columns: columns = []
        if data == None: data = []
        if not empty: empty = []

        self._text = text
        self.this = JFrame(text)
        self._table = JTable()
        self._dtm = DefaultTableModel(0, 0)
        self._dtm.setColumnIdentifiers(columns)
        self._table.setModel(self._dtm)
        self._data = data
        for d in data:
            self._dtm.addRow(d)
        self._pane = JScrollPane(self._table)
        self.this.add(self._pane)
        self._empty = empty

        self.this.addWindowListener(self)

        self._dtm.addTableModelListener(lambda _: self._update_model())
        self.this.setLocation(PropertyEditor.NEW_WINDOW_OFFSET,
                              PropertyEditor.NEW_WINDOW_OFFSET)

        if add_actions:
            self._popup = JPopupMenu()
            self._pane.setComponentPopupMenu(self._popup)
            inherits_popup_menu(self._pane)

            self._actions = actions
            self._actions.append(
                ExecutorAction('Remove Selected Rows',
                               action=lambda e: self._remove_row()))
            self._actions.append(
                ExecutorAction('Add New Row',
                               action=lambda e: self._add_row()))

            for action in self._actions:
                self._popup.add(action.menuitem)

        self.this.setForeground(Color.black)
        self.this.setBackground(Color.lightGray)
        self.this.pack()
        self.this.setVisible(True)
        self.this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)

        return self

    def _add_row(self):
        """
        Add a new row the selection

        :return: None
        """
        self._dtm.addRow(self._empty)

    def _remove_row(self):
        """
        Remove all the selected rows from the selection
        :return:
        """
        rows = self._table.getSelectedRows()
        for i in range(0, len(rows)):
            self._dtm.removeRow(rows[i] - i)

    def windowClosing(self, evt):
        """
        Overrides WindowAdapter method

        :param evt: unused
        :return: None
        """
        PropertyEditor.locations[self._text] = self.this.getLocation()
        PropertyEditor.sizes[self._text] = self.this.getSize()
        PropertyEditor.last_location = self.this.getLocation()
        PropertyEditor.last_size = self.this.getSize()
        PropertyEditor.offset = 0
        self.this.setVisible(False)
        self.this.dispose()
        del PropertyEditor.instances[self._text]

    def _update_model(self):
        """
        Update the data content with the updated rows

        :return: None
        """
        del self._data[:]
        nRow = self._dtm.getRowCount()
        nCol = self._dtm.getColumnCount()
        for i in range(0, nRow):
            self._data.append([None] * nCol)
            for j in range(0, nCol):
                d = str(self._dtm.getValueAt(i, j)).lower()
                if d == 'none' or d == '':
                    self._data[i][j] = None
                elif d == 'true' or d == 't':
                    self._data[i][j] = True
                elif d == 'false' or d == 'f':
                    self._data[i][j] = False
                else:
                    try:
                        self._data[i][j] = int(self._dtm.getValueAt(i, j))
                    except ValueError:
                        self._data[i][j] = self._dtm.getValueAt(i, j)
class BurpExtender(IBurpExtender, ISessionHandlingAction, ITab,
                   IContextMenuFactory, IContextMenuInvocation, ActionListener,
                   ITextEditor):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        # save the helpers for later
        self.helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Custom Request Handler")
        callbacks.registerSessionHandlingAction(self)
        callbacks.registerContextMenuFactory(self)
        self._text_editor = callbacks.createTextEditor()
        self._text_editor.setEditable(False)

        #How much loaded the table row
        self.current_column_id = 0

        #GUI
        self._split_main = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._split_top = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._split_top.setPreferredSize(Dimension(100, 50))
        self._split_top.setDividerLocation(700)
        self._split_center = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        boxVertical = swing.Box.createVerticalBox()
        box_top = swing.Box.createHorizontalBox()
        boxHorizontal = swing.Box.createHorizontalBox()
        buttonHorizontal = swing.Box.createHorizontalBox()
        boxVertical.add(boxHorizontal)

        box_regex = swing.Box.createVerticalBox()
        border = BorderFactory.createTitledBorder(LineBorder(Color.BLACK),
                                                  "Extract target strings",
                                                  TitledBorder.LEFT,
                                                  TitledBorder.TOP)
        box_regex.setBorder(border)

        self._add_btn = JButton("Add")
        self._add_btn.addActionListener(self)
        self._remove_btn = JButton("Remove")
        self._remove_btn.addActionListener(self)

        items = [
            'JSON',
            'Header',
        ]
        self._dropdown = JComboBox(items)
        type_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        type_panel.add(JLabel('Type:'))
        type_panel.add(self._dropdown)

        self._jLabel_param = JLabel("Name:")
        self._param_error = JLabel("Name is required")

        self._param_error.setVisible(False)
        self._param_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._param_error.setForeground(Color.red)

        regex_checkbox = JPanel(FlowLayout(FlowLayout.LEADING))
        self._is_use_regex = JCheckBox("Extract from regex group")
        regex_checkbox.add(self._is_use_regex)
        self._jTextIn_param = JTextField(20)
        self._jLabel_regex = JLabel("Regex:")
        self._jTextIn_regex = JTextField(20)
        self._regex_error = JLabel("No group defined")
        self._regex_error.setVisible(False)
        self._regex_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._regex_error.setForeground(Color.red)

        self._param_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._param_panel.add(self._jLabel_param)
        self._param_panel.add(self._jTextIn_param)
        self._param_panel.add(self._param_error)

        self._regex_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._regex_panel.add(self._jLabel_regex)
        self._regex_panel.add(self._jTextIn_regex)
        self._regex_panel.add(self._regex_error)
        button_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        #padding
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(self._add_btn)
        button_panel.add(self._remove_btn)
        box_regex.add(type_panel)
        box_regex.add(self._param_panel)
        box_regex.add(regex_checkbox)
        box_regex.add(self._regex_panel)
        buttonHorizontal.add(button_panel)
        box_regex.add(buttonHorizontal)
        boxVertical.add(box_regex)
        box_top.add(boxVertical)

        box_file = swing.Box.createHorizontalBox()
        checkbox_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        border = BorderFactory.createTitledBorder(
            LineBorder(Color.BLACK), 'Payload Sets [Simple list]',
            TitledBorder.LEFT, TitledBorder.TOP)
        box_file.setBorder(border)

        box_param = swing.Box.createVerticalBox()
        box_param.add(checkbox_panel)

        file_column_names = [
            "Type",
            "Name",
            "Payload",
        ]
        data = []
        self.file_table_model = DefaultTableModel(data, file_column_names)
        self.file_table = JTable(self.file_table_model)
        self.file_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)

        column_model = self.file_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(160)

        self.file_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.file_table.setFillsViewportHeight(True)

        panel_dropdown = JPanel(FlowLayout(FlowLayout.LEADING))
        self._file_dropdown = JComboBox(items)
        panel_dropdown.add(JLabel('Type:'))
        panel_dropdown.add(self._file_dropdown)
        box_param.add(panel_dropdown)
        box_param.add(JScrollPane(self.file_table))
        callbacks.customizeUiComponent(self.file_table)

        file_param_panel = JPanel(FlowLayout(FlowLayout.LEADING))

        self._file_param = JLabel("Name:")
        self._file_param_text = JTextField(20)

        file_param_panel.add(self._file_param)
        file_param_panel.add(self._file_param_text)
        self._error_message = JLabel("Name is required")
        self._error_message.setVisible(False)
        self._error_message.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._error_message.setForeground(Color.red)
        file_param_panel.add(self._error_message)
        box_param.add(file_param_panel)

        box_button_file = swing.Box.createVerticalBox()
        self._file_load_btn = JButton("Load")

        self._file_clear_btn = JButton("Clear")
        self._file_clear_btn.addActionListener(self)
        self._file_load_btn.addActionListener(self)
        box_button_file.add(self._file_load_btn)
        box_button_file.add(self._file_clear_btn)
        box_file.add(box_button_file)
        box_file.add(box_param)
        boxVertical.add(box_file)

        regex_column_names = [
            "Type",
            "Name",
            "Regex",
            "Start at offset",
            "End at offset",
        ]
        #clear target.json
        with open("target.json", "w") as f:
            pass
        data = []
        self.target_table_model = DefaultTableModel(data, regex_column_names)
        self.target_table = JTable(self.target_table_model)
        self.target_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        column_model = self.target_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(100)

        self.target_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.target_table.setFillsViewportHeight(True)
        callbacks.customizeUiComponent(self.target_table)
        callbacks.customizeUiComponent(boxVertical)
        table_panel = swing.Box.createVerticalBox()
        table_panel.add(JScrollPane(self.target_table))
        box_top.add(table_panel)

        self._jScrollPaneOut = JScrollPane()
        #self._split_main.setBottomComponent(self._jScrollPaneOut)
        self._split_main.setBottomComponent(self._text_editor.getComponent())
        self._split_main.setTopComponent(box_top)
        self._split_main.setDividerLocation(450)
        callbacks.customizeUiComponent(self._split_main)
        callbacks.addSuiteTab(self)
        return

    def getTabCaption(self):
        return "CRH"

    def getUiComponent(self):
        return self._split_main

    def createMenuItems(self, invocation):
        menu = []
        ctx = invocation.getInvocationContext()
        menu.append(
            swing.JMenuItem("Send to CRH",
                            None,
                            actionPerformed=lambda x, inv=invocation: self.
                            menu_action(inv)))
        return menu if menu else None

    #
    # Implementation of Menu Action
    #
    def menu_action(self, invocation):
        try:
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0].getResponse()
            res_info = self.helpers.analyzeResponse(message)
            send_res = message.tostring()
            self._text_editor.setText(send_res)
        except:
            print('Failed to add data to CRH tab.')

    #
    # Implementation of event action
    #
    def actionPerformed(self, actionEvent):

        # onclick add button of extract from regex group
        if actionEvent.getSource() is self._add_btn:
            start, end = self._text_editor.getSelectionBounds()
            value = None
            regex = None
            item = self._dropdown.getSelectedItem()
            param = self._jTextIn_param.getText()

            if len(param) is 0:
                self._param_error.setVisible(True)
                return
            self._param_error.setVisible(False)
            is_selected = self._is_use_regex.isSelected()
            if is_selected:
                start = None
                end = None
                regex = self._jTextIn_regex.getText()
                if len(regex) is 0:
                    self._regex_error.setVisible(True)
                    return

                req = self._text_editor.getText()
                try:
                    pattern = re.compile(regex)
                    match = pattern.search(req)
                    value = match.group(1) if match else None
                    if value is None:
                        raise IndexError
                except IndexError:
                    self._regex_error.setVisible(True)
                    return
                self._regex_error.setVisible(False)

            data = [
                item,
                param,
                regex,
                start,
                end,
            ]
            self.target_table_model.addRow(data)

            with open("target.json", "r+") as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()
                if is_selected:
                    data = {
                        param: [
                            item,
                            regex,
                        ]
                    }
                else:
                    data = {
                        param: [
                            item,
                            start,
                            end,
                        ]
                    }
                json_data.update(data)
                self.write_file(f, json.dumps(json_data))

        # onclick remove button of extract from regex group
        if actionEvent.getSource() is self._remove_btn:
            rowno = self.target_table.getSelectedRow()
            if rowno != -1:
                column_model = self.target_table.getColumnModel()
                param_name = self.target_table_model.getValueAt(rowno, 1)
                start = self.target_table_model.getValueAt(rowno, 3)

                self.target_table_model.removeRow(rowno)
                with open("target.json", 'r+') as f:
                    try:
                        json_data = json.load(f)
                    except ValueError:
                        json_data = dict()

                    for key, value in json_data.items():
                        if value[1] == start and key == param_name:
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                    self.write_file(f, json.dumps(json_data))

        # onclick load button of payload sets
        if actionEvent.getSource() is self._file_load_btn:
            #clear table
            self.remove_all(self.file_table_model)
            self.current_column_id = 0

            target_param = self._file_param_text.getText()
            item = self._file_dropdown.getSelectedItem()

            if len(target_param) == 0:
                self._error_message.setVisible(True)
                return
            self._error_message.setVisible(False)

            chooser = JFileChooser()
            chooser.showOpenDialog(actionEvent.getSource())
            file_path = chooser.getSelectedFile().getAbsolutePath()
            with open(file_path, 'r') as f:
                while True:
                    line = f.readline().strip()
                    if not line:
                        break
                    data = [
                        item,
                        target_param,
                        line,
                    ]
                    self.file_table_model.addRow(data)

            with open('target.json', 'r+') as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()

                json_data.update({target_param: [
                    item,
                    'Set payload',
                ]})
                self.write_file(f, json.dumps(json_data))

        # onclick clear button of payload sets
        if actionEvent.getSource() is self._file_clear_btn:
            self.remove_all(self.file_table_model)

            self.current_column_id = 0

            with open("target.json", 'r+') as f:
                try:
                    json_data = json.load(f)
                except:
                    json_data = dict()

                for key, value in json_data.items():
                    if isinstance(value[1], unicode):
                        if value[1].encode('utf-8') == 'Set payload':
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                self.write_file(f, json.dumps(json_data))

    #
    # Implementaion of ISessionHandlingAction
    #
    def getActionName(self):
        return "custom request handler"

    def performAction(self, current_request, macro_items):

        if len(macro_items) == 0:
            return

        # extract the response headers
        final_response = macro_items[len(macro_items) - 1].getResponse()
        if final_response is None:
            return

        req = self.helpers.analyzeRequest(current_request)

        try:
            with open('target.json', 'r') as f:
                read_data = f.read()
                self.read_data = json.loads(read_data)
        except ValueError:
            sys.stderr.write('Error: json.loads()')
            return

        for key, value in self.read_data.items():
            if value[0] == 'JSON':
                self.set_json_parameter(current_request, final_response, key,
                                        value)
            elif value[0] == 'Header':
                self.set_header(current_request, final_response, key, value)

    def set_json_parameter(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)

        if IRequestInfo.CONTENT_TYPE_JSON != req.getContentType():
            return False

        body = current_request.getRequest()[req.getBodyOffset():].tostring()
        json_data = json.loads(body, object_pairs_hook=collections.OrderedDict)

        target_keys = filter(lambda x: x == key, json_data.keys())
        if not target_keys:
            return

        req_data = json_data
        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.tostring())
                    req_value = match.group(1) if match else None

            req_data[key] = req_value

        req = current_request.getRequest()
        json_data_start = self.helpers.indexOf(req, bytearray(body), False, 0,
                                               len(req))

        # glue together header + customized json of request
        current_request.setRequest(
            req[0:json_data_start] +
            self.helpers.stringToBytes(json.dumps(req_data)))

    def set_header(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)
        headers = req.getHeaders()
        target_keys = []
        for header in headers:
            if header.startswith(key):
                target_keys += [key]

        if not target_keys:
            return

        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        req = current_request.getRequest()

        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.string())
                    req_value = match.group(1) if match else None

            key_start = self.helpers.indexOf(req,
                                             bytearray(key.encode('utf-8')),
                                             False, 0, len(req))
            key_end = self.helpers.indexOf(req, bytearray('\r\n'), False,
                                           key_start, len(req))

            keylen = len(key)

        # glue together first line + customized hedaer + rest of request
        current_request.setRequest(
            req[0:key_start] +
            self.helpers.stringToBytes("%s: %s" %
                                       (key.encode('utf-8'), req_value)) +
            req[key_end:])

    #
    # Implementation of function for Remove all for specific table data
    #
    def remove_all(self, model):
        count = model.getRowCount()
        for i in xrange(count):
            model.removeRow(0)

    #
    # Implementaion of function for write data for specific file
    #
    def write_file(self, f, data):
        f.seek(0)
        f.write(data)
        f.truncate()
        return