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.

11.4 KB
Raw Blame
package opensuite.proxy;

import opensuite.ui.Glyphs;
import opensuite.ui.Sections;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.List;
import java.util.function.Supplier;

/**
 * The Proxy's match and replace rules: one section for HTTP messages and one
 * for WebSocket messages. Each is a table of rules with Add, Edit, Remove, Up
 * and Down beside it; a rule is written and changed in a small dialog.
 */
public class MatchReplacePanel extends JPanel {

    private final ProxyServer server;

    public MatchReplacePanel(ProxyServer server) {
        super(new BorderLayout());
        this.server = server;
        setOpaque(false);

        JCheckBox httpScope = Ui.check("Only apply to in-scope items", server.matchReplaceInScopeOnly);
        httpScope.addActionListener(e -> server.matchReplaceInScopeOnly = httpScope.isSelected());
        JCheckBox wsScope = Ui.check("Only apply to in-scope items", server.wsMatchReplaceInScopeOnly);
        wsScope.addActionListener(e -> server.wsMatchReplaceInScopeOnly = wsScope.isSelected());

        Model http = new Model(server.matchReplace, false);
        Model ws = new Model(server.wsMatchReplace, true);
        for (JCheckBox c : new JCheckBox[] { httpScope, wsScope }) {
            c.setBorder(Ui.pad(0, 2, 0, 0));
            c.setPreferredSize(new Dimension(c.getPreferredSize().width + 2, 21));
        }
        JComponent httpRules = rules(http, false, 786, 59, 95, 130, 130, 165, 46, 148);
        JComponent wsRules = rules(ws, true, 654, 60, 96, 131, 168, 48, 149);

        add(Sections.page(
                Sections.section("HTTP match and replace rules",
                        "Use these settings to automatically replace parts of HTTP requests and responses passing through the Proxy.",
                        options(() -> { server.matchReplace.clear(); server.matchReplace.addAll(MatchReplaceRule.defaults());
                                        http.fireTableDataChanged(); }), null,
                        httpScope, Sections.gap(12), httpRules),
                Sections.section("WebSocket match and replace rules",
                        "Use these settings to automatically replace parts of WebSocket messages passing through the Proxy.",
                        options(() -> { server.wsMatchReplace.clear(); ws.fireTableDataChanged(); }), null,
                        wsScope, Sections.gap(12), wsRules)), BorderLayout.CENTER);
    }

