Пример #1
0
 def __init__(self):
     # set up the layout
     self.__component = JPanel(GridBagLayout())
     self.__image = JLabel()
     self.__album = JLabel()
     self.__artist = JLabel()
     self.__application = None
     self.__image.setVerticalAlignment(SwingConstants.TOP)
     self.__album.setVerticalAlignment(SwingConstants.TOP)
     self.__artist.setVerticalAlignment(SwingConstants.TOP)
     gbc = GridBagConstraints()
     gbc.fill = GridBagConstraints.VERTICAL
     gbc.anchor = GridBagConstraints.NORTHWEST
     gbc.gridx = 0
     gbc.gridy = 0
     gbc.weighty = 2
     gbc.gridheight = 2
     self.__component.add(self.__image, gbc)
     gbc.fill = GridBagConstraints.HORIZONTAL
     gbc.anchor = GridBagConstraints.NORTHWEST
     gbc.gridx = 1
     gbc.gridy = 0
     gbc.gridheight = 1
     gbc.weighty = 0
     gbc.insets = Insets(0, 10, 0, 10)
     self.__component.add(self.__album, gbc)
     gbc.fill = GridBagConstraints.BOTH
     gbc.anchor = GridBagConstraints.NORTHWEST
     gbc.gridx = 1
     gbc.gridy = 1
     gbc.weightx = 2
     gbc.weighty = 2
     gbc.gridheight = 1
     self.__component.add(self.__artist, gbc)
Пример #2
0
def cachedBPROM(genome, fileName, frame):
  """
  genome: Genome as a string.
  fileName: File to save the BPROM results in.
  swing: A JFrame or None.  If this is None then messages will be printed, if it isn't then
         they will also be put in a dialog box.

  return: Results of the BPROM prediction stored in a list of Promoter objects.

  If the file Specified by fileName already exists then this function simply parses the file
  already there.  Also, if a request is made to BPROM and nothing is returned, no file is
  created, the user is warned, and an empty list is returned.
  """
  offset = 25 if ".forward.bprom" in fileName else 50
  direction = "forward" if offset == 50 else "reverse"
    
  def getPromoters():
    input = open(fileName, "r")
    results = parseBPROM(input.read())
    input.close()
    return results

  if not os.path.isfile(fileName):
    results = urllib.urlopen("http://linux1.softberry.com/cgi-bin/programs/gfindb/bprom.pl",
                             urllib.urlencode({"DATA" : genome}))
    resultString = results.read()
    results.close()
    resultString = resultString[resultString.find("<pre>"):resultString.find("</pre>")]
    resultString = re.sub("<+.+>+", "", resultString).strip()
    if resultString:
      output = open(fileName, "w")
      output.write(resultString)
      output.close()
      return getPromoters()
    else:
      if frame:
        messageFrame = JFrame("BPROM Error",
                              defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE)
        messageFrame.setLocation(frame.location().x + offset, frame.location().y + offset)
        messageFrame.contentPane.layout = GridBagLayout()
        constraints = GridBagConstraints()
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        messageFrame.contentPane.add(JLabel("<html>The pipeline will continue to run but BPROM<br/>did not process the request for promoters on the<br/>" + direction + " strand.  Try again tomorrow.</html>"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 1, 1
        constraints.anchor = GridBagConstraints.LINE_END
        messageFrame.contentPane.add(JButton("Ok", actionPerformed = lambda e: messageFrame.dispose()), constraints)
        messageFrame.pack()
        messageFrame.visible = True
      print "BPROM Error:", "The pipeline will continue to run but BPROM did not process the request for promoters on the " + direction + " strand.  Try again tomorrow"
      return []
  else:
    return getPromoters()
Пример #3
0
 def __createDropDownConstraints(self):
     constr = GridBagConstraints()
     constr.fill = GridBagConstraints.HORIZONTAL
     constr.weighty = 1
     constr.gridwidth = 4
     constr.gridx = 0
     constr.gridy = 0
     return constr
Пример #4
0
 def __createRadioConstraints(self, mode):
     constr = GridBagConstraints()
     constr.fill = GridBagConstraints.HORIZONTAL
     constr.weighty = 1
     constr.weightx = 1
     if   mode == 'cases':    constr.gridx = 2
     elif mode == 'commands': constr.gridx = 3
     constr.gridy = 1
     return constr
Пример #5
0
 def __createTableConstraints(self):
     constr = GridBagConstraints()
     constr.fill = GridBagConstraints.BOTH
     constr.weighty = 1000
     constr.weightx = 2
     constr.gridwidth = 4
     constr.gridx = 0
     constr.gridy = 2
     return constr
Пример #6
0
 def __setupLayout(self):
     self.setLayout(GridBagLayout())
     constr = GridBagConstraints()
     constr.weighty = 1
     constr.weightx = 1
     constr.gridx = 0
     constr.gridy = 1
     constr.fill = GridBagConstraints.BOTH
     return constr
Пример #7
0
def _new_grid_bag(gridx, gridy, gridwidth=1):
    """Creates a new GridBagConstraints"""

    g = GridBagConstraints()
    g.gridx = gridx
    g.gridy = gridy
    g.gridwidth = gridwidth
    g.fill = GridBagConstraints.BOTH
    g.insets = Insets(2,2,5,5)

    return g
Пример #8
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("MAE ")
    frame.setSize(1024, 768)
    panel= JPanel()
    panel.setLayout(GridBagLayout())
    
    #Create and set up the content pane.
    psimures= SimoutPanel()
    psimures.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 0
    panel.add(psimures, c);
    pmeasure= MeasPanel()
    pmeasure.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 1
    panel.add(pmeasure, c);
    preport = ReportPanel()
    preport.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.VERTICAL
    c.weighty = 1
    c.gridx = 1
    c.gridy = 0
    c.gridheight= 2
    panel.add(preport,c)
    # show the GUI
    
    frame.add(panel)
#     frame.add(pmeasure)
#     frame.add(preport)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
Пример #9
0
    def __init__(self):
        self.setLayout(GridBagLayout())

        shrinkX = JButton("shrinkX")
        shrinkX.actionPerformed = lambda event : rescaleLayout(0.5, 1)
        constr = GridBagConstraints()
        constr.gridx = 0
        constr.gridy = 0
        self.add(shrinkX, constr)

        growX = JButton("growX")
        growX.actionPerformed = lambda event : rescaleLayout(1.5, 1)
        constr = GridBagConstraints()
        constr.gridx = 2
        constr.gridy = 0
        self.add(growX, constr)

        shrinkY = JButton("shrinkY")
        shrinkY.actionPerformed = lambda event : rescaleLayout(1, 0.5)
        constr = GridBagConstraints()
        constr.gridx = 0
        constr.gridy = 2
        self.add(shrinkY, constr)

        growY = JButton("growY")
        growY.actionPerformed = lambda event : rescaleLayout(1, 1.5)
        constr = GridBagConstraints()
        constr.gridx = 2
        constr.gridy = 2
        self.add(growY, constr)

        centerB = JButton("center")
        centerB.actionPerformed = lambda event : center()
        constr = GridBagConstraints()
        constr.gridx = 1
        constr.gridy = 1
        self.add(centerB, constr)

        ui.dock(self)
Пример #10
0
    def initComponents(self):

        self.setLayout(GridBagLayout())

        gbc = GridBagConstraints()
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridx = 0
        gbc.gridy = 0

        descriptionLabel = JLabel("FEA - BitCoin Validation module")
        self.add(descriptionLabel, gbc)

        tlHitlist = JLabel("Base list of hashes to analyze: ")
        gbc.gridy = 1
        self.add(tlHitlist, gbc)

        self.tbHitlist = JTextField("testlist", 20)
        self.tbHitlist.addActionListener(self.tbHitlistActionPerformed)
        gbc.gridx = 1
        self.add(self.tbHitlist, gbc)

        gbc.gridx = 0
        self.cbBlockchainCheck = JCheckBox(
            "Query Blockchain.info",
            actionPerformed=self.cbBlockchainCheckActionPerformed)
        self.cbBlockchainCheck.setSelected(True)
        gbc.gridy = 2
        self.add(self.cbBlockchainCheck, gbc)

        tlBCMaxHits = JLabel(
            "Timeout (in seconds) between calls to Blockchain.info: ")
        gbc.gridy = 3
        self.add(tlBCMaxHits, gbc)

        self.tbMaxBCHits = JTextField("5", 5)
        self.tbMaxBCHits.addActionListener(self.tbMaxBCHitsActionPerformed)
        gbc.gridx = 1
        self.add(self.tbMaxBCHits, gbc)
Пример #11
0
def arrange_plots(regplot, plotm, plotd):
    """
    arranges the plots in a certain order, 
    regplot and plotm in first row next to each other
    plotd in second row 
    """
    from javax.swing import JPanel, JFrame
    from java.awt import GridBagLayout, GridBagConstraints
    mainPanel = JPanel()
    mainPanel.setLayout(GridBagLayout())
    c = GridBagConstraints()
    c.fill = c.BOTH
    c.weightx, c.weighty = 0.5, 1
    c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 0, 10, 4
    c.weightx, c.weighty = 0.5, 1
    c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 0, 10, 4
    mainPanel.add(regplot)
    c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 0, 10, 4
    c.weightx, c.weighty = 1, 1
    mainPanel.add(plotm, c)
    c.gridx, c.gridy, c.gridwidth, c.gridheight = 0, 4, 10, 6
    mainPanel.add(plotd, c)
    return mainPanel
Пример #12
0
def arrange_plots(regplot, plotm, plotd):
    """
    arranges the plots in a certain order, 
    regplot and plotm in first row next to each other
    plotd in second row 
    """
    from javax.swing import JPanel,JFrame
    from java.awt import GridBagLayout, GridBagConstraints
    mainPanel = JPanel()
    mainPanel.setLayout(GridBagLayout())
    c=GridBagConstraints()
    c.fill=c.BOTH
    c.weightx,c.weighty=0.5,1
    c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
    c.weightx,c.weighty=0.5,1
    c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
    mainPanel.add(regplot)
    c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
    c.weightx,c.weighty=1,1
    mainPanel.add(plotm,c)
    c.gridx,c.gridy,c.gridwidth,c.gridheight=0,4,10,6
    mainPanel.add(plotd,c)
    return mainPanel
Пример #13
0
    def __init__(self):
        self.running = True
        menuBar = JMenuBar()
        
        menu = JMenu("File")
        menu.add(OpenAction(self))
        menu.add(CloseAction(self))
        menu.addSeparator()
        menu.add(QuitAction(self))
        self.addWindowListener(ProfelisWindowAdapter(self))
        menuBar.add(menu)

        self.setJMenuBar(menuBar)

        self.contentPane = JPanel()
        self.contentPane.layout = GridBagLayout()
        constraints = GridBagConstraints()

        self.blastLocation = JTextField(System.getProperty("user.home") + "/blast")
        self.databaseLocation = JTextField(System.getProperty("user.home") + "/blast/db")
        self.projects = JTabbedPane()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Blast Location"), constraints)
        constraints.gridx, constraints.gridy = 1, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.blastLocation, constraints)
        constraints.gridx, constraints.gridy = 2, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(BlastAction(self)), constraints)
        constraints.gridx, constraints.gridy = 3, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Database Location"), constraints)
        constraints.gridx, constraints.gridy = 4, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.databaseLocation, constraints)
        constraints.gridx, constraints.gridy = 5, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(DatabaseAction(self)), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        constraints.gridwidth, constraints.gridheight = 6, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.contentPane.add(self.projects, constraints)
Пример #14
0
  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)
Пример #15
0
    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)
Пример #16
0
 def __fillQuestions(self):
   panel = JPanel()
   panel.setLayout(GridBagLayout())
   panel.setBorder(None)
   c = GridBagConstraints()
   c.gridx = 0
   c.gridy = 0
   c.weightx = 1.0
   c.fill = GridBagConstraints.HORIZONTAL
   c.anchor = GridBagConstraints.PAGE_START
   line = 0
   for question in self.test.getQuestions():
     c.gridy = line
     panel.add(question.getPanel().asJComponent(),c)
     line += 1
   scrollPanel = JScrollPane(panel)
   scrollPanel.setBorder(None)
   self.questionsContainer.setLayout(BorderLayout())
   self.questionsContainer.add(scrollPanel, BorderLayout.CENTER)
Пример #17
0
def getGridBagConstraints(game,node):
    c = GridBagConstraints()
    for str in node.getAttribute("constraints").split(","):
        a = str.split(":")
        if a[0]=="fill":
            c.fill = int(a[1])
        elif a[0]=="gridwidth":
             c.gridwidth = int(a[1])
        elif a[0]=="gridheight":
             c.gridheight = int(a[1])
        elif a[0]=="gridx":
            c.gridx = int(a[1])
        elif a[0]=="gridy":
            c.gridy = int(a[1])
        elif a[0]=="weightx":
            c.weightx = int(a[1])
        elif a[0]=="weighty":
            c.weighty = int(a[1])
        else:
            print a[0]+"was not found"
    return c
Пример #18
0
 def __init__(self, view, sys):
     JDialog.__init__(self, view,
                      jEdit.getProperty("jython.pathhandler.title"))
     self.sys = sys
     content = self.contentPane
     content.layout = BorderLayout()
     upperPanel = JPanel(BorderLayout())
     leftPanel = JPanel(BorderLayout(), border = \
      BorderFactory.createTitledBorder(jEdit.getProperty("jython.pathhandler.pathborder")))
     self.model = DefaultListModel()
     for s in sys.path:
         self.model.addElement(s)
     self.pathlist = JList(
         self.model, selectionMode=ListSelectionModel.SINGLE_SELECTION)
     leftPanel.add(JScrollPane(self.pathlist))
     rightPanel = JPanel(GridBagLayout())
     constraints = GridBagConstraints()
     constraints.insets = Insets(5, 5, 5, 5)
     constraints.gridy = GridBagConstraints.RELATIVE
     constraints.gridx = 0
     buttons = [("Plus.png", "New...", self.new), \
      ("ButtonProperties.png", "Edit...", self.edit),
      ("Minus.png", "Remove", self.remove), \
      ("ArrowU.png", "Move Up", self.up), \
      ("ArrowD.png", "Move down", self.down)]
     for (i, t, a) in buttons:
         rightPanel.add(JButton(icon = GUIUtilities.loadIcon(i), \
          toolTipText=t, actionPerformed=a), constraints)
     upperPanel.add(leftPanel, BorderLayout.CENTER)
     upperPanel.add(rightPanel, BorderLayout.EAST)
     content.add(upperPanel, BorderLayout.CENTER)
     lowerPanel = JPanel(FlowLayout(FlowLayout.RIGHT))
     self.saveAsk = JCheckBox(jEdit.getProperty("options.jython.saveJythonPathTitle"), \
      selected = jEdit.getBooleanProperty("options.jython.saveJythonPath"), actionPerformed = self.saveAsk)
     ok = JButton("Ok", actionPerformed=self.__ok)
     lowerPanel.add(self.saveAsk)
     lowerPanel.add(ok)
     self.rootPane.defaultButton = ok
     lowerPanel.add(JButton("Cancel", actionPerformed=self.__cancel))
     content.add(lowerPanel, BorderLayout.SOUTH)
