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.7 KB
Raw Blame
package opensuite.intruder;

import opensuite.core.HttpMode;
import opensuite.ui.OptionsPage;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * The options tab: concurrency, redirect handling, and the response analysis
 * (grep-match, grep-extract and grep-payloads) whose rules each become a
 * column in the results table.
 */
public class OptionsPanel extends OptionsPage {

    // The reference's default flag list: common error, SQL and stack-trace markers.
    private static final String[] DEFAULT_GREP = {
        "error", "exception", "illegal", "invalid", "fail", "stack", "access",
        "directory", "file", "not found", "unknown", "SQL", "ODBC", "syntax", "ORA-"
    };

    // Request headers.
    private final JCheckBox updateContentLength = Ui.check("update Content-Length header", true);
    private final JCheckBox setConnectionHeader = Ui.check("Set Connection header", true);

    // Error handling.
    private final JTextField retries = Ui.shortField("3");
    private final JTextField retryPause = Ui.shortField("2000");

    // Attack results.
    private final JCheckBox storeRequests = Ui.check("store requests", true);
    private final JCheckBox storeResponses = Ui.check("store responses", true);
    private final JCheckBox storeFullPayloads = Ui.check("Store full payloads", false);   // off by default, as the reference
    private final JCheckBox saveToProject = Ui.check("Save attack to project file", false);
    private final JCheckBox baselineRequest = Ui.check("make unmodified baseline request", true);
    private final JCheckBox dosMode = Ui.check("use denial-of-service mode (no results)", false);

    // Auto-pause: pause the attack when an expression of its own list appears (or is missing).
    private final JCheckBox autoPause = Ui.check("enable auto-pause", false);
    private final JRadioButton pauseAppears = Ui.radio("Pause if an expression in the list appears in a response", true);
    private final JRadioButton pauseMissing = Ui.radio("Pause if an expression in the list is missing from a response", false);
    private final ExpressionList pauseList = new ExpressionList();
    private final JRadioButton pauseSimple = Ui.radio("Simple string", true);
    private final JRadioButton pauseRegex = Ui.radio("Regex", false);
    private final JCheckBox pauseCase = Ui.check("Case-sensitive match", false);

    // Grep - Match.
    private final JCheckBox flagMatches = Ui.check("Flag responses matching these expressions:", false);
    private final ExpressionList grepList = new ExpressionList(DEFAULT_GREP);
    private final JRadioButton matchSimple = Ui.radio("Simple string", true);
    private final JRadioButton matchRegex = Ui.radio("Regex", false);
    private final JCheckBox matchCase = Ui.check("case sensitive match", false);
    private final JCheckBox matchNoHeaders = Ui.check("exclude HTTP headers", true);

    // Grep - Extract.
    private final JCheckBox extractOn = Ui.check("Extract the following items from responses:", false);
    private final List<ResponseGrep.Extract> extracts = new ArrayList<>();
    private final DefaultTableModel extractModel =
            new DefaultTableModel(new Object[]{"Extract"}, 0) {
                @Override public boolean isCellEditable(int r, int c) { return false; }
            };
    private final JTable extractTable = new JTable(extractModel);
    private final JTextField extractMax = Ui.shortField("100");

    // Grep - Payloads.
    private final JCheckBox payloadGrep = Ui.check("search responses for payload strings", false);
    private final JCheckBox payloadCase = Ui.check("case sensitive match", false);
    private final JCheckBox payloadNoHeaders = Ui.check("exclude HTTP headers", false);
    private final JCheckBox payloadPreEncoded = Ui.check("Match against pre-URL-encoded payloads", true);

    // Redirections.
    private final JRadioButton[] follow = {
        Ui.radio("Never", true), Ui.radio("On-site only", false), Ui.radio("In-scope only", false), Ui.radio("Always", false) };
    private final JCheckBox redirectCookies = Ui.check("Process cookies in redirections", false);

