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.

23.2 KB
Raw Blame
package opensuite.intruder;

import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Payload processing and payload encoding, laid out as the reference draws
 * them: an ordered list of rules with Add / Edit / Remove / Up / Down beside
 * it, then a separate encoding block.
 *
 * <p>{@link #process} runs a payload through each enabled rule in order and
 * then applies the encoding. A rule that drops the payload returns null, which
 * takes it out of the attack.
 */
public class PayloadProcessor extends JPanel {

    /** The case options shared with the case-substitution generator. */
    static final String[] CASE_OPTIONS = {
            "do not modify", "to lower case", "to upper case", "to Propername", "to ProperName"
    };

    /** What a rule does, in the order the reference lists them. The label is what the list and the table show. */
    enum Kind {
        PREFIX("Add prefix"),
        SUFFIX("Add suffix"),
        MATCH_REPLACE("Match/replace"),
        SUBSTRING("Substring"),
        REVERSE_SUBSTRING("Reverse substring"),
        CASE("Modify case"),
        ENCODE("Encode"),
        DECODE("Decode"),
        HASH("Hash"),
        RAW("Add raw payload"),
        SKIP("Skip if matches regex"),
        EXTENSION("Invoke extension"),
        BASE("Replace placeholder with base value"),
        COLLABORATOR("Replace placeholder with collaborator payload");

        final String label;
        Kind(String label) { this.label = label; }
        @Override public String toString() { return label; }
    }

    /** One processing step: its kind, whether it runs, and its parameters. */
    static final class Rule {
        boolean enabled = true;
        Kind kind;
        String a = "";          // prefix, suffix, regex, placeholder, or the option chosen from the rule's list
        String b = "";          // replacement
        int from, length;       // substring
        boolean location = true;   // a collaborator payload with its server's address, not its identifier alone

        Rule(Kind kind) { this.kind = kind; }

        /** How the rule reads in the table. */
        String describe() {
            return switch (kind) {
                case PREFIX            -> "Add prefix: " + a;
                case SUFFIX            -> "Add suffix: " + a;
                case MATCH_REPLACE     -> "Match [" + a + "] replace with [" + b + "]";
                case SUBSTRING         -> "Substring: from " + from + ", length " + length;
                case REVERSE_SUBSTRING -> "Reverse substring: from " + from + ", length " + length;
                case CASE              -> "Modify case: " + a;
                case ENCODE, DECODE    -> a;
                case HASH              -> "Hash: " + a;
                case RAW               -> a;
                case SKIP              -> "Skip if matches: " + a;
                case EXTENSION         -> "Invoke extension: " + (a.isEmpty() ? "no processor" : a);
                case BASE              -> "Replace placeholder [" + a + "] with base value";
                case COLLABORATOR      -> "Replace placeholder [" + a + "] with collaborator payload";
            };
        }
    }

    private final List<Rule> rules = new ArrayList<>();
    private final RuleModel model = new RuleModel();
    private final JTable table = new JTable(model);

    private final JCheckBox encodeOn = Ui.check("URL-encode these characters:", true);
    private final JTextField urlChars = Ui.field(".\\=<>?+&*;:\"{}|^`#");

    public PayloadProcessor() {
        super(new BorderLayout());
        setOpaque(false);

        Ui.styleTable(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        int enabledWidth = Ui.fontGrowth() > 0 ? 102 : 114;   // each as measured
        table.getColumnModel().getColumn(0).setMinWidth(enabledWidth);
        table.getColumnModel().getColumn(0).setMaxWidth(enabledWidth);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
        // The Enabled title carries a tick box that switches every rule at once.
        table.getColumnModel().getColumn(0).setHeaderRenderer(new EnabledHeader());
        table.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                if (table.columnAtPoint(e.getPoint()) != 0 || rules.isEmpty()) return;
                boolean on = !allEnabled();
                for (Rule r : rules) r.enabled = on;
                model.fireTableDataChanged();
                table.getTableHeader().repaint();
            }
        });
        JScrollPane sp = Ui.scroll(table);
        sp.setPreferredSize(new Dimension(200, 150));

        JButton add    = Ui.button("Add", "Add a processing rule");
        JButton edit   = Ui.button("Edit", "Edit the selected rule");
        JButton remove = Ui.button("Remove", "Delete the selected rule");
        JButton up     = Ui.button("Up", "Run the selected rule earlier");
        JButton down   = Ui.button("Down", "Run the selected rule later");
        add.addActionListener(e -> {
            Rule r = RuleDialog.show(this, null);
            if (r != null) { rules.add(r); model.fireTableDataChanged(); }
        });
        edit.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i < 0) return;
            Rule r = RuleDialog.show(this, rules.get(i));
            if (r != null) { rules.set(i, r); model.fireTableRowsUpdated(i, i); }
        });
        remove.addActionListener(e -> {
            int i = table.getSelectedRow();
            if (i >= 0) { rules.remove(i); model.fireTableDataChanged(); }
        });
        up.addActionListener(e -> move(-1));
        down.addActionListener(e -> move(1));

        JPanel rulesRow = new JPanel(new BorderLayout(5, 0));
        rulesRow.setOpaque(false);
        rulesRow.add(Ui.buttonColumn(add, edit, remove, up, down), BorderLayout.WEST);
        rulesRow.add(sp, BorderLayout.CENTER);

        // The check box stands in for the row's label, so it and the field sit
        // on one line and the field keeps its own height.
        JPanel encoding = new JPanel(new BorderLayout());
        encoding.setOpaque(false);
        encoding.add(Ui.form(encodeOn, urlChars), BorderLayout.NORTH);

        add(opensuite.ui.Sections.column(0,
                opensuite.ui.Sections.fill(Ui.section("Payload processing",
                        "You can define rules to perform various processing tasks on each payload "
                      + "before it is used.", rulesRow)),
                opensuite.ui.Sections.fill(Ui.section("Payload encoding",
                        "This setting can be used to URL-encode selected characters within the final "
                      + "payload, for safe transmission within HTTP requests.", encoding))), BorderLayout.CENTER);
    }

    private boolean allEnabled() {
        if (rules.isEmpty()) return false;
        for (Rule r : rules) if (!r.enabled) return false;
        return true;
    }

    /** The Enabled column's title: a tick box, then the word. */
    private final class EnabledHeader extends JCheckBox implements javax.swing.table.TableCellRenderer {
        EnabledHeader() {
            super("Enabled");
            setFont(Ui.PLAIN);
            setOpaque(true);
            setBackground(opensuite.ui.Theme.HEADER);
            setIconTextGap(11);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(0, 0, 1, 1, opensuite.ui.Theme.BORDER), BorderFactory.createEmptyBorder(4, 8, 4, 0)));
            setBorderPainted(true);
        }
        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean focus, int row, int column) {
            setSelected(allEnabled());
            return this;
        }
    }

    private void move(int delta) {
        int i = table.getSelectedRow();
        int to = i + delta;
        if (i < 0 || to < 0 || to >= rules.size()) return;
        rules.add(to, rules.remove(i));
        model.fireTableDataChanged();
        table.setRowSelectionInterval(to, to);
    }

    /** Enabled / Rule, as the reference labels the two columns. */
    private final class RuleModel extends AbstractTableModel {
        private final String[] cols = {"Enabled", "Rule"};
        @Override public int getRowCount() { return rules.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : String.class; }
        @Override public boolean isCellEditable(int r, int c) { return c == 0; }
        @Override public void setValueAt(Object v, int r, int c) {
            if (c == 0) { rules.get(r).enabled = Boolean.TRUE.equals(v); fireTableRowsUpdated(r, r); }
        }
        @Override public Object getValueAt(int r, int c) {
            Rule rule = rules.get(r);
            return c == 0 ? rule.enabled : rule.describe();
        }
    }

    // ---- running the chain --------------------------------------------------

    /** Where a collaborator payload comes from; the suite sets this, and with none the rule leaves the payload alone. */
    static java.util.function.Supplier<opensuite.oast.Collaborator> collaborator = () -> null;

    /** The processed payload, or null when a rule drops it. */
    public String process(String payload) { return process(payload, ""); }

    /** As {@link #process(String)}, for a position whose own value in the request is {@code base}. */
    public String process(String payload, String base) {
        String s = processPlain(payload, base);
        return s == null ? null : encodeOn.isSelected() ? urlEncode(s, urlChars.getText()) : s;
    }

    /** The payload after its rules but before the URL-encoding of the request; null when a rule drops it. */
    public String processPlain(String payload) { return processPlain(payload, ""); }

    public String processPlain(String payload, String base) {
        String s = payload;
        for (Rule r : rules) {
            if (!r.enabled) continue;
            s = apply(r, s, payload, base);
            if (s == null) return null;
        }
        return s;
    }

    /** Whether a rule that is switched on works from the position's own value, so each position needs its own payloads. */
    public boolean usesBase() {
        for (Rule r : rules) if (r.enabled && r.kind == Kind.BASE) return true;
        return false;
    }

    /**
     * One rule applied to {@code s}. {@code raw} is the payload as it was
     * before any rule, {@code base} the value the position holds in the request.
     */
    static String apply(Rule r, String s, String raw, String base) {
        return switch (r.kind) {
            case PREFIX -> r.a + s;
            case SUFFIX -> s + r.a;
            case MATCH_REPLACE -> PayloadRules.matchReplace(s, r.a, r.b);
            case SUBSTRING -> PayloadRules.substring(s, r.from, r.length);
            case REVERSE_SUBSTRING -> PayloadRules.reverseSubstring(s, r.from, r.length);
            case CASE -> PayloadRules.modifyCase(s, r.a);
            case ENCODE -> PayloadRules.encode(s, r.a);
            case DECODE -> PayloadRules.decode(s, r.a);
            case HASH -> PayloadRules.hash(s, r.a);
            case RAW -> r.a.startsWith("Prepend") ? raw + s : s + raw;
            case SKIP -> skips(s, r.a) ? null : s;
            case EXTENSION -> s;   // no extension defines a processor to hand it to
            case BASE -> r.a.isEmpty() ? s : s.replace(r.a, base == null ? "" : base);
            case COLLABORATOR -> PayloadRules.replaceEach(s, r.a, () -> collaboratorPayload(r.location));
        };
    }

    /** A fresh collaborator payload, starting the collaborator if it is not yet running; null when there is none to be had. */
    private static String collaboratorPayload(boolean withLocation) {
        opensuite.oast.Collaborator c = collaborator.get();
        if (c == null) return null;
        String host = c.payloadHost();
        if (host == null) { c.start(); host = c.payloadHost(); }
        if (host == null) return null;
        int dot = host.indexOf('.');
        return withLocation || dot < 0 ? host : host.substring(0, dot);
    }

    static String urlEncode(String s, String chars) {
        StringBuilder out = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (chars.indexOf(c) >= 0) out.append('%').append(String.format("%02X", (int) c & 0xFF));
            else out.append(c);
        }
        return out.toString();
    }

    static boolean skips(String payload, String regex) {
        if (regex == null || regex.isEmpty()) return false;
        try { return Pattern.compile(regex).matcher(payload).find(); }
        catch (Exception e) { return false; }
    }

    static String urlDecode(String s) {
        try { return java.net.URLDecoder.decode(s, StandardCharsets.ISO_8859_1); }
        catch (Exception e) { return s; }
    }

    static String b64Decode(String s) {
        try { return new String(Base64.getDecoder().decode(s), StandardCharsets.ISO_8859_1); }
        catch (Exception e) { return s; }
    }

    /** Apply one of {@link #CASE_OPTIONS} by index. */
    static String applyCase(String s, int mode) {
        return switch (mode) {
            case 1 -> s.toLowerCase();
            case 2 -> s.toUpperCase();
            case 3 -> properName(s);       // Propername: first letter only
            case 4 -> properCase(s);       // ProperName: each word
            default -> s;
        };
    }

    private static String properName(String s) {
        if (s.isEmpty()) return s;
        return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();
    }

    private static String properCase(String s) {
        StringBuilder out = new StringBuilder(s.length());
        boolean startOfWord = true;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isLetter(c)) {
                out.append(startOfWord ? Character.toUpperCase(c) : Character.toLowerCase(c));
                startOfWord = false;
            } else {
                out.append(c);
                startOfWord = true;
            }
        }
        return out.toString();
    }

    /**
     * Add or edit one rule, laid out as the reference's window: a line of
     * guidance beside a help mark, the rule type across the width, and under
     * it only what that type needs.
     */
    private static final class RuleDialog {
        private static final String PICK = "Select rule type";

        static Rule show(Component parent, Rule existing) {
            JComboBox<Object> kind = new JComboBox<>();
            kind.setFont(Ui.PLAIN);
            if (existing == null) kind.addItem(PICK);
            for (Kind k : Kind.values()) kind.addItem(k);
            kind.setMaximumRowCount(Kind.values().length + 1);   // the whole list at once, with no scrolling

            // Every type has fields of its own, so nothing typed for one shows up in another.
            JTextField prefix = Ui.field(""), suffix = Ui.field(""), match = Ui.field(""), replace = Ui.field(""),
                    from = Ui.field("0"), length = Ui.field("0"), rfrom = Ui.field("0"), rlength = Ui.field("0"),
                    skip = Ui.field(""), basePlaceholder = Ui.field("{base}"), collabPlaceholder = Ui.field("\\{domain\\}");
            JComboBox<String> cases = Ui.combo(PayloadRules.CASES), encodings = Ui.combo(PayloadRules.ENCODINGS),
                    decodings = Ui.combo(PayloadRules.DECODINGS), hashes = Ui.combo(PayloadRules.hashes()),
                    raws = Ui.combo(PayloadRules.RAW), processors = Ui.combo(new String[]{"No processors defined"});
            encodings.setMaximumRowCount(PayloadRules.ENCODINGS.length);
            hashes.setMaximumRowCount(15);
            JCheckBox location = Ui.check("", true);

            if (existing != null) {
                kind.setSelectedItem(existing.kind);
                switch (existing.kind) {
                    case PREFIX -> prefix.setText(existing.a);
                    case SUFFIX -> suffix.setText(existing.a);
                    case MATCH_REPLACE -> { match.setText(existing.a); replace.setText(existing.b); }
                    case SUBSTRING -> { from.setText("" + existing.from); length.setText("" + existing.length); }
                    case REVERSE_SUBSTRING -> { rfrom.setText("" + existing.from); rlength.setText("" + existing.length); }
                    case CASE -> cases.setSelectedItem(existing.a);
                    case ENCODE -> encodings.setSelectedItem(existing.a);
                    case DECODE -> decodings.setSelectedItem(existing.a);
                    case HASH -> hashes.setSelectedItem(existing.a);
                    case RAW -> raws.setSelectedItem(existing.a);
                    case SKIP -> skip.setText(existing.a);
                    case EXTENSION -> { }
                    case BASE -> basePlaceholder.setText(existing.a);
                    case COLLABORATOR -> { collabPlaceholder.setText(existing.a); location.setSelected(existing.location); }
                }
            }

            JPanel fields = new JPanel(new CardLayout());
            fields.setOpaque(false);
            fields.add(card(), PICK);
            fields.add(card(row("Prefix:", prefix)), Kind.PREFIX.name());
            fields.add(card(row("Suffix:", suffix)), Kind.SUFFIX.name());
            fields.add(card(Ui.form("Match regex:", match, "Replace with:", replace)), Kind.MATCH_REPLACE.name());
            fields.add(card(Ui.form("From:", from, "Length:", length)), Kind.SUBSTRING.name());
            fields.add(card(Ui.form("From:", rfrom, "Length:", rlength)), Kind.REVERSE_SUBSTRING.name());
            fields.add(card(cases), Kind.CASE.name());
            fields.add(card(encodings), Kind.ENCODE.name());
            fields.add(card(decodings), Kind.DECODE.name());
            fields.add(card(hashes), Kind.HASH.name());
            fields.add(card(raws), Kind.RAW.name());
            fields.add(card(row("Match regex:", skip)), Kind.SKIP.name());
            fields.add(card(row("Select processor:", processors)), Kind.EXTENSION.name());
            fields.add(card(row("Placeholder to replace:", basePlaceholder)), Kind.BASE.name());
            fields.add(card(Ui.form("Placeholder regex to replace:", collabPlaceholder,
                    "Include Collaborator server location:", location)), Kind.COLLABORATOR.name());

            JButton ok = Ui.button("OK", null), cancel = Ui.button("Cancel", null);
            Dimension buttonSize = new Dimension(86, 26 + 2 * Ui.fontGrowth());
            ok.setPreferredSize(buttonSize); cancel.setPreferredSize(buttonSize);
            Runnable showCard = () -> {
                Object k = kind.getSelectedItem();
                ((CardLayout) fields.getLayout()).show(fields, k instanceof Kind kk ? kk.name() : PICK);
                ok.setEnabled(k instanceof Kind);
            };
            kind.addActionListener(e -> showCard.run());
            showCard.run();

            JLabel help = new JLabel(opensuite.ui.Glyphs.help());
            help.setVerticalAlignment(SwingConstants.TOP);
            help.setBorder(Ui.pad(0, 0, 0, 10));
            JPanel middle = new JPanel(new BorderLayout(0, 6));
            middle.setOpaque(false);
            middle.add(kind, BorderLayout.NORTH);
            middle.add(fields, BorderLayout.CENTER);
            JPanel top = new JPanel(new BorderLayout(0, 18));
            top.setOpaque(false);
            top.add(Ui.label("Enter the details of the payload processing rule."), BorderLayout.NORTH);
            top.add(middle, BorderLayout.CENTER);
            JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
            buttons.setOpaque(false);
            buttons.add(ok); buttons.add(cancel);
            JPanel body = new JPanel(new BorderLayout(0, 10));
            body.setBackground(opensuite.ui.Theme.BG);
            body.setBorder(Ui.pad(18, 16, 14, 10));
            body.add(help, BorderLayout.WEST);
            body.add(top, BorderLayout.CENTER);
            body.add(buttons, BorderLayout.SOUTH);

            JDialog d = new JDialog(SwingUtilities.getWindowAncestor(parent),
                    existing == null ? "Add payload processing rule" : "Edit payload processing rule", Dialog.ModalityType.APPLICATION_MODAL);
            d.setContentPane(body);
            d.setSize(600 + 40 * Ui.fontGrowth(), 300 + 20 * Ui.fontGrowth());
            d.setLocationRelativeTo(SwingUtilities.getWindowAncestor(parent));
            boolean[] accepted = {false};
            ok.addActionListener(e -> { accepted[0] = true; d.dispose(); });
            cancel.addActionListener(e -> d.dispose());
            d.getRootPane().setDefaultButton(ok);
            d.getRootPane().registerKeyboardAction(e -> d.dispose(), KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_IN_FOCUSED_WINDOW);
            d.setVisible(true);
            if (!accepted[0] || !(kind.getSelectedItem() instanceof Kind k)) return null;

            Rule r = new Rule(k);
            r.enabled = existing == null || existing.enabled;
            switch (k) {
                case PREFIX -> r.a = prefix.getText();
                case SUFFIX -> r.a = suffix.getText();
                case MATCH_REPLACE -> { r.a = match.getText(); r.b = replace.getText(); }
                case SUBSTRING -> { r.from = number(from); r.length = number(length); }
                case REVERSE_SUBSTRING -> { r.from = number(rfrom); r.length = number(rlength); }
                case CASE -> r.a = String.valueOf(cases.getSelectedItem());
                case ENCODE -> r.a = String.valueOf(encodings.getSelectedItem());
                case DECODE -> r.a = String.valueOf(decodings.getSelectedItem());
                case HASH -> r.a = String.valueOf(hashes.getSelectedItem());
                case RAW -> r.a = String.valueOf(raws.getSelectedItem());
                case SKIP -> r.a = skip.getText();
                case EXTENSION -> { }
                case BASE -> r.a = basePlaceholder.getText();
                case COLLABORATOR -> { r.a = collabPlaceholder.getText(); r.location = location.isSelected(); }
            }
            return r;
        }

        private static int number(JTextField f) {
            try { return Math.max(0, Integer.parseInt(f.getText().strip())); }
            catch (NumberFormatException e) { return 0; }
        }

        /** A label and its box on one line, the box taking the rest of the width. */
        private static JPanel row(String label, JComponent box) {
            JPanel p = new JPanel(new BorderLayout(5, 0));
            p.setOpaque(false);
            p.add(Ui.label(label), BorderLayout.WEST);
            p.add(box, BorderLayout.CENTER);
            return p;
        }

        /** What a rule type shows, kept to the top of the space under the type. */
        private static JPanel card(JComponent... content) {
            JPanel p = new JPanel(new BorderLayout());
            p.setOpaque(false);
            if (content.length > 0) p.add(content[0], BorderLayout.NORTH);
            return p;
        }
    }
}