Пример #19
0
def add(parent, child,
        gridx=0, gridy=0,
        anchor=GC.NORTHWEST, fill=GC.NONE,
        weightx=0.0, weighty=0.0,
        gridwidth=1):
  c = GC()
  c.gridx = gridx
  c.gridy = gridy
  c.anchor = anchor
  c.fill = fill
  c.weightx = weightx
  c.weighty = weighty
  c.gridwidth = gridwidth
  """
  # Same, more flexible, less verbose: BUT FAILS at parent, child args
  kv = locals() # dict of local variables including the function arguments
  c = GC()
  for key, value in kv.iteritems():
    setattr(c, key, value)
  """
  #
  parent.getLayout().setConstraints(child, c)
  parent.add(child)
def doall(locations, fileobs,filerun1,filerun2,stime,etime,imageDir='d:/temp',weights=None,filter_type="AVE",normalize=False):
    obs=HecDss.open(fileobs,True)
    obs.setTimeWindow(stime,etime)
    run1=HecDss.open(filerun1,True)
    run1.setTimeWindow(stime,etime)
    if filerun2 != None:
        run2=HecDss.open(filerun2,True)
        run2.setTimeWindow(stime,etime)
    else:
        run2=None
    rms1=0
    rms1_min,rms1_max=0,0
    rms2=0
    rms2_min,rms2_max=0,0
    rmsmap={}
    #run2=None
    sumwts=0
    average_interval=None;
    for l in locations:
        data1=get_matching(obs,'A=%s C=%s E=15MIN'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=IR-DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1HOUR'%(l,type))
        drun1=get_matching(run1,'B=%s C=%s'%(l,type))
        if run2 != None:
            drun2=get_matching(run2, 'B=%s C=%s'%(l,type))
        else:
            drun2=None
        avg_intvl="1DAY"
        if data1 != None:
            if average_interval != None:
                dobsd=TimeSeriesMath(data1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                dobsd=TimeSeriesMath(data1)
            if normalize:
                dobsd=dobsd.divide(TimeSeriesMath(data1).mean())
            dobsm=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            dobsm_max=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            dobsm_max.data.fullName=dobsm_max.data.fullName+"MAX"
            dobsm_min=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            dobsm_min.data.fullName=dobsm_min.data.fullName+"MIN"
            if normalize:
                dobsm=dobsm.divide(TimeSeriesMath(data1).mean())
        if drun1==None:
            continue;
        else:
            if average_interval != None:
                drun1d=TimeSeriesMath(drun1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                drun1d=TimeSeriesMath(drun1)
            if normalize:
                drun1d=drun1d.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                if average_interval != None:
                    drun2d=TimeSeriesMath(drun2).transformTimeSeries(average_interval, None, filter_type, 0)
                else:
                    drun2d=TimeSeriesMath(drun2)
                if normalize:
                    drun2d=drun2d.divide(TimeSeriesMath(drun2).mean())
            drun1m=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            drun1m_max=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            drun1m_min=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            if normalize:
                drun1m=drun1m.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                drun2m=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, filter_type, 0)
                drun2m_max=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MAX", 0)
                drun2m_min=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MIN", 0)
                if normalize:
                    drun2m=drun2m.divide(TimeSeriesMath(drun2).mean())
            else:
                drun2m=None
        if weights != None:
            sumwts=sumwts+weights[l]
            lrms1 = calculate_rms(drun1m.data, dobsm.data)*weights[l]
            lrms1_min=calculate_rms(drun1m_min.data,dobsm_min.data)*weights[l]
            lrms1_max=calculate_rms(drun1m_max.data,dobsm_max.data)*weights[l]
            rms1=rms1+lrms1
            rms1_min=rms1_min+lrms1_min
            rms1_max=rms1_max+lrms1_max
            lrms2 = calculate_rms(drun2m.data,dobsm.data)*weights[l]
            lrms2_min=calculate_rms(drun2m_min.data,dobsm_min.data)*weights[l]
            lrms2_max=calculate_rms(drun2m_max.data,dobsm_max.data)*weights[l]
            rmsmap[l] = lrms1,lrms2,lrms1_min,lrms2_min,lrms1_max,lrms2_max
            rms2=rms2+lrms2
            rms2_min=rms2_min+lrms2_min
            rms2_max=rms2_max+lrms2_max
        plotd = newPlot("Hist vs New Geom [%s]"%l)
        if data1 != None:
            plotd.addData(dobsd.data)
        plotd.addData(drun1d.data)
        if drun2 != None:
            plotd.addData(drun2d.data)
        plotd.showPlot()
        legend_label = plotd.getLegendLabel(drun1d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms1*100)/100.)+","+str(int(lrms1_min*100)/100.)+","+str(int(lrms1_max*100)/100.)+"]")
        legend_label = plotd.getLegendLabel(drun2d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms2*100)/100.)+","+str(int(lrms2_min*100)/100.)+","+str(int(lrms2_max*100)/100.)+"]")
        plotd.setVisible(False)
        xaxis=plotd.getViewport(0).getAxis("x1")
        vmin =xaxis.getViewMin()+261500. # hardwired to around july 1, 2008
        xaxis.setViewLimits(vmin,vmin+10000.)
        if data1 != None:
            pline = plotd.getCurve(dobsd.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
            g2dPanel = plotd.getPlotpanel()
            g2dPanel.revalidate();
            g2dPanel.paintGfx();
        plotm = newPlot("Hist vs New Geom Monthly [%s]"%l)
        plotm.setSize(1800,1200)
        if data1 != None:
            plotm.addData(dobsm.data)
           #plotm.addData(dobsm_max.data)
            #plotm.addData(dobsm_min.data)
        plotm.addData(drun1m.data)
        #plotm.addData(drun1m_max.data)
        #plotm.addData(drun1m_min.data)
        if drun2 != None:
            plotm.addData(drun2m.data)
            #plotm.addData(drun2m_max.data)
            #plotm.addData(drun2m_min.data)
        plotm.showPlot()
        if data1 != None:
            pline = plotm.getCurve(dobsm.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
        plotm.setVisible(False)
        if data1 != None:
            plots=do_regression_plots(dobsm,drun1m,drun2m)
            if plots != None:
                spanel = plots.getPlotpanel()
                removeToolbar(spanel)
        mpanel = plotm.getPlotpanel()
        removeToolbar(mpanel)
        dpanel = plotd.getPlotpanel()
        removeToolbar(dpanel)
        from javax.swing import JPanel,JFrame
        from java.awt import GridBagLayout, GridBagConstraints
        mainPanel = JPanel()
        mainPanel.setLayout(GridBagLayout())
        c=GridBagConstraints()
        c.fill=c.BOTH
        c.weightx,c.weighty=0.5,1
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        if data1 != None:
            if plots != None:
                pass
                #mainPanel.add(spanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        c.weightx,c.weighty=1,1
        mainPanel.add(mpanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,4,10,6
        mainPanel.add(dpanel,c)
        fr=JFrame()
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        fr.getContentPane().add(mainPanel)
        fr.setSize(1100,850);
        fr.show();
        mainPanel.setSize(1100,850);
        mainPanel.setBackground(Color.WHITE);
        #import time; time.sleep(5)
        saveToPNG(mainPanel,imageDir+l+".png")
    if weights != None:
        rms1=(rms1+rms1_min+rms1_max)/sumwts
        rms2=(rms2+rms2_min+rms2_max)/sumwts
        print 'RMS Run 1: %f'%rms1
        print 'RMS Run 2: %f'%rms2
        for loc in rmsmap.keys():
            print loc, rmsmap[loc] 
    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)
Пример #22
0
    def registerExtenderCallbacks(self, callbacks):

        # keep a reference to our callbacks object
        self._callbacks = callbacks

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Response Clusterer")

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

        # main split pane
        self._main_jtabedpane = JTabbedPane()

        # The split pane with the log and request/respponse details
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

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

        # List of log entries
        self._log_entries = []

        # 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())
        self._splitpane.setRightComponent(tabs)

        #Setup the options
        self._optionsJPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gbc = GridBagConstraints()
        self._optionsJPanel.setLayout(gridBagLayout)

        self.max_clusters = 500
        self.JLabel_max_clusters = JLabel("Maximum amount of clusters: ")
        gbc.gridy = 0
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_max_clusters, gbc)
        self.JTextField_max_clusters = JTextField(str(self.max_clusters), 5)
        self.JTextField_max_clusters.getDocument().addDocumentListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_max_clusters, gbc)
        callbacks.customizeUiComponent(self.JLabel_max_clusters)
        callbacks.customizeUiComponent(self.JTextField_max_clusters)

        self.similarity = 0.95
        self.JLabel_similarity = JLabel("Similarity (between 0 and 1)")
        gbc.gridy = 1
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_similarity, gbc)
        self.JTextField_similarity = JTextField(str(self.similarity), 5)
        self.JTextField_similarity.getDocument().addDocumentListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_similarity, gbc)
        callbacks.customizeUiComponent(self.JLabel_similarity)
        callbacks.customizeUiComponent(self.JTextField_similarity)

        self.use_quick_similar = False
        self.JLabel_use_quick_similar = JLabel(
            "Use set intersection of space splitted tokens for similarity (default: optimized difflib.SequenceMatcher.quick_ratio)"
        )
        gbc.gridy = 2
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_use_quick_similar, gbc)
        self.JCheckBox_use_quick_similar = JCheckBox("")
        self.JCheckBox_use_quick_similar.addActionListener(self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JCheckBox_use_quick_similar, gbc)
        callbacks.customizeUiComponent(self.JCheckBox_use_quick_similar)

        self.response_max_size = 10 * 1024  #10kb
        self.JLabel_response_max_size = JLabel("Response max size (bytes)")
        gbc.gridy = 3
        gbc.gridx = 0
        self._optionsJPanel.add(self.JLabel_response_max_size, gbc)
        self.JTextField_response_max_size = JTextField(
            str(self.response_max_size), 5)
        self.JTextField_response_max_size.getDocument().addDocumentListener(
            self)
        gbc.gridx = 1
        self._optionsJPanel.add(self.JTextField_response_max_size, gbc)
        callbacks.customizeUiComponent(self.JLabel_response_max_size)
        callbacks.customizeUiComponent(self.JTextField_response_max_size)

        self.uninteresting_mime_types = ('JPEG', 'CSS', 'GIF', 'script', 'GIF',
                                         'PNG', 'image')
        self.uninteresting_status_codes = ()
        self.uninteresting_url_file_extensions = ('js', 'css', 'zip', 'war',
                                                  'jar', 'doc', 'docx', 'xls',
                                                  'xlsx', 'pdf', 'exe', 'dll',
                                                  'png', 'jpeg', 'jpg', 'bmp',
                                                  'tif', 'tiff', 'gif', 'webp',
                                                  'm3u', 'mp4', 'm4a', 'ogg',
                                                  'aac', 'flac', 'mp3', 'wav',
                                                  'avi', 'mov', 'mpeg', 'wmv',
                                                  'swf', 'woff', 'woff2')

        about = "<html>"
        about += "Author: floyd, @floyd_ch, http://www.floyd.ch<br>"
        about += "modzero AG, http://www.modzero.ch<br>"
        about += "<br>"
        about += "<h3>Getting an overview of the tested website</h3>"
        about += "<p style=\"width:500px\">"
        about += "This plugin clusters all response bodies by similarity and shows a summary, one request/response per cluster. "
        about += 'Adjust similarity in the options if you get too few or too many entries in the "One member of each cluster" '
        about += "tab. The plugin will allow a tester to get an overview of the tested website's responses from all tools (scanner, proxy, etc.). "
        about += "As similarity comparison "
        about += "can use a lot of ressources, only small, in-scope responses that have interesting response codes, "
        about += "file extensions and mime types are processed. "
        about += "</p>"
        about += "</html>"
        self.JLabel_about = JLabel(about)
        self.JLabel_about.setLayout(GridBagLayout())
        self._aboutJPanel = JScrollPane(self.JLabel_about)

        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)

        # add the splitpane and options to the main jtabedpane
        self._main_jtabedpane.addTab("One member of each cluster", None,
                                     self._splitpane, None)
        self._main_jtabedpane.addTab("Options", None, self._optionsJPanel,
                                     None)
        self._main_jtabedpane.addTab("About & README", None, self._aboutJPanel,
                                     None)

        # clusters will grow up to self.max_clusters response bodies...
        self._clusters = set()
        self.Similarity = Similarity()

        # Now load the already stored
        with self._lock:
            log_entries_from_storage = self.load_project_setting("log_entries")
            if log_entries_from_storage:
                for toolFlag, req, resp, url in log_entries_from_storage:
                    try:
                        self.add_new_log_entry(toolFlag, req, resp, url)
                    except Exception as e:
                        print "Exception when deserializing a stored log entry", toolFlag, url
                        print e

        # Important: Do this at the very end (otherwise we could run into troubles locking up entire threads)
        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)
Пример #23
0
    def __init__(self):
        ''' Configuration Panel '''
#         pconfig = JPanel(GridBagLayout())
#         pconfig.setSize(Dimension(500,300))
        self.setLayout(GridBagLayout())