    /**
     * One kind's switch and rules table on their own, for the Proxy settings
     * page. The table rereads the shared rules whenever it comes into view, so
     * it agrees with the copy on the Proxy's own tab.
     */
    static JComponent block(ProxyServer server, boolean ws) {
        MatchReplacePanel owner = new MatchReplacePanel(server, true);
        JCheckBox scope = Ui.check("Only apply to in-scope items", ws ? server.wsMatchReplaceInScopeOnly : server.matchReplaceInScopeOnly);
        scope.addActionListener(e -> { if (ws) server.wsMatchReplaceInScopeOnly = scope.isSelected(); else server.matchReplaceInScopeOnly = scope.isSelected(); });
        scope.setBorder(Ui.pad(0, 2, 0, 0));
        scope.setPreferredSize(new Dimension(scope.getPreferredSize().width + 2, 21));
        Model model = new Model(ws ? server.wsMatchReplace : server.matchReplace, ws);
        JComponent rules = ws ? owner.rules(model, true, 654, 60, 96, 131, 168, 48, 149)
                              : owner.rules(model, false, 786, 59, 95, 130, 130, 165, 46, 148);
        JPanel col = Sections.column(0, scope, Sections.gap(12), rules);
        col.addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0 && col.isShowing()) {
                scope.setSelected(ws ? server.wsMatchReplaceInScopeOnly : server.matchReplaceInScopeOnly);
                model.fireTableDataChanged();
            }
        });
        return col;
    }

    /** Only the server, for {@link #block}. */
    private MatchReplacePanel(ProxyServer server, boolean bare) {
        super(new BorderLayout());
        this.server = server;
        setOpaque(false);
    }

    /** The gear under a section's help mark: a menu that puts the section back as it shipped. */
    private static JButton options(Runnable restore) {
        JButton b = Glyphs.button(Glyphs.gear(21, Theme.TEXT), "Options", null);
        b.setBorder(null);
        b.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            JMenuItem item = new JMenuItem("Restore defaults");
            item.setFont(Ui.PLAIN);
            item.addActionListener(x -> restore.run());
            m.add(item);
            m.show(b, 0, b.getHeight());
        });
        return b;
    }

    /** One rules table with its buttons. */
    private JComponent rules(Model model, boolean ws, int width, int... widths) {
        JTable table = new JTable(model);
        Ui.styleTable(table);
        Ui.exactWidths(table, widths);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JButton add = Ui.button("Add", "add a rule");
        JButton edit = Ui.button("Edit", "Change the selected rule");
        JButton remove = Ui.button("Remove", "Remove the selected rule");
        JButton up = Ui.button("Up", "Move the selected rule earlier");
        JButton down = Ui.button("Down", "Move the selected rule later");

        Supplier<Integer> sel = table::getSelectedRow;
        add.addActionListener(e -> {
            MatchReplaceRule r = dialog(null, ws);
            if (r != null) { model.rules.add(r); model.fireTableDataChanged(); }
        });
        Runnable doEdit = () -> {
            int i = sel.get();
            if (i < 0 || i >= model.rules.size()) return;
            MatchReplaceRule r = dialog(model.rules.get(i), ws);
            if (r != null) { model.rules.set(i, r); model.fireTableRowsUpdated(i, i); }
        };
        edit.addActionListener(e -> doEdit.run());
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2 && table.columnAtPoint(e.getPoint()) > 0) doEdit.run();
            }
        });
        remove.addActionListener(e -> {
            int i = sel.get();
            if (i >= 0 && i < model.rules.size()) { model.rules.remove(i); model.fireTableDataChanged(); }
        });
        up.addActionListener(e -> move(model, table, -1));
        down.addActionListener(e -> move(model, table, 1));

        return Sections.besideTable(Ui.buttonColumn(add, edit, remove, up, down),
                Sections.withArrow(Ui.scroll(table), width, 150));
    }

    /** Swap the selected rule with its neighbour, keeping the selection on it. */
    private static void move(Model model, JTable table, int delta) {
        int i = table.getSelectedRow();
        int j = i + delta;
        if (i < 0 || j < 0 || j >= model.rules.size()) return;
        MatchReplaceRule tmp = model.rules.get(i);
        model.rules.set(i, model.rules.get(j));
        model.rules.set(j, tmp);
        model.fireTableDataChanged();
        table.getSelectionModel().setSelectionInterval(j, j);
    }

    /** Ask for a rule; returns null when cancelled. */
    private MatchReplaceRule dialog(MatchReplaceRule from, boolean ws) {
        String[] types = ws ? MatchReplaceRule.WS_TYPES : MatchReplaceRule.TYPES;
        String[] shown = new String[types.length];
        for (int i = 0; i < types.length; i++) shown[i] = MatchReplaceRule.shown(types[i]);
        JComboBox<String> type = Ui.combo(shown);
        JTextField name = Ui.field(from == null ? "" : from.name);
        JTextField match = Ui.field(from == null ? "" : from.match);
        JTextField replace = Ui.field(from == null ? "" : from.replace);
        JTextField comment = Ui.field(from == null ? "" : from.comment);
        JCheckBox regex = Ui.check("Regex match", from == null || !from.literal);
        if (from != null) for (int i = 0; i < types.length; i++) if (types[i].equals(from.type)) type.setSelectedIndex(i);
        for (JTextField f : new JTextField[] { name, match, replace, comment }) f.setColumns(30);
        match.setToolTipText(ws ? "Text to match in a message" : "Text to match; leave blank to add a new header");
        replace.setToolTipText(ws ? "Replacement text" : "Replacement text; leave blank to remove a matched header");

        JPanel form = ws
                ? Ui.form("Direction:", type, "Match:", match, "Replace:", replace, "Comment:", comment, "", regex)
                : Ui.form("Type:", type, "Name:", name, "Match:", match, "Replace:", replace, "Comment:", comment, "", regex);
        String title = (from == null ? "Add" : "Edit") + (ws ? " WebSocket" : "") + " match/replace rule";
        if (JOptionPane.showConfirmDialog(this, form, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)
                != JOptionPane.OK_OPTION) return null;
        if (ws && match.getText().isBlank()) return null;
        MatchReplaceRule r = new MatchReplaceRule(from == null || from.enabled, types[type.getSelectedIndex()],
                match.getText(), replace.getText(), comment.getText());
        r.name = name.getText();
        r.literal = !regex.isSelected();
        return r;
    }

    /** A rule list as a table. Only the tick is edited in place; the rest goes through the dialog. */
    private static final class Model extends AbstractTableModel {
        private final String[] cols;
        private final List<MatchReplaceRule> rules;
        private final boolean ws;
        Model(List<MatchReplaceRule> rules, boolean ws) {
            this.rules = rules;
            this.ws = ws;
            this.cols = ws ? new String[] { "Enabled", "Direction", "Match", "Replace", "Type", "Comment" }
                           : new String[] { "Enabled", "Item", "Name", "Match", "Replace", "Type", "Comment" };
        }
        @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 Object getValueAt(int r, int c) {
            MatchReplaceRule x = rules.get(r);
            String kind = x.literal ? "Literal" : "Regex";
            if (ws) return switch (c) {
                case 0 -> x.enabled;
                case 1 -> MatchReplaceRule.shown(x.type);
                case 2 -> x.match;
                case 3 -> x.replace;
                case 4 -> kind;
                default -> x.comment;
            };
            return switch (c) {
                case 0 -> x.enabled;
                case 1 -> MatchReplaceRule.shown(x.type);
                case 2 -> x.name == null ? "" : x.name;
                case 3 -> x.match;
                case 4 -> x.replace;
                case 5 -> kind;
                default -> x.comment;
            };
        }

        @Override public void setValueAt(Object v, int r, int c) {
            if (c != 0) return;
            MatchReplaceRule x = rules.get(r);
            x.enabled = Boolean.TRUE.equals(v);
            if (rules instanceof java.util.concurrent.CopyOnWriteArrayList<MatchReplaceRule> cow) cow.set(r, x);
            fireTableRowsUpdated(r, r);
        }
    }
}