    // HTTP/1 connection reuse and HTTP version: each follows the project unless overridden here.
    private final opensuite.ui.SmallSwitch h1Override = new opensuite.ui.SmallSwitch(true);
    private final JCheckBox h1Reuse = Ui.check("Reuse HTTP/1 connections if the server supports it", true);
    private final opensuite.ui.SmallSwitch h2Override = new opensuite.ui.SmallSwitch(false);
    private final JCheckBox h2Default = Ui.check("Default to HTTP/2 if the server supports it", true);

    public OptionsPanel() {
        // In the reference's order. Each section's second gutter mark puts it
        // back as a new attack has it.
        restore = () -> saveToProject.setSelected(false);
        JPanel save = section("Save attack",
                Ui.note("Use this setting to save the attack with the project when it finishes. A saved attack is stored in a folder "
                        + "alongside the project file and can be reopened from Intruder > Open saved attack."),
                saveToProject);
        // The reference's first heading shares its line with a button and so
        // stands 3px lower with 5px more beneath; the same room is left here
        // so every section after it lands on the same row.
        save.setBorder(Ui.pad(11, opensuite.ui.Sections.MARGIN, 20, opensuite.ui.Sections.MARGIN));
        restore = () -> { updateContentLength.setSelected(true); setConnectionHeader.setSelected(true); };
        section("Request headers",
                Ui.note("These settings control whether Intruder updates the configured request headers during attacks."),
                updateContentLength, setConnectionHeader);
        restore = () -> { retries.setText("3"); retryPause.setText("2000"); };
        section("Error handling",
                Ui.note("These settings control how Intruder handles network errors during the attack."),
                OptionsPage.fieldRow("Number of retries on network failure:", retries, ""),
                OptionsPage.fieldRow("Pause before retry (milliseconds):", retryPause, ""));
        restore = () -> { storeRequests.setSelected(true); storeResponses.setSelected(true); storeFullPayloads.setSelected(false);
                          baselineRequest.setSelected(true); dosMode.setSelected(false); };
        section("Attack results",
                Ui.note("These settings control what information is captured in attack results."),
                storeRequests, storeResponses, baselineRequest, dosMode, storeFullPayloads);

        group(pauseAppears, pauseMissing);
        group(pauseSimple, pauseRegex);
        group(matchSimple, matchRegex);
        group(follow);
        autoPause.addActionListener(e -> syncAutoPause());
        syncAutoPause();
        restore = () -> { autoPause.setSelected(false); pauseAppears.setSelected(true); pauseList.set();
                          pauseSimple.setSelected(true); pauseCase.setSelected(false); syncAutoPause(); };
        JPanel pauseOptions = new JPanel(new BorderLayout(22, 0));
        pauseOptions.setOpaque(false);
        JLabel optionsLabel = Ui.label("Options:");
        optionsLabel.setVerticalAlignment(SwingConstants.TOP);
        optionsLabel.setBorder(Ui.pad(3, 0, 0, 0));
        pauseOptions.add(optionsLabel, BorderLayout.WEST);
        pauseOptions.add(stack(pauseAppears, pauseMissing), BorderLayout.CENTER);
        section("Auto-pause attack",
                Ui.note("Use this setting to automatically pause the attack when a specified expression "
                        + "appears or is missing in a response."),
                autoPause, opensuite.ui.Sections.gap(5), pauseOptions,
                opensuite.ui.Sections.gap(5), opensuite.ui.Sections.fill(pauseList.panel()),
                opensuite.ui.Sections.gap(10), beside("Match type:", stack(pauseSimple, pauseRegex)),
                opensuite.ui.Sections.gap(5), pauseCase);

        restore = () -> { flagMatches.setSelected(false); grepList.set(DEFAULT_GREP);
                          matchSimple.setSelected(true); matchCase.setSelected(false); matchNoHeaders.setSelected(true); };
        section("Grep - Match",
                Ui.note("These settings can be used to flag result items containing specified expressions."),
                flagMatches, opensuite.ui.Sections.gap(5), opensuite.ui.Sections.fill(grepList.panel()),
                opensuite.ui.Sections.gap(10), beside("Match type:", stack(matchSimple, matchRegex)),
                opensuite.ui.Sections.gap(5), matchCase, matchNoHeaders);

        Ui.styleTable(extractTable);
        extractTable.setTableHeader(null);
        JScrollPane xsp = Ui.scroll(extractTable);
        xsp.setPreferredSize(new Dimension(200, 110));
        JButton xAdd    = Ui.button("Add");
        JButton xEdit   = Ui.button("Edit");
        JButton xRemove = Ui.button("Remove");
        JButton xDup    = Ui.button("Duplicate");
        JButton xUp     = Ui.button("Up");
        JButton xDown   = Ui.button("Down");
        JButton xClear  = Ui.button("Clear");
        xAdd.addActionListener(e -> editExtract(-1));
        xEdit.addActionListener(e -> editExtract(extractTable.getSelectedRow()));
        xRemove.addActionListener(e -> {
            int[] rows = extractTable.getSelectedRows();
            for (int i = rows.length - 1; i >= 0; i--) extracts.remove(rows[i]);
            refreshExtracts();
        });
        xDup.addActionListener(e -> {
            int r = extractTable.getSelectedRow();
            if (r >= 0 && r < extracts.size()) { extracts.add(r + 1, extracts.get(r)); refreshExtracts(); selectExtract(r + 1); }
        });
        xUp.addActionListener(e -> moveExtract(extractTable.getSelectedRow(), -1));
        xDown.addActionListener(e -> moveExtract(extractTable.getSelectedRow(), 1));
        xClear.addActionListener(e -> { extracts.clear(); refreshExtracts(); });
        extractTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) editExtract(extractTable.getSelectedRow());
            }
        });
        JPanel extractPanel = new JPanel(new BorderLayout(5, 0));
        extractPanel.setOpaque(false);
        extractPanel.add(Ui.buttonColumn(xAdd, xEdit, xRemove, xDup, xUp, xDown, xClear), BorderLayout.WEST);
        extractPanel.add(xsp, BorderLayout.CENTER);
        restore = () -> { extractOn.setSelected(false); extracts.clear(); refreshExtracts(); extractMax.setText("100"); };
        section("Grep - Extract",
                Ui.note("These settings can be used to extract useful information from responses into the attack results table."),
                extractOn, opensuite.ui.Sections.gap(5), opensuite.ui.Sections.fill(extractPanel),
                opensuite.ui.Sections.gap(5), OptionsPage.fieldRow("Maximum capture length:", extractMax, ""));

        payloadGrep.addActionListener(e -> syncPayloadGrep());
        syncPayloadGrep();
        restore = () -> { payloadGrep.setSelected(false); payloadCase.setSelected(false); payloadNoHeaders.setSelected(false);
                          payloadPreEncoded.setSelected(true); syncPayloadGrep(); };
        for (JCheckBox c : new JCheckBox[] { payloadCase, payloadNoHeaders, payloadPreEncoded, h1Reuse, h2Default }) {
            // Set in beside its section's rows, each on the same 20px line as they are.
            c.setBorder(Ui.pad(0, 2, 0, 0));
            c.setPreferredSize(new Dimension(c.getPreferredSize().width, Ui.tall(20)));
        }
        section("Grep - Payloads",
                Ui.note("These settings can be used to flag result items containing reflections of the submitted payload."),
                payloadGrep,
                OptionsPage.indent(payloadCase, 17),
                OptionsPage.indent(payloadNoHeaders, 17),
                OptionsPage.indent(payloadPreEncoded, 17));

        restore = () -> { follow[0].setSelected(true); redirectCookies.setSelected(false); };
        section("Redirections",
                Ui.note("These settings control how Intruder handles redirections when performing attacks."),
                beside("Follow redirections:", stack(follow)),
                redirectCookies);

        h1Override.setOnToggle(this::syncOverrides);
        h2Override.setOnToggle(this::syncOverrides);
        syncOverrides();
        restore = () -> { h1Override.setOn(true); h1Reuse.setSelected(true); syncOverrides(); };
        section("HTTP/1 connection reuse",
                Ui.note("Use this setting to control whether Intruder reuses the same connection for multiple HTTP/1 "
                        + "requests during this attack. This can increase the speed of the attack."),
                opensuite.ui.Sections.fill(overrideRow(h1Override, "Override the project-level HTTP/1 setting")),
                opensuite.ui.Sections.gap(10), OptionsPage.indent(h1Reuse, 16));
        restore = () -> { h2Override.setOn(false); h2Default.setSelected(true); syncOverrides(); };
        section("HTTP version",
                Ui.note("Use this setting to control whether Intruder defaults to HTTP/1 or HTTP/2 for outbound "
                        + "connections over TLS during this attack."),
                opensuite.ui.Sections.fill(overrideRow(h2Override, "Override the project-level HTTP/2 setting")),
                opensuite.ui.Sections.gap(10), OptionsPage.indent(h2Default, 16));
        restore = null;
        // The reference lays this pane out a little wider than the panel shows
        // and lets it scroll sideways, so its paragraphs break where they do there.
        setMinWidth(MIN_WIDTH);
        setWheelStep(25);   // the reference moves 25px a notch here
    }

    /** The width the pane is laid out at when the panel is narrower. */
    private static final int MIN_WIDTH = 500;

    private static void group(JRadioButton... radios) {
        ButtonGroup g = new ButtonGroup();
        for (JRadioButton r : radios) g.add(r);
    }

    /** Radios one under another, on the rhythm of the tick boxes. */
    private static JPanel stack(JRadioButton... radios) {
        for (JRadioButton r : radios) r.setPreferredSize(new Dimension(r.getPreferredSize().width, Ui.tall(20)));
        return opensuite.ui.Sections.column(5, radios);
    }

    /** A label with its choices to the right, the label level with the first of them. */
    private static JPanel beside(String label, JComponent choices) {
        JPanel p = new JPanel(new BorderLayout(5, 0));
        p.setOpaque(false);
        JLabel l = Ui.label(label);
        l.setVerticalAlignment(SwingConstants.TOP);
        l.setBorder(Ui.pad(Ui.fontGrowth() == 0 ? 3 : 2, 0, 0, 0));
        p.add(l, BorderLayout.WEST);
        p.add(choices, BorderLayout.CENTER);
        return p;
    }

    /** The boxed line that says whether this attack overrides a project-level setting. */
    private static JPanel overrideRow(opensuite.ui.SmallSwitch sw, String label) {
        JLabel text = Ui.label(label);
        text.setForeground(opensuite.ui.Theme.TEXT);
        text.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { sw.dispatchEvent(SwingUtilities.convertMouseEvent(text, e, sw)); }
        });
        JPanel p = new JPanel(null) {
            @Override public void doLayout() {
                sw.setBounds(13, (getHeight() - opensuite.ui.SmallSwitch.HEIGHT) / 2, opensuite.ui.SmallSwitch.WIDTH, opensuite.ui.SmallSwitch.HEIGHT);
                int x = 47 + 2 * Ui.fontGrowth();
                text.setBounds(x, 0, Math.max(0, getWidth() - x - 1), getHeight());
            }
        };
        p.setBackground(opensuite.ui.Theme.CONTENT);
        p.setBorder(BorderFactory.createLineBorder(opensuite.ui.Theme.BORDER));
        p.setPreferredSize(new Dimension(300, Ui.tall(42)));
        p.add(sw);
        p.add(text);
        return p;
    }

    /** A setting the project decides is shown as the project has it, and cannot be changed here. */
    private void syncOverrides() {
        h1Reuse.setEnabled(h1Override.isOn());
        h2Default.setEnabled(h2Override.isOn());
    }

    /** What the next section's restore mark does; set just before each {@link #section} call. */
    private Runnable restore;

    @Override protected JComponent secondMark(String title) {
        final Runnable r = restore;
        if (r == null) return null;
        JButton b = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.restore(21, opensuite.ui.Theme.TEXT),
                "Restore this section's defaults", r);
        b.setBorder(Ui.pad(6, 0, 0, 0));
        return b;
    }

    private void syncAutoPause() {
        // The choices stay live either way, as the reference leaves them.
        pauseAppears.setEnabled(true);
        pauseMissing.setEnabled(true);
    }

    private void selectExtract(int row) {
        if (row >= 0 && row < extractTable.getRowCount()) extractTable.setRowSelectionInterval(row, row);
    }

    private void moveExtract(int row, int delta) {
        int to = row + delta;
        if (row < 0 || to < 0 || to >= extracts.size()) return;
        ResponseGrep.Extract moved = extracts.remove(row);
        extracts.add(to, moved);
        refreshExtracts();
        selectExtract(to);
    }

    private void syncPayloadGrep() {
        boolean on = payloadGrep.isSelected();
        payloadCase.setEnabled(on);
        payloadNoHeaders.setEnabled(on);
        payloadPreEncoded.setEnabled(on);
    }

    private void refreshExtracts() {
        extractModel.setRowCount(0);
        for (ResponseGrep.Extract x : extracts) {
            String name = x.name() == null || x.name().isBlank() ? "" : x.name().trim() + ": ";
            extractModel.addRow(new Object[]{name + describe(x)});
        }
    }

    /** A one-line summary of what a rule extracts, for the rule table. */
    static String describe(ResponseGrep.Extract x) {
        if (x.regex() != null && !x.regex().isEmpty()) return "regex: " + x.regex();
        String start = x.startAfter() == null || x.startAfter().isEmpty()
                ? "from the start" : "after \"" + x.startAfter() + "\"";
        String end = x.endAt() == null || x.endAt().isEmpty()
                ? "to the end of the line" : "up to \"" + x.endAt() + "\"";
        return start + " " + end;
    }

    /** Add a rule (row below zero) or edit the one at {@code row}. */
    private void editExtract(int row) {
        ResponseGrep.Extract cur = row >= 0 && row < extracts.size() ? extracts.get(row) : null;
        if (row >= 0 && cur == null) return;

        JTextField name = Ui.field(cur == null ? "" : cur.name());
        JTextField start = Ui.field(cur == null ? "" : cur.startAfter());
        JTextField end = Ui.field(cur == null ? "" : cur.endAt());
        JTextField regex = Ui.field(cur == null ? "" : cur.regex());
        JCheckBox cs = Ui.check("case sensitive match", cur != null && cur.caseSensitive());
        JCheckBox noHeaders = Ui.check("exclude HTTP headers", cur != null && cur.excludeHeaders());

        JPanel form = Ui.form(
                "column name:", name,
                "start after expression:", start,
                "end at delimiter:", end,
                "or extract by regex:", regex);
        JPanel body = Ui.vbox(
                Ui.note("Specify the expression that precedes the value and the delimiter "
                        + "that terminates it, or a regex whose first capture group is the value. Without an "
                        + "end delimiter, the value extends to the end of the line."),
                form, cs, noHeaders);
        int ok = JOptionPane.showConfirmDialog(this, body, "Define extract grep item",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return;
        if (start.getText().isEmpty() && regex.getText().isEmpty()) return;

        int limit = intOf(extractMax, 100);
        ResponseGrep.Extract x = new ResponseGrep.Extract(name.getText().trim(), start.getText(),
                end.getText(), regex.getText(), cs.isSelected(), noHeaders.isSelected(), limit);
        if (cur == null) extracts.add(x); else extracts.set(row, x);
        extractOn.setSelected(true);   // a rule just written is meant to be used
        refreshExtracts();
    }

    // ---------------- accessors ----------------

    /** Start from the suite-wide defaults kept under Settings > Intruder. */
    public void applyDefaults(opensuite.core.Settings s) {
        follow[s.getBool(IntruderSettingsPanel.REDIRECTS_KEY, false) ? 3 : 0].setSelected(true);
    }

    public boolean followRedirects() { return !follow[0].isSelected(); }

    /**
     * Whether the attack should go over HTTP/2 where the server speaks it:
     * this attack's own choice when it overrides the project's setting, else
     * the project's. Otherwise it is sent as byte-exact HTTP/1.
     */
    public boolean prefersHttp2(opensuite.core.Settings project) {
        return h2Override.isOn() ? h2Default.isSelected()
                : project == null || project.getBool(opensuite.core.NetworkConfig.HTTP2_DEFAULT, true);
    }

    private static int intOf(JTextField f, int def) {
        try { return Math.max(0, Integer.parseInt(f.getText().trim())); } catch (Exception e) { return def; }
    }

    /** The error-handling, header and result-capture options, bundled for the attack engine. */
    public AttackEngine.Options engineOptions() {
        AttackEngine.Options o = new AttackEngine.Options();
        o.updateContentLength = updateContentLength.isSelected();
        o.setConnectionHeader = setConnectionHeader.isSelected();
        o.retries = intOf(retries, 3);
        o.retryPauseMs = intOf(retryPause, 2000);
        o.storeRequests = storeRequests.isSelected();
        o.storeResponses = storeResponses.isSelected();
        o.storeFullPayloads = storeFullPayloads.isSelected();
        o.saveToProject = saveToProject.isSelected();
        o.baselineRequest = baselineRequest.isSelected();
        o.dosMode = dosMode.isSelected();
        o.autoPause = autoPause.isSelected();
        o.pauseOnMissing = autoPause.isSelected() && pauseMissing.isSelected();
        o.pauseExpressions = pauseList.items();
        o.pauseRegex = pauseRegex.isSelected();
        o.pauseCaseSensitive = pauseCase.isSelected();
        o.redirects = follow[1].isSelected() ? "onsite" : follow[2].isSelected() ? "inscope" : follow[3].isSelected() ? "always" : "never";
        o.cookiesInRedirects = redirectCookies.isSelected();
        o.keepAlive = h1Override.isOn() ? Boolean.valueOf(h1Reuse.isSelected()) : null;
        return o;
    }

    /** The response analysis for the next attack, as configured on this tab. */
    public ResponseGrep responseGrep() {
        int limit = intOf(extractMax, 100);
        List<ResponseGrep.Extract> rules = new ArrayList<>();
        if (extractOn.isSelected()) for (ResponseGrep.Extract x : extracts) {
            rules.add(new ResponseGrep.Extract(x.name(), x.startAfter(), x.endAt(), x.regex(),
                    x.caseSensitive(), x.excludeHeaders(), limit));
        }
        return new ResponseGrep(
                new ResponseGrep.Match(flagMatches.isSelected() ? grepExpressions() : List.of(), matchRegex.isSelected(),
                        matchCase.isSelected(), matchNoHeaders.isSelected()),
                rules,
                // Ticked, the payload is looked for as it was before encoding; unticked, exactly as it was sent.
                new ResponseGrep.Payloads(payloadGrep.isSelected(), payloadCase.isSelected(),
                        payloadNoHeaders.isSelected(), payloadPreEncoded.isSelected()));
    }

    /** The grep-match list as it stands, whether or not it is in use. */
    public List<String> grepExpressions() { return grepList.items(); }
}