#         super(self,GridBagLayout())
        self.setSize(Dimension(500,300))
        ''' fila 1 '''
        label = JLabel('Configuration panel')
        c1 = GridBagConstraints()
        c1.fill = GridBagConstraints.HORIZONTAL
        c1.weightx = 0.5
        c1.gridwidth = 4
        c1.gridx = 0
        c1.gridy = 0
        self.add(label, c1)
        ''' fila 2 '''
        self.radioBtnOMC = JRadioButton('OpenModelica')
        c2 = GridBagConstraints()
        c2.fill = GridBagConstraints.HORIZONTAL
        c2.weightx = 0.5
        c2.gridx = 0
        c2.gridy = 1
        self.add(self.radioBtnOMC, c2)
        self.radioBtnJM = JRadioButton('JModelica')
        c3 = GridBagConstraints()
        c3.fill = GridBagConstraints.HORIZONTAL
        c3.weightx = 0.5
        c3.gridx = 1
        c3.gridy = 1
        self.add(self.radioBtnJM, c3)
        self.radioBtnDY = JRadioButton('Dymola')
        c4 = GridBagConstraints()
        c4.fill = GridBagConstraints.HORIZONTAL
        c4.weightx = 0.5
        c4.gridx = 2
        c4.gridy = 1
        self.add(self.radioBtnDY, c4)
        rbBtnGroup = ButtonGroup()
        rbBtnGroup.add(self.radioBtnOMC)
        rbBtnGroup.add(self.radioBtnJM)
        rbBtnGroup.add(self.radioBtnDY)
        ''' fila 2 '''
        label = JLabel('Start time')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 2
        self.add(label, c)
        self.txtstart= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 2
        self.add(self.txtstart, c)
        label = JLabel('Stop time')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 2
        self.add(label, c)
        self.txtstop= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 2
        self.add(self.txtstop, c)
        ''' fila 3 '''
        label = JLabel('Solver')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 3
        self.add(label, c)
        self.cbsolver= JComboBox(['dassl','rkfix2'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 3
        self.add(self.cbsolver, c)
        label = JLabel('Algorithm (JM)')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 3
        self.add(label, c)
        self.cbalgorithm= JComboBox(['AssimuloAlg'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 3
        self.add(self.cbalgorithm, c)
        ''' fila 4 '''
        label = JLabel('Interval')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 4
        self.add(label, c)
        self.txtinterval= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 4
        self.add(self.txtinterval, c)
        ''' fila 5 '''
        label = JLabel('Tolerance')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 5
        self.add(label, c)
        self.txttolerance= JTextField('0')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 5
        self.add(self.txttolerance, c)
        ''' fila 6 '''
        label = JLabel('Output format')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 0
        c.gridy = 6
        self.add(label, c)
        self.cboutformat= JComboBox(['.mat','.h5','.csv'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 1
        c.gridy = 6
        self.add(self.cboutformat, c)
        label = JLabel('Initialize (JM)')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 2
        c.gridy = 6
        self.add(label, c)
        self.cbinitialize= JComboBox(['True','False'])
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridx = 3
        c.gridy = 6
        self.add(self.cbinitialize, c)
        ''' fila 7 '''
        bSaveCfg= JButton('Save Configuration', actionPerformed= self.saveConfiguration)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 0
        c.gridy = 7
        self.add(bSaveCfg, c)
        self.bSimulation= JButton('Load Configuration', actionPerformed= self.loadConfiguration)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 2
        c.gridy = 7
        self.add(self.bSimulation, c)
        ''' fila 8 '''
        self.bSimulation= JButton('Simulate', actionPerformed= self.startSimlation)
        self.bSimulation.enabled= 0
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 8
        self.add(self.bSimulation, c)
        ''' file 9 '''
        simProgress= JProgressBar(0, self.getWidth(), value=0, stringPainted=True)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 9
        self.add(simProgress, c)
        ''' fila 10 '''
        self.lblResult= JLabel('Simulation information')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 10
        self.add(self.lblResult, c) 
Пример #24
0
    def __init__(self):
        ''' Resources Panel '''
#         psimures= JPanel(GridBagLayout())
#         psimures.setSize(Dimension(500,300))
        self.setLayout(GridBagLayout())
#         super(self,GridBagLayout())
        self.setSize(Dimension(500,300))
        ''' fila 1 '''
        label = JLabel('Resources panel')
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 1
        c.gridwidth = 4
        c.gridx = 0
        c.gridy = 0
        self.add(label, c)
        ''' fila 2 '''
        self.dModelFile = []
        self.cbMoFile = JComboBox(self.dModelFile)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.75
        c.gridwidth = 3
        c.gridx = 0
        c.gridy = 1
        self.add(self.cbMoFile, c)
        bloadmodel= JButton('Load Model',actionPerformed=self.onOpenFile)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.25
#         c.gridwidth = 1
        c.gridx = 3
        c.gridy = 1
        self.add(bloadmodel, c)
        ''' fila 3 '''
        self.dLibFile = []
        self.cbMoLib = JComboBox(self.dLibFile)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.75
        c.gridwidth = 3
        c.gridx = 0
        c.gridy = 2
        self.add(self.cbMoLib, c)
        bloadlib= JButton('Load Library',actionPerformed=self.onOpenFile)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.25
#         c.gridwidth = 1
        c.gridx = 3
        c.gridy = 2
        self.add(bloadlib, c)
        ''' fila 4 '''
        self.dModel = []
        self.cbModel = JComboBox(self.dModel)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.75
        c.gridwidth = 3
        c.gridx = 0
        c.gridy = 3
        self.add(self.cbModel, c)
        bselectmodel= JButton('Select Model',actionPerformed=self.onOpenModel)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.25
#         c.gridwidth = 1
        c.gridx = 3
        c.gridy = 3
        self.add(bselectmodel, c)
        ''' fila 5 '''
        self.dOutPath = []
        self.cbOutDir = JComboBox(self.dOutPath)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.75
        c.gridwidth = 3
        c.gridx = 0
        c.gridy = 4
        self.add(self.cbOutDir, c)
        bloadoutpath= JButton('Output Path',actionPerformed=self.onOpenFolder)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.25
#         c.gridwidth = 1
        c.gridx = 3
        c.gridy = 4
        self.add(bloadoutpath, c)
        ''' fila 6 '''
        bsaveSource= JButton('Save Resources',actionPerformed=self.saveResources)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 0
        c.gridy = 5
        self.add(bsaveSource, c)
        bloadSource= JButton('Load Resources',actionPerformed=self.loadResources)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.weightx = 0.5
        c.gridwidth = 2
        c.gridx = 2
        c.gridy = 5
        self.add(bloadSource, c)
Пример #25
0
def makeRegistrationUI(original_images, original_calibration, coarse_affines, params, images, minC, maxC, cropped, cropped_imp):
  """
  Register cropped images either all to all or all to the first one,
  and print out a config file with the coarse affines,
  the ROI for cropping, and the refined affines post-crop.

  original_images: the original, raw images, with original dimensions.
  original_calibration: the calibration of the images as they are on disk.
  coarse_affines: list of AffineTransform3D, one per image, that specify the translation between images
                  as manually set using the makeTranslationUI.
  params: dictionary with parameters for registering the given cropped images.
          This includes a calibration that is likely [1.0, 1.0, 1.0] as the cropped images
          are expected to have been scaled to isotropy.
  images: the list of near-original images but scaled (by calibration) to isotropy.
          (These are really views of the original images, using nearest neighbor interpolation
           to scale them to isotropy.)
  minC, maxC: the minimum and maximum coordinates of a ROI with which the cropped images were made.
  cropped: the list of images that have been scaled to isotropy, translated and cropped by the ROI.
           (These are really interval views of the images, the latter using nearest neighbor interpolation.)
  cropped_imp: the ImagePlus holding the virtual stack of cropped image views.

  The computed registration will merge the scaling to isotropy + first transform (a translation)
   + roi cropping translation + the params["modelclass"] registration transform, to read directly
   from the original images using a nearest interpolation, for best performance (piling two nearest
   interpolations over one another would result in very slow access to pixel data).
  """

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  calibration = params["calibration"]
  params["cal X"] = calibration[0]
  params["cal Y"] = calibration[1]
  params["cal Z"] = calibration[2]

  # Add a label and a text field for every parameter, with titles for every block
  strings = [["Calibration",
              "cal X", "cal Y", "cal Z"],
             ["Difference of Gaussian",
              "minPeakValue", "sigmaSmaller", "sigmaLarger"],
             ["Feature extraction",
              "radius", "min_angle", "max_per_peak",
              "angle_epsilon", "len_epsilon_sq",
              "pointmatches_nearby", "pointmatches_search_radius"],
             ["RANSAC parameters for the model",
              "maxEpsilon", "minInlierRatio", "minNumInliers",
              "n_iterations", "maxTrust"],
             ["All to all registration",
              "maxAllowedError", "maxPlateauwidth", "maxIterations", "damp"]]
  # Insert all as fields, with values populated from the params dictionary
  # and updating dynamically the params dictionary
  params = dict(params) # copy, will be updated
  insertFloatFields(panel, gb, gc, params, strings)

  # Identity transforms prior to registration
  affines = [affine3D([1, 0, 0, 0,
                       0, 1, 0, 0,
                       0, 0, 1, 0]) for img in cropped]
  
  def run():
    exe = newFixedThreadPool(min(len(cropped), numCPUs()))
    try:
      # Dummy for in-RAM reading of isotropic images
      img_filenames = [str(i) for i in xrange(len(cropped))]
      loader = InRAMLoader(dict(zip(img_filenames, cropped)))
      getCalibration = params.get("getCalibration", None)
      if not getCalibration:
        getCalibration = lambda img: [1.0] * cropped[0].numDimensions()
      csv_dir = params["csv_dir"]
      modelclass = params["modelclass"]
      # Matrices describing the registration on the basis of the cropped images
      matrices = computeOptimizedTransforms(img_filenames, loader, getCalibration,
                                            csv_dir, exe, modelclass, params)
      # Store outside, so they can be e.g. printed, and used beyond here
      for matrix, affine in zip(matrices, affines):
        affine.set(*matrix)

      # Combine the transforms: scaling (by calibration)
      #                         + the coarse registration (i.e. manual translations)
      #                         + the translation introduced by the ROI cropping
      #                         + the affine matrices computed above over the cropped images.
      coarse_matrices = []
      for coarse_affine in coarse_affines:
        matrix = zeros(12, 'd')
        coarse_affine.toArray(matrix)
        coarse_matrices.append(matrix)

      # NOTE: both coarse_matrices and matrices are from the camera X to camera 0. No need to invert them.
      # NOTE: uses identity calibration because the coarse_matrices already include the calibration scaling to isotropy
      transforms = mergeTransforms([1.0, 1.0, 1.0], coarse_matrices, [minC, maxC], matrices, invert2=False)

      print "calibration:", [1.0, 1.0, 1.0]
      print "cmTransforms:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in coarse_matrices)
      print "ROI", [minC, maxC]
      print "fineTransformsPostROICrop:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in matrices)
      print "invert2:", False
      
      # Show registered images
      registered = [transformedView(img, transform, interval=cropped[0])
                    for img, transform in izip(original_images, transforms)]
      registered_imp = showAsStack(registered, title="Registered with %s" % params["modelclass"].getSimpleName())
      registered_imp.setDisplayRange(cropped_imp.getDisplayRangeMin(), cropped_imp.getDisplayRangeMax())

      """
      # TEST: same as above, but without merging the transforms. WORKS, same result
      # Copy into ArrayImg, otherwise they are rather slow to browse
      def copy(img1, affine):
        # Copy in two steps. Otherwise the nearest neighbor interpolation on top of another
        # nearest neighbor interpolation takes a huge amount of time
        dimensions = Intervals.dimensionsAsLongArray(img1)
        aimg1 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img1, aimg1.factory()), aimg1)
        img2 = transformedView(aimg1, affine)
        aimg2 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img2, aimg2.factory()), aimg2)
        return aimg2
      futures = [exe.submit(Task(copy, img, affine)) for img, affine in izip(cropped, affines)]
      aimgs = [f.get() for f in futures]
      showAsStack(aimgs, title="DEBUG Registered with %s" % params["modelclass"].getSimpleName())
      """
    except:
      print sys.exc_info()
    finally:
      exe.shutdown()
      SwingUtilities.invokeLater(lambda: run_button.setEnabled(True))

  def launchRun(event):
    # Runs on the event dispatch thread
    run_button.setEnabled(False) # will be re-enabled at the end of run()
    # Fork:
    Thread(run).start()


  def printAffines(event):
    for i, affine in enumerate(affines):
      matrix = zeros(12, 'd')
      affine.toArray(matrix)
      msg = "# Refined post-crop affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)

  def prepareDeconvolutionScriptUI(event):
    """
    # DEBUG generateDeconvolutionScriptUI: generate params as a loadable serialized file
    with open("/tmp/parameters.pickle", 'w') as f:
      import pickle
      def asArrays(affines):
        arrays = []
        for affine in affines:
          matrix = zeros(12, 'd')
          affine.toArray(matrix)
          arrays.append(matrix)
        return arrays
        
      pickle.dump([params["srcDir"], params["tgtDir"], calibration,
                   asArrays(coarse_affines), [minC, maxC], asArrays(affines)], f)
    """
    generateDeconvolutionScriptUI(params["srcDir"], params["tgtDir"], calibration,
                                  coarse_affines, [minC, maxC], affines)
  
  # Buttons
  panel_buttons = JPanel()
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(panel_buttons, gc)
  panel.add(panel_buttons)
  
  run_button = JButton("Run")
  run_button.addActionListener(launchRun)
  gb.setConstraints(run_button, gc)
  panel_buttons.add(run_button)
  
  print_button = JButton("Print affines")
  print_button.addActionListener(printAffines)
  panel_buttons.add(print_button)

  prepare_button = JButton("Prepare deconvolution script")
  prepare_button.addActionListener(prepareDeconvolutionScriptUI)
  panel_buttons.add(prepare_button)

  frame = JFrame("Registration")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl())
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
Пример #26
0
def makeTranslationUI(affines, imp, show=True, print_button_text="Print transforms"):
  """
  A GUI to control the translation components of a list of AffineTransform3D instances.
  When updated, the ImagePlus is refreshed.

  affines: a list (will be read multiple times) of one affine transform per image.
  imp: the ImagePlus that hosts the virtual stack with the transformed images.
  show: defaults to True, whether to make the GUI visible.
  print_button_text: whatever you want the print button to read like, defaults to "Print transforms".
   
  Returns the JFrame, the main JPanel and the lower JButton panel.
  """
  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()
  gc.anchor = GBC.WEST
  gc.fill = GBC.NONE

  # Column labels
  gc.gridy = 0
  for i, title in enumerate(["Camera", "translation X", "translation Y", "translation Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  gc.anchor = GBC.WEST
  listeners = []
  
  # One row per affine to control: skip the first
  for i, affine in enumerate(affines[1:]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel("CM0%i: " % (i + 1))
    gb.setConstraints(label, gc)
    panel.add(label)
    # One JTextField per dimension
    for dimension, translation in enumerate(affine.getTranslation()):
      tf = JTextField(str(translation), 10)
      listener = MatrixTextFieldListener(affine, dimension, tf, imp)
      listeners.append(listener)
      imp.addImageListener(listener) # to disable the JTextField when closed
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)
      gc.gridx += 1
      gb.setConstraints(tf, gc)
      panel.add(tf)

  # Documentation for the user
  help_lines = ["Type a number and push enter,",
                "or use the scroll wheel."]
  gc.gridx = 0
  gc.gridwidth = 4
  for line in help_lines:
    gc.gridy += 1
    help = JLabel(line)
    gb.setConstraints(help, gc)
    panel.add(help)

  # Buttons
  printButton = JButton(print_button_text)
  
  def printTransforms(event):
    for i, aff in enumerate(affines): # print all, including the first
      matrix = zeros(12, 'd')
      aff.toArray(matrix)
      msg = "# Coarse affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)
      
  
  printButton.addActionListener(printTransforms)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  button_panel = JPanel()
  button_panel.add(printButton)
  gb.setConstraints(button_panel, gc)
  panel.add(button_panel)

  frame = JFrame("Translation control")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl(destroyables=listeners))
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(show)

  return frame, panel, button_panel
Пример #27
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Session Authentication Tool")
        self.out = callbacks.getStdout()

        # definition of suite tab
        self.tab = JPanel(GridBagLayout())
        self.tabledata = MappingTableModel(callbacks)
        self.table = JTable(self.tabledata)
        #self.table.getColumnModel().getColumn(0).setPreferredWidth(50);
        #self.table.getColumnModel().getColumn(1).setPreferredWidth(100);
        self.tablecont = JScrollPane(self.table)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.anchor = GridBagConstraints.FIRST_LINE_START
        c.gridx = 0
        c.gridy = 0
        c.gridheight = 6
        c.weightx = 0.3
        c.weighty = 0.5
        self.tab.add(self.tablecont, c)

        c = GridBagConstraints()
        c.weightx = 0.1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        c.gridx = 1

        c.gridy = 0
        label_id = JLabel("Identifier:")
        self.tab.add(label_id, c)
        self.input_id = JTextField(20)
        self.input_id.setToolTipText("Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name.")
        c.gridy = 1
        self.tab.add(self.input_id, c)

        c.gridy = 2
        label_content = JLabel("Content:")
        self.tab.add(label_content, c)
        self.input_content = JTextField(20, actionPerformed=self.btn_add_id)
        self.input_content.setToolTipText("Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user.")
        c.gridy = 3
        self.tab.add(self.input_content, c)

        self.btn_add = JButton("Add/Edit Identity", actionPerformed=self.btn_add_id)
        c.gridy = 4
        self.tab.add(self.btn_add, c)

        self.btn_del = JButton("Delete Identity", actionPerformed=self.btn_del_id)
        c.gridy = 5
        self.tab.add(self.btn_del, c)

        callbacks.customizeUiComponent(self.tab)
        callbacks.customizeUiComponent(self.table)
        callbacks.customizeUiComponent(self.tablecont)
        callbacks.customizeUiComponent(self.btn_add)
        callbacks.customizeUiComponent(self.btn_del)
        callbacks.customizeUiComponent(label_id)
        callbacks.customizeUiComponent(self.input_id)
        callbacks.addSuiteTab(self)
        callbacks.registerScannerCheck(self)
        callbacks.registerIntruderPayloadGeneratorFactory(self)
        callbacks.registerContextMenuFactory(self)
    def registerExtenderCallbacks(self, callbacks):

        endianVal = 0

        def generateTextBox(defaultTxt, editable):
            sample = JTextArea(5, 20)
            scrollPane1 = JScrollPane(sample)
            sample.setBounds(0, 0, 400, 400)
            sample.setEditable(editable)
            sample.setLineWrap(True)
            sample.setWrapStyleWord(True)
            sample.setBorder(BorderFactory.createLineBorder(Color.BLACK))
            sample.setText(defaultTxt)

            return sample

        def decodeData(event):

            #Get Base64 token
            full_str = base64.b64decode(self._left_tb1.getText())

            sha_mac = full_str[44:64].encode('hex')
            inflate_data = full_str[76:]
            data = zlib.decompress(inflate_data)

            user_length = data[20]
            loc = 21
            tokenDetails = "User name :" + data[
                loc:loc + int(user_length.encode('hex'), 16)].replace(
                    "\x00", "") + "\n"
            loc = loc + int(user_length.encode('hex'), 16)
            lang_length = data[loc]
            loc = loc + 1

            tokenDetails += "Lang Code :" + data[
                loc:loc + int(lang_length.encode('hex'), 16)].replace(
                    "\x00", "") + "\n"
            tmp1.setText(data[loc:loc +
                              int(lang_length.encode('hex'), 16)].replace(
                                  "\x00", ""))
            loc = loc + int(lang_length.encode('hex'), 16)
            node_length = data[loc]
            loc = loc + 1

            tokenDetails += "Node name :" + data[
                loc:loc + int(node_length.encode('hex'), 16)].replace(
                    "\x00", "") + "\n"
            tmp2.setText(data[loc:loc +
                              int(node_length.encode('hex'), 16)].replace(
                                  "\x00", ""))
            loc = loc + int(node_length.encode('hex'), 16)
            time_length = data[loc]
            loc = loc + 1

            tokenDetails += "Creation time :" + data[
                loc:loc + int(time_length.encode('hex'), 16)].replace(
                    "\x00", "")

            tmp = data[loc:loc + int(time_length.encode('hex'), 16)].replace(
                "\x00", "")
            datestamp = tmp[:len(tmp) - 7]
            tmp3.setText(datestamp)
            # Determine if it's little or big endian
            if (data[4:8].encode('hex') == '04030201'):
                endianVal = 0
            else:
                endianVal = 1

            tmp4.setText(str(endianVal))
            hashcatFormat = sha_mac + ":" + data.encode("hex")

            left_tb2.setText(tokenDetails)
            left_tb3.setText(hashcatFormat)

        def make_field(part, size):
            part = chr(len(part) + size) + part
            return part

        def generateToken(event):

            newtoken = ""

            endianVal = int(tmp4.getText())

            if endianVal == 1:
                username = right_tb2.getText().encode('utf_16_be')
                nodepw = right_tb1.getText().encode('utf_16_le')
                lang = tmp1.getText().encode('utf_16_be')
                nodename = tmp2.getText().encode('utf_16_be')
                datestamp = (tmp3.getText() + '.164266').encode('utf_16_be')
                token_ver = "8.10".encode('utf_16_be')
                unknown_field = "N".encode('utf_16_be')

                uncompressed_data = '\x01\x02\x03\x04\x00\x01\x00\x00\x00\x00\x02\xbc\x00\x00\x00\x00' + make_field(
                    username, 0) + make_field(lang, 0) + make_field(
                        nodename, 0) + make_field(datestamp, 0) + '\x00'
                uncompressed_field = '\x00\x00\x00' + make_field(
                    uncompressed_data, 4)

                inflate_data = zlib.compress(uncompressed_field)

                sha1_mac = hashlib.sha1(uncompressed_field + nodepw).digest()

                uncompressed_length = chr(len(uncompressed_field))
                static_headers1 = '\x01\x02\x03\x04\x00\x01\x00\x00\x00\x00\x02\xbc\x00\x00\x00\x00\x00\x00\x00\x2c\x00\x04\x53\x68\x64\x72\x02' + unknown_field + uncompressed_length + '\x08' + token_ver + '\x14'
                static_headers2 = '\x00\x05\x53\x64\x61\x74\x61'
                body = '\x00\x00\x00' + make_field(
                    static_headers2 + make_field(inflate_data, 0), 4)
                token = '\x00\x00\x00' + make_field(
                    static_headers1 + sha1_mac + body, 4)

                newtoken = base64.b64encode(token)

            elif endianVal == 0:
                username = right_tb2.getText().encode('utf_16_le')
                nodepw = right_tb1.getText().encode('utf_16_le')
                lang = tmp1.getText().encode('utf_16_le')
                nodename = tmp2.getText().encode('utf_16_le')
                datestamp = (tmp3.getText() + '.999543').encode('utf_16_le')
                token_ver = "8.10".encode('utf_16_le')
                unknown_field = "N".encode('utf_16_le')

                uncompressed_data = '\x00\x00\x00\x04\x03\x02\x01\x01\x00\x00\x00\xbc\x02\x00\x00\x00\x00\x00\x00' + make_field(
                    username, 0) + make_field(lang, 0) + make_field(
                        nodename, 0) + make_field(datestamp, 0) + '\x00'
                uncompressed_field = make_field(uncompressed_data, 1)

                inflate_data = zlib.compress(uncompressed_field)

                sha1_mac = hashlib.sha1(uncompressed_field + nodepw).digest()

                uncompressed_length = chr(len(uncompressed_field))

                static_headers1 = '\x00\x00\x00\x04\x03\x02\x01\x01\x00\x00\x00\xbc\x02\x00\x00\x00\x00\x00\x00\x2c\x00\x00\x00\x04\x00\x53\x68\x64\x72\x02' + unknown_field + uncompressed_length + '\x08' + token_ver + '\x14'
                static_headers2 = '\x00\x00\x00\x05\x00\x53\x64\x61\x74\x61'
                body = make_field(
                    static_headers2 + make_field(inflate_data, 0), 1)
                token = make_field(static_headers1 + sha1_mac + body, 1)

                newtoken = base64.b64encode(token)

            right_tb3.setText("PS_TOKEN=" + newtoken + ";")

        # keep a reference to our callbacks object
        self._callbacks = callbacks

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("PeopleSoft PSToken Processor")

        # main split pane
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._splitpane.setResizeWeight(0.5)

        c = GridBagConstraints()
        c.weightx = 1
        c.weighty = 1

        c.anchor = GridBagConstraints.NORTHWEST

        #Temp variables

        tmp1 = JLabel("tmp")
        tmp2 = JLabel("tmp")
        tmp3 = JLabel("tmp")
        tmp4 = JLabel("tmp")

        # add left panel
        panel1 = JPanel(GridBagLayout())
        header1 = JLabel("EXTRACTION")
        header1.setFont(Font("Myriad Pro", Font.BOLD, 24))

        left_t1 = JLabel("PS_TOKEN Cookie")
        left_t2 = JLabel("Token Details")
        left_t3 = JLabel("Token Hash + Salt (Hashcat Format)")
        left_t4 = JLabel(
            "Save this into a .hash file and run the following Hashcat command: hashcat -m 13500 <hashfile> <dictionary file>"
        )

        self._left_tb1 = generateTextBox("Your PS_TOKEN value here", True)
        left_tb2 = generateTextBox("Token Details here", False)
        left_tb3 = generateTextBox("Hashcat format here", False)

        btnDecode = JButton("Decode", actionPerformed=decodeData)
        btnGenerate = JButton("Generate", actionPerformed=generateToken)
        #add right panel
        panel2 = JPanel(GridBagLayout())
        header2 = JLabel("GENERATION")
        header2.setFont(Font("Myriad Pro", Font.BOLD, 24))

        right_t1 = JLabel("Node password")
        right_t2 = JLabel("New username")
        right_t3 = JLabel("New Base64 PS_TOKEN")
        right_t4 = JLabel(
            "Match & Replace rule to modify PS_TOKEN (Type: Request Header, enable regex)"
        )
        right_t5 = JLabel("Match rule: PS_TOKEN=[A-Za-z0-9\/\+]*;")
        right_t6 = JLabel("Replace: PS_TOKEN=<new generated PS_TOKEN>;")

        right_tb1 = generateTextBox("Password here", True)
        right_tb2 = generateTextBox("PSADMIN", True)
        right_tb3 = generateTextBox("Your new token here", False)

        panel1.add(header1, c)
        panel2.add(header2, c)

        c.gridx = 0
        c.gridy = 1
        panel1.add(left_t1, c)
        panel2.add(right_t1, c)
        c.gridy += 1
        panel1.add(self._left_tb1, c)
        panel2.add(right_tb1, c)

        c.gridy += 1
        panel1.add(left_t2, c)
        panel2.add(right_t2, c)
        c.gridy += 1
        panel1.add(left_tb2, c)
        panel2.add(right_tb2, c)

        c.gridy += 1
        panel1.add(left_t3, c)
        panel2.add(right_t3, c)
        c.gridy += 1
        panel1.add(left_t4, c)
        panel2.add(right_t4, c)
        c.gridy += 1
        panel1.add(left_tb3, c)
        panel2.add(right_t5, c)
        c.gridy += 1
        panel2.add(right_t6, c)
        c.gridy += 1
        panel2.add(right_tb3, c)
        c.gridy += 1
        panel1.add(btnDecode, c)
        panel2.add(btnGenerate, c)

        self._splitpane.setLeftComponent(panel1)
        self._splitpane.setRightComponent(panel2)

        # customize our UI components
        callbacks.customizeUiComponent(self._splitpane)
        #callbacks.customizeUiComponent(panel1)
        #callbacks.customizeUiComponent(scrollPane)

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

        #add option to do right-click
        callbacks.registerContextMenuFactory(self)

        return
Пример #29
0
  def getArguments(self):
    """
    This function brings up a window to retreive any required arguments.  It uses a window with fields for each argument, filled with any arguments already given.
    While this window is visible the program will wait, once it is no longer visible all the arguments will be filled with the entries in the fields.
    """

    class LocationAction(AbstractAction):
      """
      Action to set the text of a text field to a folder or directory.
      """
      def __init__(self, field):
        AbstractAction.__init__(self, "...")
        self.field = field

      def actionPerformed(self, event):
        fileChooser = JFileChooser()
        fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
          self.field.text = fileChooser.selectedFile.absolutePath
    
    class HelpAction(AbstractAction):
      """
      Displays a help page in a web browser.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Help")

      def actionPerformed(self, event):
        browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
        osName = System.getProperty("os.name")
        helpHTML = ClassLoader.getSystemResource("help.html").toString()
        if osName.find("Mac OS") == 0:
          Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
        elif osName.find("Windows") == 0:
          Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
        else:
          browser = None
          for b in browsers:
            if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
              browser = b
              Runtime.getRuntime().exec([browser, helpHTML])

    class OKAction(AbstractAction):
      """
      Action for starting the pipeline.  This action will simply make the window invisible.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Ok")

      def actionPerformed(self, event):
        frame.setVisible(False)

    class CancelAction(AbstractAction):
      """
      Action for canceling the pipeline.  Exits the program.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Cancel")

      def actionPerformed(self, event):
        sys.exit(0)

    frame = JFrame("Neofelis")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    constraints = GridBagConstraints()
    contentPane = JPanel(GridBagLayout())
    frame.setContentPane(contentPane)
    blastField = JTextField(self.blastLocation)
    genemarkField = JTextField(self.genemarkLocation)
    transtermField = JTextField(self.transtermLocation)
    tRNAscanField = JTextField(self.tRNAscanLocation)
    databaseLocationField = JTextField(os.path.split(self.database)[0])
    databaseField = JTextField(os.path.split(self.database)[1])
    matrixField = JTextField(str(self.matrix))
    eValueField = JTextField(str(self.eValue))
    minLengthField = JTextField(str(self.minLength))
    scaffoldingDistanceField = JTextField(str(self.scaffoldingDistance))
    promoterScoreField = JTextField(str(self.promoterScoreCutoff))
    queryField = JTextField(self.sources[0])

    constraints.gridx = 0
    constraints.gridy = 0
    constraints.gridwidth = 1
    constraints.gridheight = 1
    constraints.fill = GridBagConstraints.HORIZONTAL
    constraints.weightx = 0
    constraints.weighty = 0
    contentPane.add(JLabel("Blast Location"), constraints)
    constraints.gridy = 1
    contentPane.add(JLabel("Genemark Location"), constraints)
    constraints.gridy = 2
    contentPane.add(JLabel("Transterm Location"), constraints)
    constraints.gridy = 3
    contentPane.add(JLabel("tRNAscan Location"), constraints)
    constraints.gridy = 4
    contentPane.add(JLabel("Databases Location"), constraints)
    constraints.gridy = 5
    contentPane.add(JLabel("Database"), constraints)
    constraints.gridy = 6
    contentPane.add(JLabel("Matrix(Leave blank to use heuristic matrix)"), constraints)
    constraints.gridy = 7
    contentPane.add(JLabel("E Value"), constraints)
    constraints.gridy = 8
    contentPane.add(JLabel("Minimum Intergenic Length"), constraints)
    constraints.gridy = 9
    contentPane.add(JLabel("Scaffold Distance"), constraints)
    constraints.gridy = 10
    contentPane.add(JLabel("Promoter Score Cutoff"), constraints)
    constraints.gridy = 11
    contentPane.add(JLabel("Query"), constraints)
    constraints.gridx = 1
    constraints.gridy = 0
    constraints.weightx = 1
    contentPane.add(blastField, constraints)
    constraints.gridy = 1
    contentPane.add(genemarkField, constraints)
    constraints.gridy = 2
    contentPane.add(transtermField, constraints)
    constraints.gridy = 3
    contentPane.add(tRNAscanField, constraints)
    constraints.gridy = 4
    contentPane.add(databaseLocationField, constraints)
    constraints.gridy = 5
    contentPane.add(databaseField, constraints)
    constraints.gridy = 6
    contentPane.add(matrixField, constraints)
    constraints.gridy = 7
    contentPane.add(eValueField, constraints)
    constraints.gridy = 8
    contentPane.add(minLengthField, constraints)
    constraints.gridy = 9
    contentPane.add(scaffoldingDistanceField, constraints)
    constraints.gridy = 10
    contentPane.add(promoterScoreField, constraints)
    constraints.gridy = 11
    contentPane.add(queryField, constraints)
    constraints.gridx = 2
    constraints.gridy = 0
    constraints.weightx = 0
    constraints.fill = GridBagConstraints.NONE
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(LocationAction(blastField)), constraints)
    constraints.gridy = 1
    contentPane.add(JButton(LocationAction(genemarkField)), constraints)
    constraints.gridy = 2
    contentPane.add(JButton(LocationAction(transtermField)), constraints)
    constraints.gridy = 3
    contentPane.add(JButton(LocationAction(tRNAscanField)), constraints)
    constraints.gridy = 4
    contentPane.add(JButton(LocationAction(databaseLocationField)), constraints)
    constraints.gridy = 11
    contentPane.add(JButton(LocationAction(queryField)), constraints)

    constraints.gridx = 0
    constraints.gridy = 12
    constraints.anchor = GridBagConstraints.LINE_START
    contentPane.add(JButton(HelpAction()), constraints)
    constraints.gridx = 1
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(OKAction()), constraints)
    constraints.gridx = 2
    contentPane.add(JButton(CancelAction()), constraints)

    frame.pack()
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)

    while frame.isVisible():
      pass

    self.blastLocation = blastField.getText()
    self.genemarkLocation = genemarkField.getText()
    self.transtermLocation = transtermField.getText()
    self.database = databaseLocationField.getText() + "/" + databaseField.getText()
    self.matrix = matrixField.getText()
    self.eValue = float(eValueField.getText())
    self.minLength = int(minLengthField.getText())
    self.scaffoldingDistance = int(scaffoldingDistanceField.getText())
    self.promoterScoreCutoff = float(promoterScoreField.getText())
    self.sources = [queryField.getText()]
    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))
Пример #31
0
    def __init__(self, extender=None, *rows):
        self.extender = extender

        self.table = table = JTable(ParameterProcessingRulesTableModel(*rows))
        table.setPreferredScrollableViewportSize(Dimension(500, 70))
        table.setRowSorter(TableRowSorter(table.getModel()))
        table.setFillsViewportHeight(True)

        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [0, 0, 25, 0 ]
        gridBagLayout.rowHeights = [0, 0, 0, 0]
        gridBagLayout.columnWeights = [0.0, 1.0, 1.0, Double.MIN_VALUE]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, Double.MIN_VALUE]
        self.setLayout(gridBagLayout)

        addButton = JButton("Add")
        addButton.addActionListener(AddRemoveParameterListener(table))
        addButtonConstraints = GridBagConstraints()
        addButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        addButtonConstraints.insets = Insets(0, 0, 5, 5) 
        addButtonConstraints.gridx = 0
        addButtonConstraints.gridy = 0
        self.add(addButton, addButtonConstraints)

        removeButton = JButton("Remove")
        removeButton.addActionListener(AddRemoveParameterListener(table))
        removeButtonConstraints = GridBagConstraints()
        removeButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        removeButtonConstraints.insets = Insets(0, 0, 5, 5) 
        removeButtonConstraints.gridx = 0
        removeButtonConstraints.gridy = 1
        self.add(removeButton, removeButtonConstraints)

        upButton = JButton("Up")
        upButton.addActionListener(AddRemoveParameterListener(table))
        upButtonConstraints = GridBagConstraints()
        upButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        upButtonConstraints.insets = Insets(0, 0, 5, 5) 
        upButtonConstraints.gridx = 0
        upButtonConstraints.gridy = 2
        self.add(upButton, upButtonConstraints)

        downButton = JButton("Down")
        downButton.addActionListener(AddRemoveParameterListener(table))
        downButtonConstraints = GridBagConstraints()
        downButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        downButtonConstraints.anchor = GridBagConstraints.NORTH
        downButtonConstraints.insets = Insets(0, 0, 5, 5) 
        downButtonConstraints.gridx = 0
        downButtonConstraints.gridy = 3
        self.add(downButton, downButtonConstraints)

        scrollPane = JScrollPane(table)
        scrollPaneConstraints = GridBagConstraints()
        scrollPaneConstraints.gridwidth = 2
        scrollPaneConstraints.gridheight = 5
        scrollPaneConstraints.insets = Insets(0, 0, 5, 5)
        scrollPaneConstraints.anchor = GridBagConstraints.NORTHWEST 
        scrollPaneConstraints.gridx = 1
        scrollPaneConstraints.gridy = 0
        self.add(scrollPane, scrollPaneConstraints)

        self.initParameterColumn(table)
        self.initColumnSizes(table)
Пример #32
0
    def initComponents(self):
        self.setLayout(GridBagLayout())

        gbc = GridBagConstraints()
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridx = 0
        gbc.gridy = 0

        descriptionLabel = JLabel("FEA - Forensics Email Analysis")
        self.add(descriptionLabel, gbc)

        gbc.gridy = 1
        self.cbNSLookup = JCheckBox(
            "Perform DNS Lookup on email domains",
            actionPerformed=self.cbNSLookupActionPerformed)
        self.cbNSLookup.setSelected(True)
        self.add(self.cbNSLookup, gbc)

        # TODO: include option to browse for text file with list of emails to exclude from analysis

        numberThreadsLabel = JLabel(
            "Maximum number of threads for DNS Lookup task: ")
        gbc.gridy = 2
        self.add(numberThreadsLabel, gbc)

        self.numberThreadsSlider = JSlider(
            JSlider.HORIZONTAL,
            1,
            16,
            8,
            stateChanged=self.sliderActionPerformed)
        self.numberThreadsSlider.setMajorTickSpacing(1)
        self.numberThreadsSlider.setPaintLabels(True)
        self.numberThreadsSlider.setPaintTicks(True)
        self.numberThreadsSlider.setSnapToTicks(True)
        self.numberThreadsSlider.setToolTipText(
            "set maximum number of concurrent threads when performing DNS lookup on email domains"
        )

        gbc.gridy = 5
        gbc.gridwidth = 15
        gbc.gridheight = 1
        gbc.fill = GridBagConstraints.BOTH
        gbc.weightx = 0
        gbc.weighty = 0
        gbc.anchor = GridBagConstraints.NORTHWEST
        gbc.gridy = 3
        self.add(self.numberThreadsSlider, gbc)

        self.cbGenerateExcel = JCheckBox(
            "Generate Excel format report (more detailed)",
            actionPerformed=self.cbGenerateExcelActionPerformed)
        self.cbGenerateExcel.setSelected(True)
        gbc.gridy = 4
        self.add(self.cbGenerateExcel, gbc)

        self.cbGenerateCSV = JCheckBox(
            "Generate CSV format report (plaintext)",
            actionPerformed=self.cbGenerateCSVActionPerformed)
        self.cbGenerateCSV.setSelected(True)
        gbc.gridy = 5
        self.add(self.cbGenerateCSV, gbc)

        gbc.gridy = 6
        self.cbWayback = JCheckBox(
            "Perform Wayback Machine Lookup on email domains (WARNING: can be a slow process!)",
            actionPerformed=self.cbWaybackActionPerformed)
        self.cbWayback.setSelected(True)
        self.add(self.cbWayback, gbc)
Пример #33
0
    def __init__(self, callbacks, parent):
        # Initialze self stuff
        self._callbacks = callbacks
        self.config = {}
        self.ext_stats = {}
        self.url_reqs = []
        self.parse_files = False
        self.tab = JPanel(GridBagLayout())
        self.view_port_text = JTextArea("===SpyDir===")
        self.delim = JTextField(30)
        self.ext_white_list = JTextField(30)
        # I'm not sure if these fields are necessary still
        # why not just use Burp func to handle this?
        # leaving them in case I need it for the HTTP handler later
        # self.cookies = JTextField(30)
        # self.headers = JTextField(30)
        self.url = JTextField(30)
        self.parent_window = parent
        self.plugins = {}
        self.loaded_p_list = set()
        self.loaded_plugins = False
        self.config['Plugin Folder'] = None
        self.double_click = False
        self.source_input = ""
        self.print_stats = True
        self.curr_conf = JLabel()
        self.window = JFrame("Select plugins",
                             preferredSize=(200, 250),
                             windowClosing=self.p_close)
        self.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
        self.window.setVisible(False)
        self.path_vars = JTextField(30)


        # Initialize local stuff
        tab_constraints = GridBagConstraints()
        status_field = JScrollPane(self.view_port_text)

        # Configure view port
        self.view_port_text.setEditable(False)

        labels = self.build_ui()

        # Add things to rows
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        tab_constraints.gridx = 1
        tab_constraints.gridy = 0
        tab_constraints.fill = GridBagConstraints.HORIZONTAL
        self.tab.add(JButton(
            "Resize screen", actionPerformed=self.resize),
                     tab_constraints)
        tab_constraints.gridx = 0
        tab_constraints.gridy = 1
        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_START
        self.tab.add(labels, tab_constraints)

        tab_constraints.gridx = 1
        tab_constraints.gridy = 1
        tab_constraints.fill = GridBagConstraints.BOTH
        tab_constraints.weightx = 1.0
        tab_constraints.weighty = 1.0

        tab_constraints.anchor = GridBagConstraints.FIRST_LINE_END
        self.tab.add(status_field, tab_constraints)
        try:
            self._callbacks.customizeUiComponent(self.tab)
        except Exception:
            pass
Пример #34
0
    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()
        callbacks.setExtensionName("Session Authentication Tool")
        self.out = callbacks.getStdout()

        # definition of suite tab
        self.tab = JPanel(GridBagLayout())
        self.tabledata = MappingTableModel(callbacks)
        self.table = JTable(self.tabledata)
        #self.table.getColumnModel().getColumn(0).setPreferredWidth(50);
        #self.table.getColumnModel().getColumn(1).setPreferredWidth(100);
        self.tablecont = JScrollPane(self.table)
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.anchor = GridBagConstraints.FIRST_LINE_START
        c.gridx = 0
        c.gridy = 0
        c.gridheight = 6
        c.weightx = 0.3
        c.weighty = 0.5
        self.tab.add(self.tablecont, c)

        c = GridBagConstraints()
        c.weightx = 0.1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        c.gridx = 1

        c.gridy = 0
        label_id = JLabel("Identifier:")
        self.tab.add(label_id, c)
        self.input_id = JTextField(20)
        self.input_id.setToolTipText(
            "Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name."
        )
        c.gridy = 1
        self.tab.add(self.input_id, c)

        c.gridy = 2
        label_content = JLabel("Content:")
        self.tab.add(label_content, c)
        self.input_content = JTextField(20, actionPerformed=self.btn_add_id)
        self.input_content.setToolTipText(
            "Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user."
        )
        c.gridy = 3
        self.tab.add(self.input_content, c)

        self.btn_add = JButton("Add/Edit Identity",
                               actionPerformed=self.btn_add_id)
        c.gridy = 4
        self.tab.add(self.btn_add, c)

        self.btn_del = JButton("Delete Identity",
                               actionPerformed=self.btn_del_id)
        c.gridy = 5
        self.tab.add(self.btn_del, c)

        callbacks.customizeUiComponent(self.tab)
        callbacks.customizeUiComponent(self.table)
        callbacks.customizeUiComponent(self.tablecont)
        callbacks.customizeUiComponent(self.btn_add)
        callbacks.customizeUiComponent(self.btn_del)
        callbacks.customizeUiComponent(label_id)
        callbacks.customizeUiComponent(self.input_id)
        callbacks.addSuiteTab(self)
        callbacks.registerScannerCheck(self)
        callbacks.registerIntruderPayloadGeneratorFactory(self)
        callbacks.registerContextMenuFactory(self)
Пример #35
0
    def initComponents(self):

        #set the layout and add form components
        self.setLayout(GridBagLayout())

        gc = GridBagConstraints()

        gc.weightx = 1
        gc.weighty = 1

        # First Row
        gc.gridy = 0

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.fill = GridBagConstraints.NONE
        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.nameLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.nameField, gc)

        # Second Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.mobLabel, gc)

        gc.gridx = 1

        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.mobField, gc)

        #Third Row
        gc.gridy += 1

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.emailLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.emailField, gc)

        #Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.userNameLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.userNameField, gc)

        # Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.passwordLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.passwordField, gc)

        # Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.confirmPasswordLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.confirmPasswordField, gc)

        # Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.superPassLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.superPassField, gc)

        # Next Row

        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 2.0
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        self.add(self.addAdminBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Add Admin')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))
Пример #36
0
def makeCropUI(imp, images, tgtDir, panel=None, cropContinuationFn=None):
  """ imp: the ImagePlus to work on.
      images: the list of ImgLib2 images, one per frame, not original but already isotropic.
              (These are views that use a nearest neighbor interpolation using the calibration to scale to isotropy.)
      tgtDir: the target directory where e.g. CSV files will be stored, for ROI, features, pointmatches.
      panel: optional, a JPanel controlled by a GridBagLayout.
      cropContinuationFn: optional, a function to execute after cropping,
                          which is given as arguments the original images,
                          minC, maxC (both define a ROI), and the cropped images. """
  independent = None == panel
  if not panel:
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
    gb = GridBagLayout()
    gc = GBC()
  else:
    gb = panel.getLayout()
    # Constraints of the last component
    gc = gb.getConstraints(panel.getComponent(panel.getComponentCount() - 1))
    
    # Horizontal line to separate prior UI components from crop UI
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 4
    gc.anchor = GBC.WEST
    gc.fill = GBC.HORIZONTAL
    sep = JSeparator()
    sep.setMinimumSize(Dimension(200, 10))
    gb.setConstraints(sep, gc)
    panel.add(sep)

  # ROI UI header
  title = JLabel("ROI controls:")
  gc.gridy +=1
  gc.anchor = GBC.WEST
  gc.gridwidth = 4
  gb.setConstraints(title, gc)
  panel.add(title)

  # Column labels for the min and max coordinates
  gc.gridy += 1
  gc.gridwidth = 1
  for i, title in enumerate(["", "X", "Y", "Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  textfields = []
  rms = []

  # Load stored ROI if any
  roi_path = path = os.path.join(tgtDir, "crop-roi.csv")
  if os.path.exists(roi_path):
    with open(roi_path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
      reader.next() # header
      minC = map(int, reader.next()[1:])
      maxC = map(int, reader.next()[1:])
      # Place the ROI over the ImagePlus
      imp.setRoi(Roi(minC[0], minC[1], maxC[0] + 1 - minC[0], maxC[1] + 1 - minC[1]))
  else:
    # Use whole image dimensions
    minC = [0, 0, 0]
    maxC = [v -1 for v in Intervals.dimensionsAsLongArray(images[0])]

  # Text fields for the min and max coordinates
  for rowLabel, coords in izip(["min coords: ", "max coords: "],
                               [minC, maxC]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel(rowLabel)
    gb.setConstraints(label, gc)
    panel.add(label)
    for i in xrange(3):
      gc.gridx += 1
      tf = JTextField(str(coords[i]), 10)
      gb.setConstraints(tf, gc)
      panel.add(tf)
      textfields.append(tf)
      listener = RoiMaker(imp, textfields, len(textfields) -1)
      rms.append(listener)
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)

  # Listen to changes in the ROI of imp
  rfl = RoiFieldListener(imp, textfields)
  Roi.addRoiListener(rfl)
  # ... and enable cleanup
  ImagePlus.addImageListener(FieldDisabler(rfl, rms))

  # Functions for cropping images
  cropped = None
  cropped_imp = None

  def storeRoi(minC, maxC):
    if os.path.exists(roi_path):
      # Load ROI
      with open(path, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        reader.next() # header
        same = True
        for a, b in izip(minC + maxC, map(int, reader.next()[1:] + reader.next()[1:])):
          if a != b:
            same = False
            # Invalidate any CSV files for features and pointmatches: different cropping
            for filename in os.listdir(tgtDir):
              if filename.endswith("features.csv") or filename.endswith("pointmatches.csv"):
                os.remove(os.path.join(tgtDir, filename))
            break
        if same:
          return
    # Store the ROI as crop-roi.csv
    with open(roi_path, 'w') as csvfile:
      w = csv.writer(csvfile, delimiter=',', quotechar="\"", quoting=csv.QUOTE_NONNUMERIC)
      w.writerow(["coords", "x", "y", "z"])
      w.writerow(["min"] + map(int, minC))
      w.writerow(["max"] + map(int, maxC))
  
  def crop(event):
    global cropped, cropped_imp
    coords = [int(float(tf.getText())) for tf in textfields]
    minC = [max(0, c) for c in coords[0:3]]
    maxC = [min(d -1, c) for d, c in izip(Intervals.dimensionsAsLongArray(images[0]), coords[3:6])]
    storeRoi(minC, maxC)
    print "ROI min and max coordinates"
    print minC
    print maxC
    cropped = [Views.zeroMin(Views.interval(img, minC, maxC)) for img in images]
    cropped_imp = showAsStack(cropped, title="cropped")
    cropped_imp.setDisplayRange(imp.getDisplayRangeMin(), imp.getDisplayRangeMax())
    if cropContinuationFn:
      cropContinuationFn(images, minC, maxC, cropped, cropped_imp)

  # Buttons to create a ROI and to crop to ROI,
  # which when activated enables the fine registration buttons
  crop_button = JButton("Crop to ROI")
  crop_button.addActionListener(crop)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  gc.anchor = GBC.WEST
  buttons_panel = JPanel()
  buttons_panel.add(crop_button)
  gb.setConstraints(buttons_panel, gc)
  panel.add(buttons_panel)

  if independent:
    frame = JFrame("Crop by ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
    frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
    frame.setVisible(True)
  else:
    # Re-pack the JFrame
    parent = panel.getParent()
    while not isinstance(parent, JFrame) and parent is not None:
      parent = parent.getParent()

    if parent:
      frame = parent
      frame.pack()
      found = False
      for wl in frame.getWindowListeners():
        if isinstance(wl, CloseControl):
          wl.addDestroyables(rms + [rfl])
          found = True
          break
      if not found:
        frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
      frame.setVisible(True)

  return panel
Пример #37
0
    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable, in_scope_only
        global remove_csrf_headers, remove_csrf_params, change_method_to_post
        global change_ct_to_json, change_ct_to_plain, change_to_get

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        callbacks.registerProxyListener(self)

        callbacks.registerContextMenuFactory(
            SendToWhitelist(self.whitelist_text_area))

        print "Successfully loaded %s v%s by Mikhail Egorov @0ang3el" % (
            NAME, VERSION)
Пример #38
0
def generateDeconvolutionScriptUI(srcDir,
                                  tgtDir,
                                  calibration,
                                  preCropAffines,
                                  ROI,
                                  postCropAffines):
  """
  Open an UI to automatically generate a script to:
  1. Register the views of each time point TM folder, and deconvolve them.
  2. Register deconvolved time points to each other, for a range of consecutive time points.

  Will ask for the file path to the kernel file,
  and also for the range of time points to process,
  and for the deconvolution iterations for CM00-CM01, and CM02-CM03.
  """

  template = """
# AUTOMATICALLY GENERATED - %s

import sys, os
sys.path.append("%s")
from lib.isoview import deconvolveTimePoints
from mpicbg.models import RigidModel3D, TranslationModel3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL

# The folder with the sequence of TM\d+ folders, one per time point in the 4D series.
# Each folder should contain 4 KLB files, one per camera view of the IsoView microscope.
srcDir = "%s"

# A folder to save deconvolved images in, and CSV files describing features, point matches and transformations
targetDir = "%s"

# Path to the volume describing the point spread function (PSF)
kernelPath = "%s"

calibration = [%s] # An array with 3 floats (identity--all 1.0--because the coarse affines, that is,
                   # the camera transformations, already include the scaling to isotropy computed using the original calibration.

# The transformations of each timepoint onto the camera at index zero.
def cameraTransformations(dims0, dims1, dims2, dims3, calibration):
  return {
    0: [%s],
    1: [%s],
    2: [%s],
    3: [%s]
  }

# Deconvolution parameters
paramsDeconvolution = {
  "blockSizes": None, # None means the image size + kernel size. Otherwise specify like e.g. [[128, 128, 128]] for img in images]
  "CM_0_1_n_iterations": %i,
  "CM_2_3_n_iterations": %i,
}

# Joint dictionary of parameters
params = {}
params.update(paramsDeconvolution)

# A region of interest for each camera view, for cropping after registration but prior to deconvolution
roi = ([%s], # array of 3 integers, top-left coordinates
       [%s]) # array of 3 integers, bottom-right coordinates

# All 4 cameras relative to CM00
fineTransformsPostROICrop = \
   [[1, 0, 0, 0,
     0, 1, 0, 0,
     0, 0, 1, 0],
    [%s],
    [%s],
    [%s]]

deconvolveTimePoints(srcDir, targetDir, kernelPath, calibration,
                    cameraTransformations, fineTransformsPostROICrop,
                    params, roi, fine_fwd=True, subrange=range(%i, %i))
  """

  od = OpenDialog("Choose kernel file", srcDir)
  kernel_path = od.getPath()
  if not kernel_path:
    JOptionPane.showMessageDialog(None, "Can't proceed without a filepath to the kernel", "Alert", JOptionPane.ERROR_MESSAGE)
    return

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  msg = ["Edit parameters, then push the button",
         "to generate a script that, when run,",
         "will execute the deconvolution for each time point",
         "saving two 3D stacks per time point as ZIP files",
         "in the target directory under subfolder 'deconvolved'.",
         "Find the script in a new Script Editor window.",
         " "]
  gc.gridy = -1 # init
  for line in msg:
    label = JLabel(line)
    gc.anchor = GBC.WEST
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.gridheight = 1
    gb.setConstraints(label, gc)
    panel.add(label)

  strings = [["Deconvolution iterations",
              "CM_0_1_n_iterations", "CM_2_3_n_iterations"],
             ["Range",
              "First time point", "Last time point"]]
  params = {"CM_0_1_n_iterations": 5,
            "CM_2_3_n_iterations": 7,
            "First time point": 0,
            "Last time point": -1} # -1 means last
  insertFloatFields(panel, gb, gc, params, strings)

  def asString(affine):
    matrix = zeros(12, 'd')
    affine.toArray(matrix)
    return ",".join(imap(str, matrix))

  def generateScript(event):
    script = template % (str(datetime.now()),
                         filter(lambda path: path.endswith("IsoView-GCaMP"), sys.path)[-1],
                         srcDir,
                         tgtDir,
                         kernel_path,
                         ", ".join(imap(str, calibration)),
                         asString(preCropAffines[0]),
                         asString(preCropAffines[1]),
                         asString(preCropAffines[2]),
                         asString(preCropAffines[3]),
                         params["CM_0_1_n_iterations"],
                         params["CM_2_3_n_iterations"],
                         ", ".join(imap(str, ROI[0])),
                         ", ".join(imap(str, ROI[1])),
                         asString(postCropAffines[1]),
                         asString(postCropAffines[2]),
                         asString(postCropAffines[3]),
                         params["First time point"],
                         params["Last time point"])
    tab = None
    for frame in JFrame.getFrames():
      if str(frame).startswith("org.scijava.ui.swing.script.TextEditor["):
        try:
          tab = frame.newTab(script, "python")
          break
        except:
          print sys.exc_info()
    if not tab:
      try:
        now = datetime.now()
        with open(os.path.join(System.getProperty("java.io.tmpdir"),
                               "script-%i-%i-%i_%i:%i.py" % (now.year, now.month, now.day,
                                                             now.hour, now.minute)), 'w') as f:
          f.write(script)
      except:
        print sys.exc_info()
        print script
  

  gen = JButton("Generate script")
  gen.addActionListener(generateScript)
  gc.anchor = GBC.CENTER
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(gen, gc)
  panel.add(gen)

  frame = JFrame("Generate deconvolution script")
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
    def build_gui(self):
        component = JPanel(GridBagLayout())
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL

        c.gridwidth = 2

        # 1st line
        c.gridy = 0

        c.gridx = 0
        component.add(
            JLabel(
                'Don\'t forget to create a Session handling rule invoking this Burp extension under Project options > Sessions and to configure the tool and URL scopes.'
            ), c)

        c.gridwidth = 1

        # 2nd line
        c.gridy = 1

        c.gridx = 0
        component.add(JLabel(' '), c)

        # 3rd line
        c.gridy = 2

        c.gridx = 0
        component.add(
            JLabel(
                'Name of the anti-CSRF token, can also be a substring of the name of the anti-CSRF token:'
            ), c)

        self._csrf_name_contains_field = JTextField('csrf', 40)
        c.gridx = 1
        component.add(self._csrf_name_contains_field, c)

        # 4th line
        c.gridy = 3

        c.gridx = 0
        component.add(
            JLabel(
                'Start marker of the anti-CSRF token in the response, #csrf_name# is replaced by the name of the anti-CSRF token:'
            ), c)

        self._csrf_start_marker_field = JTextField(
            'name="' + CSRF_NAME_PLACEHOLDER + '" value="', 40)
        c.gridx = 1
        component.add(self._csrf_start_marker_field, c)

        # 5th line
        c.gridy = 4

        c.gridx = 0
        component.add(
            JLabel(
                'End marker of the anti-CSRF token in the response, #csrf_name# is replaced by the name of the anti-CSRF token:'
            ), c)

        self._csrf_end_marker_field = JTextField('"', 40)
        c.gridx = 1
        component.add(self._csrf_end_marker_field, c)

        # 6th line
        c.gridy = 5

        c.gridx = 0
        component.add(JLabel(' '), c)

        # 7th line
        c.gridy = 6

        c.gridx = 0
        component.add(JLabel('HTML decode the anti-CSRF token:'), c)

        self._do_html_decode = JCheckBox("", True)
        c.gridx = 1
        component.add(self._do_html_decode, c)

        # 8th line
        c.gridy = 7

        c.gridx = 0
        component.add(JLabel('URL decode the anti-CSRF token:'), c)

        self._do_url_decode = JCheckBox("", True)
        c.gridx = 1
        component.add(self._do_url_decode, c)

        # 9th line
        c.gridy = 8

        c.gridx = 0
        component.add(JLabel('URL encode the anti-CSRF token:'), c)

        self._do_url_encode = JCheckBox("", True)
        c.gridx = 1
        component.add(self._do_url_encode, c)

        # 10th line
        c.gridy = 9

        c.gridx = 0
        component.add(JLabel(' '), c)

        self._callbacks.customizeUiComponent(component)
        self._ui_component = component
Пример #40
0
        SwingUtilities.invokeLater(
            lambda: table.updateUI())  # executed by the event dispatch thread
    except:
        print "Malformed regex pattern"


def typingInSearchField(event):
    if KeyEvent.VK_ENTER == event.getKeyCode():
        filterTable()
    elif KeyEvent.VK_ESCAPE == event.getKeyCode():
        search_field.setText("")
        filterTable()  # to restore the full list of rows


# Top-left element: a text field for filtering rows by regular expression match
c.gridx = 0
c.gridy = 0
c.anchor = GridBagConstraints.CENTER
c.fill = GridBagConstraints.HORIZONTAL
search_field = JTextField("", keyPressed=typingInSearchField)
gb.setConstraints(search_field, c)
all.add(search_field)

# Bottom left element: the table, wrapped in a scrollable component
table = JTable(TableModel())
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
#table.setCellSelectionEnabled(True)
table.setAutoCreateRowSorter(
    True)  # to sort the view only, not the data in the underlying TableModel
c.gridx = 0
c.gridy = 1
Пример #41
0
    def __init__(self, frame, name):
        self.frame = frame
        self.exception = None
        self.name = name
        self.searchTerm = None
        self.searchIndex = -1

        self.searchField = JTextField("")
        self.searchField.addActionListener(SearchListener(self))

        self.newGeneFrom = JTextField("")
        self.newGeneTo = JTextField("")
        self.newGeneButton = JButton("New Gene")
        newGeneActionListener = NewGeneActionListener(self)
        self.newGeneFrom.addActionListener(newGeneActionListener)
        self.newGeneTo.addActionListener(newGeneActionListener)
        self.newGeneButton.addActionListener(newGeneActionListener)

        self.markForRemovalButton = JButton("Mark For Removal")
        self.markForRemovalButton.addActionListener(MarkForRemovalListener(self))
        
        self.inGenes = JList(DefaultListModel())
        self.inGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.inGenes.cellRenderer = ProfelisCellRenderer()
        self.markButtonLabelerTimer = Timer(100, MarkButtonLabeler(self))
        self.markButtonLabelerTimer.start()
        self.loadFile()

        self.outGenes = JList(DefaultListModel())
        self.outGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.outGenes.cellRenderer = ProfelisCellRenderer()
                
        constraints = GridBagConstraints()
        self.layout = GridBagLayout()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes In Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        self.add(JButton(RemoveAction(self)), constraints)
        constraints.gridx, constraints.gridy = 1, 1
        self.add(self.markForRemovalButton, constraints)
        constraints.gridx, constraints.gridy = 2, 1
        self.add(JLabel("Search"), constraints)
        constraints.gridx, constraints.gridy = 3, 1
        constraints.fill = GridBagConstraints.HORIZONTAL
        self.add(self.searchField, constraints)
        constraints.gridx, constraints.gridy = 0, 2
        constraints.gridwidth, constraints.gridheight = 4, 2
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.inGenes), constraints)

        constraints.gridx, constraints.gridy = 4, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes To Add To Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 4, 1
        self.add(self.newGeneButton, constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 5, 1
        self.add(self.newGeneFrom, constraints)
        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 6, 1
        self.add(JLabel("To"), constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 7, 1
        self.add(self.newGeneTo, constraints)

        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 4, 2
        self.add(JButton(AddGenesAction(self)), constraints)
        constraints.gridx, constraints.gridy = 4, 3
        constraints.gridwidth, constraints.gridheight = 4, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.outGenes), constraints)
# Create the UI: a 3-column table and a text area next to it
# to show the Motivation column of any selected row:
all = JPanel()
gb = GridBagLayout()
all.setLayout(gb)
c = GridBagConstraints()
table = JTable(TableModel())
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
table.setAutoCreateRowSorter(True) # to sort the view only, not the data in the underlying TableModel
jsp = JScrollPane(table)
jsp.setPreferredSize(Dimension(200, 500))
c.anchor = GridBagConstraints.NORTHWEST
c.fill = GridBagConstraints.BOTH # resize with the frame
gb.setConstraints(jsp, c)
all.add(jsp)
c.gridx = 1
c.weightx = 1.0 # take any additionally available horizontal space
c.weighty = 1.0
textarea = JTextArea()
textarea.setLineWrap(True)
textarea.setWrapStyleWord(True) # wrap text by cutting at whitespace
textarea.setEditable(False) # avoid changing the text, as any changes wouldn't be persisted to disk
font = textarea.getFont().deriveFont(20.0)
textarea.setFont(font)
textarea.setPreferredSize(Dimension(500, 500))
gb.setConstraints(textarea, c)
all.add(textarea)
frame = JFrame("CSV")
frame.getContentPane().add(all)
frame.pack()
frame.setVisible(True)
Пример #43
0
    def registerExtenderCallbacks(self, this_callbacks):  ### IBurpExtender
        global callbacks, helpers
        global extension_enable, in_scope_only
        global change_method_to_post

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

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

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

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

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

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

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

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

        self.tabs = JTabbedPane()
        self.tabs.addTab('Settings', self.settings)

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

        callbacks.registerProxyListener(self)

        print "Successfully loaded %s v%s by Mohammed alsaggaf " % (NAME,
                                                                    VERSION)
Пример #44
0
    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
Пример #45
0
def specifyRoiUI(roi=Roi(0, 0, 0, 0)):
    # A panel in which to place UI elements
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
    gb = GridBagLayout()
    panel.setLayout(gb)
    gc = GBC()

    bounds = roi.getBounds() if roi else Rectangle()
    textfields = []
    roimakers = []

    # Basic properties of most UI elements, will edit when needed
    gc.gridx = 0  # can be any natural number
    gc.gridy = 0  # idem.
    gc.gridwidth = 1  # when e.g. 2, the UI element will occupy two horizontally adjacent grid cells
    gc.gridheight = 1  # same but vertically
    gc.fill = GBC.NONE  # can also be BOTH, VERTICAL and HORIZONTAL

    for title in ["x", "y", "width", "height"]:
        # label
        gc.gridx = 0
        gc.anchor = GBC.EAST
        label = JLabel(title + ": ")
        gb.setConstraints(label, gc)  # copies the given constraints 'gc',
        # so we can modify and reuse gc later.
        panel.add(label)
        # text field, below the title
        gc.gridx = 1
        gc.anchor = GBC.WEST
        text = str(getattr(bounds,
                           title))  # same as e.g. bounds.x, bounds.width, ...
        textfield = JTextField(text,
                               10)  # 10 is the size of the field, in digits
        gb.setConstraints(textfield, gc)
        panel.add(textfield)
        textfields.append(
            textfield)  # collect all 4 created textfields for the listeners
        # setup ROI and text field listeners
        listener = RoiMaker(textfields,
                            len(textfields) -
                            1)  # second argument is the index of textfield
        # in the list of textfields.
        roimakers.append(listener)
        textfield.addKeyListener(listener)
        textfield.addMouseWheelListener(listener)
        # Position next ROI property in a new row by increasing the Y coordinate of the layout grid
        gc.gridy += 1

    # User documentation (uses HTML to define line breaks)
    doc = JLabel(
        "<html><body><br />Click on a field to activate it, then:<br />" +
        "Type in integer numbers<br />" +
        "or use arrow keys to increase by 1<br />" +
        "or use the scroll wheel on a field.</body></html>")
    gc.gridx = 0  # start at the first column
    gc.gridwidth = 2  # Spans both columns
    gb.setConstraints(doc, gc)
    panel.add(doc)

    # Listen to changes in the ROI of imp
    roilistener = TextFieldUpdater(textfields)
    Roi.addRoiListener(roilistener)

    # Show window
    frame = JFrame("Specify rectangular ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setLocationRelativeTo(None)  # center in the screen
    frame.setDefaultCloseOperation(
        JFrame.DO_NOTHING_ON_CLOSE)  # prevent closing the window
    frame.addWindowListener(
        CloseControl(roilistener))  # handles closing the window
    frame.setVisible(True)
Пример #46
0
    def _constructAttackPanel(self, insets, messageEditorComponent):
        attackPanel = JPanel(GridBagLayout())

        targetHeadingLabel = JLabel("<html><b>Target</b></html>")
        targetHeadingLabelConstraints = GridBagConstraints()
        targetHeadingLabelConstraints.gridx = 0
        targetHeadingLabelConstraints.gridy = 0
        targetHeadingLabelConstraints.gridwidth = 4
        targetHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        targetHeadingLabelConstraints.insets = insets
        attackPanel.add(targetHeadingLabel, targetHeadingLabelConstraints)

        startAttackButton = JButton("<html><b>Start Attack</b></html>",
                                    actionPerformed=self._startAttack)
        startAttackButtonConstraints = GridBagConstraints()
        startAttackButtonConstraints.gridx = 4
        startAttackButtonConstraints.gridy = 0
        startAttackButtonConstraints.insets = insets
        attackPanel.add(startAttackButton, startAttackButtonConstraints)

        hostLabel = JLabel("Host:")
        hostLabelConstraints = GridBagConstraints()
        hostLabelConstraints.gridx = 0
        hostLabelConstraints.gridy = 1
        hostLabelConstraints.anchor = GridBagConstraints.LINE_START
        hostLabelConstraints.insets = insets
        attackPanel.add(hostLabel, hostLabelConstraints)

        self._hostTextField = JTextField(25)
        self._hostTextField.setMinimumSize(
            self._hostTextField.getPreferredSize())
        hostTextFieldConstraints = GridBagConstraints()
        hostTextFieldConstraints.gridx = 1
        hostTextFieldConstraints.gridy = 1
        hostTextFieldConstraints.weightx = 1
        hostTextFieldConstraints.gridwidth = 2
        hostTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        hostTextFieldConstraints.insets = insets
        attackPanel.add(self._hostTextField, hostTextFieldConstraints)

        portLabel = JLabel("Port:")
        portLabelConstraints = GridBagConstraints()
        portLabelConstraints.gridx = 0
        portLabelConstraints.gridy = 2
        portLabelConstraints.anchor = GridBagConstraints.LINE_START
        portLabelConstraints.insets = insets
        attackPanel.add(portLabel, portLabelConstraints)

        self._portTextField = JTextField(5)
        self._portTextField.setMinimumSize(
            self._portTextField.getPreferredSize())
        portTextFieldConstraints = GridBagConstraints()
        portTextFieldConstraints.gridx = 1
        portTextFieldConstraints.gridy = 2
        portTextFieldConstraints.gridwidth = 2
        portTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        portTextFieldConstraints.insets = insets
        attackPanel.add(self._portTextField, portTextFieldConstraints)

        self._protocolCheckBox = JCheckBox("Use HTTPS")
        protocolCheckBoxConstraints = GridBagConstraints()
        protocolCheckBoxConstraints.gridx = 0
        protocolCheckBoxConstraints.gridy = 3
        protocolCheckBoxConstraints.gridwidth = 3
        protocolCheckBoxConstraints.anchor = GridBagConstraints.LINE_START
        protocolCheckBoxConstraints.insets = insets
        attackPanel.add(self._protocolCheckBox, protocolCheckBoxConstraints)

        requestHeadingLabel = JLabel("<html><b>Request</b></html>")
        requestHeadingLabelConstraints = GridBagConstraints()
        requestHeadingLabelConstraints.gridx = 0
        requestHeadingLabelConstraints.gridy = 4
        requestHeadingLabelConstraints.gridwidth = 4
        requestHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestHeadingLabelConstraints.insets = insets
        attackPanel.add(requestHeadingLabel, requestHeadingLabelConstraints)

        messageEditorComponentConstraints = GridBagConstraints()
        messageEditorComponentConstraints.gridx = 0
        messageEditorComponentConstraints.gridy = 5
        messageEditorComponentConstraints.weightx = 1
        messageEditorComponentConstraints.weighty = .75
        messageEditorComponentConstraints.gridwidth = 4
        messageEditorComponentConstraints.gridheight = 2
        messageEditorComponentConstraints.fill = GridBagConstraints.BOTH
        messageEditorComponentConstraints.insets = insets
        attackPanel.add(
            messageEditorComponent, messageEditorComponentConstraints)

        addPayloadButton = JButton(
            "Add \xa7", actionPerformed=self._addPayload)
        addPayloadButtonConstraints = GridBagConstraints()
        addPayloadButtonConstraints.gridx = 4
        addPayloadButtonConstraints.gridy = 5
        addPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        addPayloadButtonConstraints.insets = insets
        attackPanel.add(addPayloadButton, addPayloadButtonConstraints)

        clearPayloadButton = JButton(
            "Clear \xa7", actionPerformed=self._clearPayloads)
        clearPayloadButtonConstraints = GridBagConstraints()
        clearPayloadButtonConstraints.gridx = 4
        clearPayloadButtonConstraints.gridy = 6
        clearPayloadButtonConstraints.anchor = GridBagConstraints.PAGE_START
        clearPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        clearPayloadButtonConstraints.insets = insets
        attackPanel.add(clearPayloadButton, clearPayloadButtonConstraints)

        payloadHeadingLabel = JLabel("<html><b>Payloads<b></html>")
        payloadHeadingLabelConstraints = GridBagConstraints()
        payloadHeadingLabelConstraints.gridx = 0
        payloadHeadingLabelConstraints.gridy = 7
        payloadHeadingLabelConstraints.gridwidth = 4
        payloadHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        payloadHeadingLabelConstraints.insets = insets
        attackPanel.add(payloadHeadingLabel, payloadHeadingLabelConstraints)

        self._payloadTextArea = JTextArea()
        payloadScrollPane = JScrollPane(self._payloadTextArea)
        payloadScrollPaneConstraints = GridBagConstraints()
        payloadScrollPaneConstraints.gridx = 0
        payloadScrollPaneConstraints.gridy = 8
        payloadScrollPaneConstraints.weighty = .25
        payloadScrollPaneConstraints.gridwidth = 3
        payloadScrollPaneConstraints.fill = GridBagConstraints.BOTH
        payloadScrollPaneConstraints.insets = insets
        attackPanel.add(payloadScrollPane, payloadScrollPaneConstraints)

        requestsNumLabel = JLabel("Number of requests for each payload:")
        requestsNumLabelConstraints = GridBagConstraints()
        requestsNumLabelConstraints.gridx = 0
        requestsNumLabelConstraints.gridy = 9
        requestsNumLabelConstraints.gridwidth = 2
        requestsNumLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumLabelConstraints.insets = insets
        attackPanel.add(requestsNumLabel, requestsNumLabelConstraints)

        self._requestsNumTextField = JTextField("100", 4)
        self._requestsNumTextField.setMinimumSize(
            self._requestsNumTextField.getPreferredSize())
        requestsNumTextFieldConstraints = GridBagConstraints()
        requestsNumTextFieldConstraints.gridx = 2
        requestsNumTextFieldConstraints.gridy = 9
        requestsNumTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumTextFieldConstraints.insets = insets
        attackPanel.add(
            self._requestsNumTextField, requestsNumTextFieldConstraints)

        return attackPanel
Пример #47
0
 def addSigningKeyFromCmdTextField(self):
     c = GridBagConstraints()
     c.gridx = 1
     c.gridy = 6
     self._configurationPanel.add(self._fromCmdTextField, c)
Пример #48
0
    def initComponents(self):

        self.setLayout(GridBagLayout())

        gc = GridBagConstraints()

        gc.weightx = 1
        gc.weighty = 1

        # First Row
        gc.gridy = 0

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.fill = GridBagConstraints.NONE
        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.nameLabel, gc)

        gc.gridx = 1
        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.nameField, gc)

        # Second Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0

        gc.anchor = GridBagConstraints.LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.mobLabel, gc)

        gc.gridx = 1

        gc.anchor = GridBagConstraints.LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.mobField, gc)

        #Third Row
        gc.gridy += 1

        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.emailLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.emailField, gc)

        #Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 0.1
        gc.gridx = 0
        gc.anchor = GridBagConstraints.FIRST_LINE_END
        gc.insets = Insets(0, 0, 0, 5)
        self.add(self.vehicleLabel, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.vehicleField, gc)

        gc.weightx = 1
        gc.weighty = 0.2
        gc.gridx = 2
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        gc.insets = Insets(0, 0, 0, 0)
        self.add(self.automateRecogBtn, gc)

        #Next Row
        gc.gridy += 1
        gc.weightx = 1
        gc.weighty = 2.0
        gc.gridx = 1
        gc.anchor = GridBagConstraints.FIRST_LINE_START
        self.add(self.regBtn, gc)

        innerBorder = BorderFactory.createTitledBorder('Register Vehicle')
        outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.setBorder(
            BorderFactory.createCompoundBorder(outerBorder, innerBorder))
Пример #49
0
    def build_welcome_panel(self):
        '''
        Construct the welcome panel here.
        '''
        panel = JPanel(GridBagLayout())
        constraints = GridBagConstraints()
        constraints.insets = Insets(10, 10, 10, 10)

        message = ('<html><body>'
                   '<h1>Welcome to Nammu</h1>'
                   '<h2>An editor for the ORACC project<h2>'
                   '<p>'
                   '<a href=\'oracc\'>Click here</a> for help with ORACC.'
                   '</p>'
                   '<p>Learn more about Nammu <a href=\'nammu\'>here</a>.</p>'
                   '</body></html>')

        # Configure a JEditorPane to display HTML for our welcome message
        msg_pane = JEditorPane()
        msg_pane.setEditable(False)
        kit = HTMLEditorKit()
        msg_pane.setEditorKit(kit)
        scrollPane = JScrollPane(msg_pane)

        # This handles the stylesheet applied to the welcome message
        styleSheet = kit.getStyleSheet()
        styleSheet.addRule('body {color:black; font-size: 16 pt; }')
        styleSheet.addRule('h1 {text-align:center; }')
        styleSheet.addRule('h2 {text-align:center; }')

        # Set the JEditorPane background to match the rest of the window
        msg_pane.border = BorderFactory.createEmptyBorder(4, 4, 4, 4)
        msg_pane.background = Color(238, 238, 238)

        # Add the message and the css and to the JEditorPane
        doc = kit.createDefaultDocument()
        msg_pane.setDocument(doc)
        msg_pane.setText(message)

        # Set up a hyperlink listener
        listener = addEventListener(msg_pane, HyperlinkListener,
                                    'hyperlinkUpdate', self.handleEvent)

        # Configure the placement of the JEditorPane
        constraints.gridx = 1
        constraints.gridy = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.anchor = GridBagConstraints.CENTER

        panel.add(msg_pane, constraints)

        # Build and place the checkbox
        self.checkbox = JCheckBox('Don\'t show this message again.',
                                  selected=False)
        constraints.gridx = 1
        constraints.gridy = 2
        panel.add(self.checkbox, constraints)

        # Build and place the close button
        close_button = JButton('Close', actionPerformed=self.close_action)

        constraints.gridx = 2
        constraints.gridy = 2
        panel.add(close_button, constraints)

        return panel
Пример #50
0
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

        # Keep a reference to our callbacks object
        self._callbacks = callbacks

        # Obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Burpsuite Yara Scanner")

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

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

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

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

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

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

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

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")
Пример #51
0
	def getUiComponent(self):
		#
		# Button functions
		#
		
		# Apply regex and preview
		def regexify(event):
			withSect = re.sub(regexBox.getText(), lambda m: unichr(167) + m.group(0) + unichr(167), contentBox.getText(), flags = re.M)
			resultsBox.setText(withSect)
			resultsBox.requestFocusInWindow()
			return

		# Actually send to Intruder
		def sendToIntruder(event):
			# TODO Parse host, port, and SSL
			offsets = ArrayList()
			p = re.compile(regexBox.getText())
			for m in p.finditer(contentBox.getText()):
				offsets.add(array((m.start(), m.end()), 'i'))
			self._callbacks.sendToIntruder("www.example.com", 80, False, contentBox.getText(), offsets)
			return
			

		# HTML body box
		body = """POST /example?p1=p1val&p2=p2val HTTP/1.0
Cookie: c=cval
Content-Length: 17

p3=p3val&p4=p4val&asdf=1234&qwer=123

<b>test</b>

<xml body:something tag='asdf'>
</xml>

&sect;"""
		# HTTP request box
		contentBox = JTextArea(body, 10, 80)
		contentBoxScroll = JScrollPane(contentBox)

		# Regex box
		regexBox = JTextField("[0-9]{3}", 40)

		# Buttons
		btnRegexify = JButton("Regexify", actionPerformed=regexify)
		btnSendToIntruder = JButton("Send to Intruder", actionPerformed=sendToIntruder)

		# Results box
		resultsBox = JTextArea("Results will be shown here", 10, 80)
		resultsBoxScroll = JScrollPane(resultsBox)        

		# Main panel
		mainPanel = JPanel(GridBagLayout())
		gbc = GridBagConstraints()
		gbc.gridx = 0
		gbc.gridy = 0
		gbc.weightx = 0.8
		contentBoxScroll.setPreferredSize(Dimension(1000, 300))
		mainPanel.add(contentBoxScroll, gbc)
		gbc.gridx = 1
		gbc.gridy = 0
		gbc.weightx = 0.1
		mainPanel.add(regexBox, gbc)
		gbc.gridx = 1
		gbc.gridy = 1
		gbc.weightx = 0.1
		mainPanel.add(btnRegexify, gbc)
		gbc.gridx = 1
		gbc.gridy = 3
		gbc.weightx = 0.1
		mainPanel.add(btnSendToIntruder, gbc)
		gbc.gridx = 0
		gbc.gridy = 2
		gbc.weightx = 1
		gbc.weighty = 1
		resultsBoxScroll.setPreferredSize(Dimension(1000, 300))
		mainPanel.add(resultsBoxScroll, gbc)

		return mainPanel
Пример #52
0
    def registerExtenderCallbacks( self, callbacks):
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JWT FuzzHelper")
        callbacks.registerIntruderPayloadProcessor(self)
        callbacks.registerExtensionStateListener(self)
        
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # Holds values passed by user from Configuration panel
        self._fuzzoptions = { 
                                "target" : "Header", 
                                "selector" : None, 
                                "signature" : False,
                                "algorithm" : "HS256",
                                "key" : "",
                                "key_cmd" : ""
                            }

        self._isNone = lambda val: isinstance(val, type(None))

        # Configuration panel Layout
        self._configurationPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [ 0, 0, 0]
        gridBagLayout.rowHeights = [ 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
        gridBagLayout.columnWeights = [ 0.0, 0.0, 0.0 ]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
        self._configurationPanel.setLayout(gridBagLayout)

        # Setup tabs
        self._tabs = JTabbedPane()
        self._tabs.addTab('Configuration',self._configurationPanel)
        #self._tabs.addTab('Help',self._helpPanel)

        # Target Options
        targetLabel = JLabel("Target Selection (Required): ")
        targetLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 1
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(targetLabel,c)

        options = [ 'Header', 'Payload' ]
        self._targetComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 1
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._targetComboBox,c)

        # Help Button
        self._helpButton = JButton("Help", actionPerformed=self.helpMenu)
        c = GridBagConstraints()
        c.gridx = 2
        c.gridy = 1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._helpButton,c)

        # Selector Options
        self._selectorLabel = JLabel("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._selectorLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._selectorLabel, c)

        self._selectorTextField = JTextField('',50)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 2
        self._configurationPanel.add(self._selectorTextField, c)

        # Regex option

        self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ")
        self._regexLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 3
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._regexLabel,c)

        self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 3
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._regexCheckBox,c)

        # Signature Options
        generateSignatureLabel = JLabel("Generate signature? (Required): ")
        generateSignatureLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 4
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(generateSignatureLabel,c)

        options = ["False", "True"]
        self._generateSignatureComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 4
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._generateSignatureComboBox,c)

        signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ")
        signatureAlgorithmLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 5
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(signatureAlgorithmLabel,c)

        options = ["None", "HS256","HS384","HS512","ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS256","PS384","PS512"]
        self._algorithmSelectionComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 5
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._algorithmSelectionComboBox,c)

        # Signing key options
        self._signingKeyLabel = JLabel("Signing Key (Optional): ")
        self._signingKeyLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 6
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._signingKeyLabel,c)

        self.addSigningKeyTextArea()
        self._fromFileTextField = JTextField('',50) 

        fromFileLabel = JLabel("Signing key from file? (Optional): ")
        fromFileLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 7
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromFileLabel,c)

        self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 7
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromFileCheckBox,c)

        self._fromCmdTextField = JTextField('',50)

        fromCmdLabel = JLabel("Signing key from command? (Optional): ")
        fromCmdLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 8
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromCmdLabel,c)

        self._fromCmdCheckBox = JCheckBox("", actionPerformed=self.fromCmd)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 8
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromCmdCheckBox,c)

        self._saveButton = JButton("Save Configuration", actionPerformed=self.saveOptions)
        self._saveButton.setText("Save Configuration")
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 9
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._saveButton,c)

        
        callbacks.customizeUiComponent(self._configurationPanel)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.addSuiteTab(self)

        self._stdout.println("[JWT FuzzHelper] Loaded successfully")
        return
Пример #53
0
    def tag_3_1(self, c):
        # 输入框-标题
        lblParams = JLabel(u'请填写域名:')
        self.setFontBold(lblParams)
        lblParams.setForeground(Color(0, 0, 153))
        c.gridx = 0
        c.gridy = 0
        c.insets = Insets(5, 5, 5, 5)
        c.fill = GridBagConstraints.NONE
        c.anchor = GridBagConstraints.FIRST_LINE_END
        self.white_list_domain_settings.add(lblParams, c)

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

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

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

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

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

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

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

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

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

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