Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

19.3 KB
Raw Blame
package opensuite.intruder;

import opensuite.core.Bytes;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.Param;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * The positions tab: an editable view of the request with {@code §} payload
 * markers, buttons to manage those markers, and the attack-type combo.
 */
public class PositionsPanel extends JPanel {

    /** The payload position marker. */
    static final char MARK = '§';

    private static final String DEFAULT_REQUEST =
            "POST /example?p1=" + MARK + "p1val" + MARK + "&p2=" + MARK + "p2val" + MARK + " HTTP/1.0\r\n"
            + "Cookie: c=" + MARK + "cval" + MARK + "\r\n"
            + "Content-Length: 17\r\n"
            + "\r\n"
            + "p3=" + MARK + "p3val" + MARK + "&p4=" + MARK + "p4val" + MARK;

    /**
     * The request editor. Payload positions are drawn the way the reference
     * draws them: dark red text on a grey block, or on the selection colour when
     * the position is selected. A plain text area cannot colour ranges of text,
     * so the positions are painted over after the text itself.
     */
    private final JTextArea area = new JTextArea(DEFAULT_REQUEST) {
        @Override protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            paintMarkerText((Graphics2D) g);
        }
    };
    private final JComboBox<AttackType> attackCombo = Ui.combo(AttackType.ordered());
    private final JLabel highlightLabel = Ui.label("0 highlights");
    private final JLabel posLabel = Ui.label("0 payload positions");
    private final JLabel lenLabel = Ui.label("Length: 0");
    private final JTextField editorSearch = Ui.field("");
    private final JButton start = Ui.primaryButton("Start attack", "Launch the attack with the current configuration");
    /** Holds the target row supplied by the tool, under the attack type. */
    private final JPanel targetSlot = new JPanel(new BorderLayout());

    private Runnable onChange;

    /** Place the target row (host, port, TLS) under the attack type, as in the reference. */
    public void setTargetRow(JComponent target) {
        targetSlot.removeAll();
        targetSlot.add(target, BorderLayout.CENTER);
        targetSlot.revalidate();
        targetSlot.repaint();
    }

    public PositionsPanel() {
        super(new BorderLayout());

        area.setFont(Ui.MONO);
        area.setLineWrap(false);
        area.setMargin(new Insets(2, 5, 2, 4));
        area.setToolTipText("Use the § marker to define the beginning and end of each payload "
                + "position; the inserted payload will replace the text between the markers");
        area.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e)  { counts(); }
            public void removeUpdate(DocumentEvent e)  { counts(); }
            public void changedUpdate(DocumentEvent e) { counts(); }
        });

        // Header, as in the reference: three ruled rows. A help mark, the attack
        // type stretched across the row and the orange Start attack at its right
        // end; the target row; then the Positions row with its marker buttons
        // directly above the request editor.
        attackCombo.setToolTipText("The attack type determines the way in which payloads are "
                + "assigned to payload positions");
        attackCombo.addActionListener(e -> fire());
        start.setIcon(circledPlay());
        start.setIconTextGap(10);
        start.setHorizontalAlignment(SwingConstants.LEFT);
        start.setBorder(BorderFactory.createEmptyBorder(3, 11, 3, 10));
        Ui.sized(start, 124);
        JButton attackHelp = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.help(21, opensuite.ui.Theme.TEXT), "Intruder", null);
        attackHelp.setBorder(null);
        attackHelp.addActionListener(e -> JOptionPane.showMessageDialog(this,
                "Choose an attack type, mark the payload positions in the request below, "
                + "then configure the payloads on the right and start the attack.", "Intruder", JOptionPane.INFORMATION_MESSAGE));
        // Three bands of 52px on white, each with its controls 15px down.
        JPanel attackRow = band(new BorderLayout(10, 0));
        attackRow.add(attackHelp, BorderLayout.WEST);
        attackRow.add(attackCombo, BorderLayout.CENTER);
        attackRow.add(start, BorderLayout.EAST);

        JButton addMark   = Ui.button("Add §", "Insert a payload marker");
        JButton clearMark = Ui.button("Clear §", "Clear all payload markers");
        JButton autoMark  = Ui.button("Auto §", "Automatically set a payload at each URL, "
                + "cookie and body parameter");
        markButtons = new JButton[]{ addMark, clearMark, autoMark };
        addMark.addActionListener(e -> addMarker());
        clearMark.addActionListener(e -> clearMarkers());
        autoMark.addActionListener(e -> autoPlace());
        JPanel posRow = band(new FlowLayout(FlowLayout.LEFT, 0, 0));
        posRow.setBorder(Ui.pad(ROW_PAD, 15, ROW_PAD, 15));
        JLabel posLabelHead = Ui.label("Positions");
        posLabelHead.setPreferredSize(new Dimension(posLabelHead.getPreferredSize().width, Ui.tall(22)));
        posRow.add(posLabelHead);
        posRow.add(Box.createHorizontalStrut(10));
        posRow.add(addMark);
        posRow.add(Box.createHorizontalStrut(5));
        posRow.add(clearMark);
        posRow.add(Box.createHorizontalStrut(5));
        posRow.add(autoMark);

        targetSlot.setOpaque(true);
        targetSlot.setBackground(opensuite.ui.Theme.CONTENT);
        targetSlot.setBorder(Ui.pad(ROW_PAD, 15, ROW_PAD, 15));
        targetSlot.setPreferredSize(new Dimension(10, Ui.tall(52)));
        JPanel header = Ui.vbox(attackRow, rule(), targetSlot, rule(), posRow, rule());

        // The editor footer, as in the reference: help, settings, the match
        // steppers and search, then the three counts parted by rules.
        JPanel south = opensuite.ui.MessageEditor.searchBar(editorSearch,
                () -> JOptionPane.showMessageDialog(this,
                        "Select a value and press Add \u00a7 to mark it, or press Auto \u00a7 to mark every "
                        + "parameter. Each marked pair is one payload position.", "Payload positions", JOptionPane.INFORMATION_MESSAGE),
                b -> editorMenu().show(b, 0, b.getHeight()),
                () -> step(-1), () -> step(1), highlightLabel, posLabel, lenLabel);

        editorSearch.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e)  { search(); }
            public void removeUpdate(DocumentEvent e)  { search(); }
            public void changedUpdate(DocumentEvent e) { search(); }
        });

        JScrollPane sp = Ui.scroll(area);
        sp.setBorder(BorderFactory.createEmptyBorder());
        sp.setRowHeaderView(new opensuite.ui.LineGutter(area));
        area.addCaretListener(e -> area.repaint());   // a selected position changes colour
        add(header, BorderLayout.NORTH);
        add(sp, BorderLayout.CENTER);
        add(south, BorderLayout.SOUTH);

        counts();
        paintMarkers();
    }

    // ---------------- configuration ----------------

    public void setStartAction(Runnable r) {
        for (java.awt.event.ActionListener l : start.getActionListeners()) start.removeActionListener(l);
        start.addActionListener(e -> r.run());
    }

    public void onChange(Runnable r) { this.onChange = r; }

    private JButton[] markButtons = new JButton[0];

    /**
     * How an attack's own window shows its positions: no Start attack button,
     * and the attack type and the marker buttons white inside their outlines.
     */
    public void hideStart() {
        start.setVisible(false);
        attackCombo.setBackground(opensuite.ui.Theme.CONTENT);
        for (JButton b : markButtons) b.putClientProperty(opensuite.ui.theme.FlatButtonUI.OUTLINED, Boolean.TRUE);
    }

    private void fire() { if (onChange != null) onChange.run(); }

    /** Load a request, replacing the text and auto-placing markers. */
    public void setRequest(HttpService svc, HttpMessage req) {
        if (req == null) return;
        area.setText(Bytes.str(req.raw()));
        area.setCaretPosition(0);
        autoPlace();
    }

    public AttackType attackType() {
        AttackType t = (AttackType) attackCombo.getSelectedItem();
        return t == null ? AttackType.SNIPER : t;
    }

    public void setAttackType(AttackType t) { if (t != null) attackCombo.setSelectedItem(t); }

    /** Whether Auto wraps each value (false) or puts an empty position after it (true). */
    private java.util.function.BooleanSupplier appendPlacement = () -> false;
    public void setAppendPlacement(java.util.function.BooleanSupplier s) { if (s != null) appendPlacement = s; }

    /** The current text, markers included. */
    public String markedText() { return area.getText(); }

    /** Replace the marked request text directly, keeping the user's § markers. */
    public void setMarkedText(String s) { area.setText(s == null ? "" : s); }

    /** Number of payload positions, each a matched pair of markers. */
    public int positionCount() {
        int marks = 0;
        String s = area.getText();
        for (int i = 0; i < s.length(); i++) if (s.charAt(i) == MARK) marks++;
        return marks / 2;
    }

    // ---------------- marker editing ----------------

    private void addMarker() {
        int a = area.getSelectionStart(), b = area.getSelectionEnd();
        try {
            if (b > a) {
                area.getDocument().insertString(b, String.valueOf(MARK), null);
                area.getDocument().insertString(a, String.valueOf(MARK), null);
            } else {
                area.getDocument().insertString(a, "" + MARK + MARK, null);
            }
        } catch (Exception ignored) {}
        counts();
    }

    private void clearMarkers() {
        area.setText(stripMarkers(area.getText()));
        counts();
    }

    /** Remove all payload markers, keeping the request text. */
    public void clearPositions() { clearMarkers(); }

    static String stripMarkers(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) if (s.charAt(i) != MARK) sb.append(s.charAt(i));
        return sb.toString();
    }

    /** Wrap each parameter value (URL, body, cookie, JSON, XML, multipart) in markers. */
    private void autoPlace() {
        String text = stripMarkers(area.getText());
        HttpMessage m = new HttpMessage(Bytes.bytes(text));
        List<int[]> ranges = new ArrayList<>();
        for (Param p : m.parameters()) {
            Param.Type t = p.type();
            if (t == Param.Type.HEADER) continue;
            int vs = p.valueStart(), ve = p.valueEnd();
            if (vs >= 0 && ve >= vs && ve <= text.length()) ranges.add(new int[]{vs, ve});
        }
        // Insert from the end so earlier offsets stay valid.
        ranges.sort(Comparator.comparingInt((int[] r) -> r[0]).reversed());
        StringBuilder sb = new StringBuilder(text);
        boolean append = appendPlacement.getAsBoolean();
        for (int[] r : ranges) {
            sb.insert(r[1], MARK);
            sb.insert(append ? r[1] : r[0], MARK);
        }
        area.setText(sb.toString());
        area.setCaretPosition(0);
        counts();
    }

    private void counts() {
        int n = positionCount();
        posLabel.setText(n + (n == 1 ? " payload position" : " payload positions"));
        if (editorSearch.getText().isEmpty()) highlightLabel.setText(n + (n == 1 ? " highlight" : " highlights"));
        // The length of the request as typed, markers and line ends included.
        lenLabel.setText("Length: " + area.getText().length());
        paintMarkers();
        fire();
    }

    // ---------------- editor marks ----------------

    /** Tint every marked payload position, so the positions read at a glance. */
    private void paintMarkers() {
        javax.swing.text.Highlighter h = area.getHighlighter();
        for (javax.swing.text.Highlighter.Highlight hl : h.getHighlights()) {
            if (hl.getPainter() instanceof javax.swing.text.DefaultHighlighter.DefaultHighlightPainter) h.removeHighlight(hl);
        }
        String s = area.getText();
        int from = s.indexOf(MARK);
        while (from >= 0) {
            int to = s.indexOf(MARK, from + 1);
            if (to < 0) break;
            try { h.addHighlight(from, to + 1, MARKER_PAINT); } catch (javax.swing.text.BadLocationException ignored) {}
            from = s.indexOf(MARK, to + 1);
        }
        searchHits = 0;
        String q = editorSearch == null ? "" : editorSearch.getText();
        if (!q.isEmpty()) {
            String hay = s.toLowerCase();
            String needle = q.toLowerCase();
            int i = hay.indexOf(needle);
            while (i >= 0) {
                try { h.addHighlight(i, i + needle.length(), SEARCH_PAINT); } catch (javax.swing.text.BadLocationException ignored) {}
                searchHits++;
                i = hay.indexOf(needle, i + needle.length());
            }
        }
        // With nothing searched for, the tinted payload positions are the highlights.
        int shown = editorSearch.getText().isEmpty() ? positionCount() : searchHits;
        highlightLabel.setText(shown + (shown == 1 ? " highlight" : " highlights"));
    }

    /** Padding above and below each header row, so the rules sit where the reference's do. */
    private static final int ROW_PAD = 15;

    /** One white 52px band of the header. */
    private static JPanel band(LayoutManager layout) {
        JPanel p = new JPanel(layout);
        p.setOpaque(true);
        p.setBackground(opensuite.ui.Theme.CONTENT);
        p.setBorder(Ui.pad(ROW_PAD, 15, ROW_PAD, 15));
        p.setPreferredSize(new Dimension(10, Ui.tall(52)));
        return p;
    }

    /** The mark on Start attack: a play triangle in a ring, white on the accent. */
    private static Icon circledPlay() {
        java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(14, 14, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setColor(Color.WHITE);
        g.setStroke(new BasicStroke(1.2f));
        g.draw(new java.awt.geom.Ellipse2D.Double(1, 1, 12, 12));
        java.awt.geom.Path2D t = new java.awt.geom.Path2D.Double();
        t.moveTo(5.6, 4.4); t.lineTo(9.6, 7); t.lineTo(5.6, 9.6); t.closePath();
        g.fill(t);
        g.dispose();
        return new ImageIcon(img);
    }

    /** A full-width hairline between the header rows. */
    private static JComponent rule() {
        JPanel r = new JPanel();
        r.setBackground(Ui.GRID);
        r.setPreferredSize(new Dimension(1, 1));
        r.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1));
        r.setAlignmentX(Component.LEFT_ALIGNMENT);
        return r;
    }

    /** The reference's payload position colours: dark red text on a grey block. */
    private static Color markerFill() {
        return opensuite.ui.Theme.dark ? new Color(0x4A, 0x4A, 0x4A) : new Color(0xDE, 0xDE, 0xDE);
    }
    private static Color markerText() {
        return opensuite.ui.Theme.dark ? new Color(0xFF, 0x8A, 0x80) : new Color(0xA0, 0x10, 0x10);
    }

    /**
     * Repaint each marked position over the text the area has already drawn:
     * its block (the selection colour where the selection covers it) and then
     * its text in the marker colour. Only positions that sit on one line are
     * repainted; one that spans lines keeps the highlighter's plain block.
     */
    private void paintMarkerText(Graphics2D g) {
        String s = area.getText();
        int selFrom = area.getSelectionStart(), selTo = area.getSelectionEnd();
        Rectangle clip = g.getClipBounds();
        Graphics2D g2 = (Graphics2D) g.create();
        Object hints = Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints");
        if (hints instanceof java.util.Map<?, ?> m) g2.addRenderingHints(m);
        else opensuite.ui.Theme.textSmoothing(g2);
        g2.setFont(area.getFont());
        FontMetrics fm = g2.getFontMetrics();
        int from = s.indexOf(MARK);
        while (from >= 0) {
            int to = s.indexOf(MARK, from + 1);
            if (to < 0) break;
            try {
                java.awt.geom.Rectangle2D a = area.modelToView2D(from);
                java.awt.geom.Rectangle2D b = area.modelToView2D(to + 1);
                if (a != null && b != null && a.getY() == b.getY()
                        && (clip == null || clip.intersects(a.getX(), a.getY(), b.getX() - a.getX(), a.getHeight()))) {
                    boolean selected = selFrom < selTo && selFrom <= from && selTo >= to + 1;
                    g2.setColor(selected ? area.getSelectionColor() : markerFill());
                    g2.fill(new java.awt.geom.Rectangle2D.Double(a.getX(), a.getY(), b.getX() - a.getX(), a.getHeight()));
                    g2.setColor(markerText());
                    g2.drawString(s.substring(from, to + 1), (float) a.getX(), (float) (a.getY() + fm.getAscent()));
                }
            } catch (javax.swing.text.BadLocationException ignored) {
                // The text changed under the paint; the next repaint is correct.
            }
            from = s.indexOf(MARK, to + 1);
        }
        g2.dispose();
    }

    private static final javax.swing.text.DefaultHighlighter.DefaultHighlightPainter MARKER_PAINT =
            new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(markerFill());
    private static final javax.swing.text.DefaultHighlighter.DefaultHighlightPainter SEARCH_PAINT =
            new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(opensuite.ui.Theme.CONTROL_TINT);

    private int searchHits;
    private int searchAt;

    private void search() { searchAt = 0; paintMarkers(); }

    /** Move the caret to the next or previous search match. */
    private void step(int dir) {
        String q = editorSearch.getText();
        if (q.isEmpty()) return;
        String hay = area.getText().toLowerCase();
        String needle = q.toLowerCase();
        java.util.List<Integer> at = new ArrayList<>();
        int i = hay.indexOf(needle);
        while (i >= 0) { at.add(i); i = hay.indexOf(needle, i + needle.length()); }
        if (at.isEmpty()) return;
        searchAt = (searchAt + dir + at.size()) % at.size();
        int off = at.get(searchAt);
        area.setCaretPosition(off);
        area.select(off, off + needle.length());
        area.requestFocusInWindow();
    }

    /** The editor settings the footer gear offers. */
    private JPopupMenu editorMenu() {
        JPopupMenu m = new JPopupMenu();
        JCheckBoxMenuItem wrap = new JCheckBoxMenuItem("Wrap lines", area.getLineWrap());
        wrap.setFont(Ui.PLAIN);
        wrap.addActionListener(e -> area.setLineWrap(wrap.isSelected()));
        m.add(wrap);
        JMenuItem reset = new JMenuItem("Clear payload positions");
        reset.setFont(Ui.PLAIN);
        reset.addActionListener(e -> clearMarkers());
        m.add(reset);
        return m;
    }
}