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.

31.6 KB
Raw Blame
package opensuite.intruder;

import opensuite.core.HttpMode;
import opensuite.core.HttpService;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.ui.Ui;
import opensuite.ui.ResourcePoolPanel;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The Intruder tool: automated customised attacks. Each numbered tab is one
 * attack configuration with its own target, payload positions, payload sets,
 * resource pool and settings, as in the reference; sending a request to
 * Intruder opens it in a new tab. Starting an attack opens a results window
 * that fills in as responses arrive.
 */
public class IntruderTool implements ToolModule {

    private final SuiteContext ctx;
    private final JTabbedPane tabs = new JTabbedPane();
    private final AtomicInteger tabCounter = new AtomicInteger(0);
    private final AtomicInteger attackCounter = new AtomicInteger(0);

    public IntruderTool(SuiteContext ctx) {
        this.ctx = ctx;
    }

    /** One attack configuration: everything a numbered tab holds. */
    /** Set once "Don't show this again" is chosen on the Payloads introduction. */
    static final String PAYLOADS_INTRO_HIDDEN = "intruder.payloads.introHidden";

    private final class AttackTab extends JPanel {
        final TargetPanel target = new TargetPanel();
        final PositionsPanel positions = new PositionsPanel();
        final PayloadsPanel payloads = new PayloadsPanel();
        final OptionsPanel options = new OptionsPanel();
        final ResourcePoolPanel resourcePool = new ResourcePoolPanel("attack");
        /** The Payloads pane: an introduction until there is a position to fill, then the payloads themselves. */
        final CardLayout payloadCards = new CardLayout();
        final JPanel payloadPane = new JPanel(payloadCards);
        boolean introClosed;

        /** Show the introduction while there are no positions and it has not been closed. */
        void showPayloadPane() {
            boolean hidden = introClosed || positions.positionCount() > 0
                    || (ctx != null && ctx.settings().getBool(PAYLOADS_INTRO_HIDDEN, false));
            payloadCards.show(payloadPane, hidden ? "payloads" : "intro");
        }

        private JPanel payloadsIntro() {
            JButton close = Ui.button("Close");
            close.addActionListener(e -> { introClosed = true; showPayloadPane(); });
            JButton more = Ui.primaryButton("Learn more", "Open the project documentation");
            more.addActionListener(e -> opensuite.ui.EmptyState.openDocs());
            JLabel never = new JLabel("Don't show this again");
            never.setFont(Ui.PLAIN);
            never.setForeground(opensuite.ui.Theme.ACCENT);
            never.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            never.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mouseClicked(java.awt.event.MouseEvent e) {
                    if (ctx != null) ctx.settings().setBool(PAYLOADS_INTRO_HIDDEN, true);
                    introClosed = true;
                    showPayloadPane();
                }
            });
            JPanel p = opensuite.ui.EmptyState.of(opensuite.ui.EmptyState.art(0.85), 33, "Payloads",
                    "To get started, highlight the part of the request or target you want to replace, then click \u0001Add \u00a7\u0002 to set a payload position.",
                    239, opensuite.ui.Theme.BG, close, more);
            return opensuite.ui.EmptyState.withFooter(p, never, 30);
        }

        AttackTab() {
            super(new BorderLayout());
            payloadPane.setOpaque(false);
            payloadPane.add(payloadsIntro(), "intro");
            payloadPane.add(payloads, "payloads");
            positions.onChange(() -> {
                    payloads.setAttack(positions.attackType(), positions.positionCount());
                    showPayloadPane(); });
            showPayloadPane();
            positions.setStartAction(() -> startAttack(this));
            payloads.setStartAction(() -> startAttack(this));
            payloads.setAttack(positions.attackType(), positions.positionCount());
            if (ctx != null) options.applyDefaults(ctx.settings());
            positions.setAppendPlacement(() -> ctx != null
                    && "append".equals(ctx.settings().get(IntruderSettingsPanel.AUTO_PLACE, "replace")));
            // Where the side panel stands and how it opens come from Settings > Tools > Intruder.
            final boolean[] leftSide = { ctx != null && "left".equals(ctx.settings().get(IntruderSettingsPanel.SIDE_POSITION, "right")) };
            final boolean startCollapsed = ctx != null && "collapsed".equals(ctx.settings().get(IntruderSettingsPanel.SIDE_MODE, "auto"));

            // Single-view layout, as in the reference: the attack header, target row
            // and positions editor on the left; on the right the Payloads, Resource
            // pool and Settings panes, switched by a vertical tab strip on the edge.
            positions.setTargetRow(target);

            JSplitPane split = opensuite.ui.SideDock.build(positions, java.util.List.of(
                    new opensuite.ui.SideDock.Item("Payloads", payloadPane, opensuite.ui.Glyphs.section(18, opensuite.ui.Theme.TEXT)),
                    new opensuite.ui.SideDock.Item("Resource pool", resourcePool, opensuite.ui.Glyphs.clock(18, opensuite.ui.Theme.TEXT)),
                    new opensuite.ui.SideDock.Item("Settings", options, opensuite.ui.Glyphs.gear(18, opensuite.ui.Theme.TEXT))),
                    leftSide[0], startCollapsed, "Intruder settings", () -> {
                        if (ctx != null) opensuite.ui.SettingsDialog.open(SwingUtilities.getWindowAncestor(this), ctx, "Intruder");
                    });
            add(split, BorderLayout.CENTER);
        }

        /** The attack's configuration (type, payloads, resource pool, settings), not its target or request. */
        java.util.Map<String, String> config() { return source().config(); }

        void applyConfig(java.util.Map<String, String> m) {
            try { positions.setAttackType(AttackType.valueOf(m.getOrDefault("attackType", positions.attackType().name()))); }
            catch (IllegalArgumentException ignored) { }
            payloads.setAttack(positions.attackType(), positions.positionCount());
            opensuite.ui.FormState.apply(payloads, under(m, "payloads/"));
            opensuite.ui.FormState.apply(resourcePool, under(m, "pool/"));
            opensuite.ui.FormState.apply(options, under(m, "settings/"));
        }

        private static java.util.Map<String, String> under(java.util.Map<String, String> m, String prefix) {
            java.util.Map<String, String> out = new java.util.LinkedHashMap<>();
            for (java.util.Map.Entry<String, String> e : m.entrySet()) {
                if (e.getKey().startsWith(prefix)) out.put(e.getKey().substring(prefix.length()), e.getValue());
            }
            return out;
        }

        /** Concurrency from the chosen resource pool. */
        int poolThreads() { return source().threads(); }

        /** Pacing: the pool's delay when it has one. */
        long poolThrottle() { return source().throttle(); }

        AttackSource source() { return new AttackSource(target, positions, payloads, options, resourcePool); }
    }

    /**
     * The panes an attack is started from: those of a tab, or those at the side
     * of an attack's own window when it is repeated.
     */
    record AttackSource(TargetPanel target, PositionsPanel positions, PayloadsPanel payloads, OptionsPanel options,
                        opensuite.ui.ResourcePoolPanel pool) {
        int threads() { return Math.max(1, pool.selected().effectiveConcurrent()); }

        long throttle() {
            opensuite.core.ResourcePool p = pool.selected();
            return p.delayOn() ? p.delayMs() : 0;
        }

        java.util.Map<String, String> config() {
            java.util.Map<String, String> m = new java.util.LinkedHashMap<>();
            m.put("attackType", positions.attackType().name());
            for (java.util.Map.Entry<String, String> e : opensuite.ui.FormState.capture(payloads).entrySet()) m.put("payloads/" + e.getKey(), e.getValue());
            for (java.util.Map.Entry<String, String> e : opensuite.ui.FormState.capture(pool).entrySet()) m.put("pool/" + e.getKey(), e.getValue());
            for (java.util.Map.Entry<String, String> e : opensuite.ui.FormState.capture(options).entrySet()) m.put("settings/" + e.getKey(), e.getValue());
            return m;
        }
    }

    @Override public String name() { return "intruder"; }

    @Override public boolean alwaysTabbed() { return false; }

    @Override public void init(SuiteContext ctx) {
        // Settings > Intruder holds the defaults a new attack tab starts with;
        // the per-attack values stay on each tab's Settings pane.
        opensuite.ui.SettingsDialog.register("Intruder", () -> new IntruderSettingsPanel(ctx.settings()));
        SimpleListGenerator.customLists = () -> {
            if (!"custom".equals(ctx.settings().get(IntruderSettingsPanel.LISTS, "builtin"))) return null;
            String dir = ctx.settings().get(IntruderSettingsPanel.LISTS_DIR, "");
            return dir.isBlank() ? null : new java.io.File(dir);
        };
        ctx.registerSink("intruder", (svc, req, resp, cap) ->
                SwingUtilities.invokeLater(() -> {
                    AttackTab t = newTab(null);
                    t.target.set(svc);
                    t.positions.setRequest(svc, req);
                    t.payloads.setAttack(t.positions.attackType(), t.positions.positionCount());
                    t.showPayloadPane();
                }));
        opensuite.ui.TabStrip.tabMenu(tabs, this::tabMenu, c -> renameTab(tabs.indexOfComponent(c)));
    }

    /** Open a new attack tab holding the example request, and select it. */
    private AttackTab newTab(String title) {
        List<AttackTab> before = attackTabs();
        AttackTab t = new AttackTab();
        // A new tab may start as a copy of the first or the last tab's configuration.
        String start = ctx == null ? "default" : ctx.settings().get(IntruderSettingsPanel.NEW_TAB, "default");
        if (!before.isEmpty() && !"default".equals(start)) {
            t.applyConfig(("first".equals(start) ? before.get(0) : before.get(before.size() - 1)).config());
        }
        String name = title != null && !title.isBlank() ? title : String.valueOf(tabCounter.incrementAndGet());
        closeIntro();
        tabs.addTab(name, t);
        opensuite.ui.TabStrip.closable(tabs, tabs.indexOfComponent(t));
        tabs.setSelectedComponent(t);
        return t;
    }

    /** The tab in front, or null when only the "+" tab is showing. */
    private AttackTab current() {
        return tabs.getSelectedComponent() instanceof AttackTab t ? t : null;
    }

    /** Every attack tab, in order (the "+" tab is not one). */
    private List<AttackTab> attackTabs() {
        List<AttackTab> out = new ArrayList<>();
        for (int i = 0; i < tabs.getTabCount(); i++) {
            if (tabs.getComponentAt(i) instanceof AttackTab t) out.add(t);
        }
        return out;
    }

    private void renameTab(int i) {
        if (i < 0) return;
        String name = JOptionPane.showInputDialog(ctx.frame(), "Enter the new tab name", tabs.getTitleAt(i));
        if (name != null && !name.isBlank()) opensuite.ui.TabStrip.rename(tabs, i, name.trim());
    }

    private void closeTabs(java.util.function.Predicate<AttackTab> which) {
        for (AttackTab t : attackTabs()) {
            if (which.test(t) && opensuite.ui.TabStrip.count(tabs) > 1) tabs.remove(t);
        }
    }

    /** A copy of a tab: the same target and marked request in a new tab. */
    private void duplicate(AttackTab from) {
        AttackTab t = newTab(null);
        t.target.setText(from.target.text());
        t.target.setUpdateHostHeader(from.target.updateHostHeader());
        t.positions.setMarkedText(from.positions.markedText());
        t.payloads.setAttack(t.positions.attackType(), t.positions.positionCount());
        t.showPayloadPane();
    }

    /** The right-click menu of one tab's header, as the reference offers it. */
    private JPopupMenu tabMenu(Component c) {
        JPopupMenu m = new JPopupMenu();
        if (!(c instanceof AttackTab tab)) return m;
        int index = tabs.indexOfComponent(tab);
        item(m, "Rename tab", () -> renameTab(index));
        item(m, "Duplicate tab", () -> duplicate(tab));
        m.addSeparator();
        JMenuItem close = item(m, "Close tab", () -> closeTabs(t -> t == tab));
        JMenuItem others = item(m, "Close other tabs", () -> closeTabs(t -> t != tab));
        JMenuItem left = item(m, "Close tabs to the left",
                () -> closeTabs(t -> tabs.indexOfComponent(t) < tabs.indexOfComponent(tab)));
        JMenuItem right = item(m, "Close tabs to the right",
                () -> closeTabs(t -> tabs.indexOfComponent(t) > tabs.indexOfComponent(tab)));
        boolean many = opensuite.ui.TabStrip.count(tabs) > 1;
        close.setEnabled(many);
        others.setEnabled(many);
        left.setEnabled(index > 0);
        right.setEnabled(index < attackTabs().size() - 1);
        return m;
    }

    private static JMenuItem item(JPopupMenu m, String text, Runnable action) {
        JMenuItem mi = new JMenuItem(text);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> action.run());
        m.add(mi);
        return mi;
    }

    @Override public Tab[] tabs() {
        // Before anything has been sent here the page that says how to begin is in front.
        boolean fresh = tabs.getTabCount() == 0 && ctx != null && !ctx.settings().getBool(INTRO_HIDDEN, false);
        if (tabs.getTabCount() == 0) newTab(null);
        pages.setOpaque(false);
        pages.add(opensuite.ui.TabStrip.wrap(tabs, () -> newTab(null)), "tabs");
        pages.add(new opensuite.ui.ToolIntro("Intruder",
                "Configure automated attacks that send the same request many times, substituting specific values with "
                        + "predetermined payloads each time.",
                opensuite.ui.ToolIntro.volley(), 48, 306, this::closeIntro, () -> {
                    ctx.settings().setBool(INTRO_HIDDEN, true);
                    closeIntro();
                }), "intro");
        introShown = fresh;
        pageCards.show(pages, fresh ? "intro" : "tabs");
        return new Tab[]{ new Tab("intruder", pages) };
    }

    /** Set once "Don't show this again" is chosen on the Intruder's first page. */
    static final String INTRO_HIDDEN = "intruder.introHidden";
    private final CardLayout pageCards = new CardLayout();
    private final JPanel pages = new JPanel(pageCards);
    private boolean introShown;

    /** Put the tabs in front; anything that arrives in the Intruder does this too. */
    private void closeIntro() {
        if (!introShown) return;
        introShown = false;
        pageCards.show(pages, "tabs");
    }

    /** One saved tab: its title, target, marked request and the Host-header tick. */
    private static final int S_TITLE = 0, S_TARGET = 1, S_MARKED = 2, S_HOST = 3;

    @Override public java.io.Serializable saveState() {
        ArrayList<String[]> out = new ArrayList<>();
        for (AttackTab t : attackTabs()) {
            out.add(new String[]{ tabs.getTitleAt(tabs.indexOfComponent(t)), t.target.text(),
                    t.positions.markedText(), String.valueOf(t.target.updateHostHeader()) });
        }
        return out.isEmpty() ? null : out;
    }

    @Override public void restoreState(java.io.Serializable state) {
        if (state instanceof String marked) {
            // A project saved before Intruder had tabs holds one marked request.
            AttackTab t = current() != null ? current() : newTab(null);
            t.positions.setMarkedText(marked);
            t.payloads.setAttack(t.positions.attackType(), t.positions.positionCount());
            t.showPayloadPane();
            return;
        }
        if (!(state instanceof List<?> saved) || saved.isEmpty()) return;
        for (AttackTab t : attackTabs()) tabs.remove(t);
        for (Object o : saved) {
            if (!(o instanceof String[] row) || row.length <= S_MARKED) continue;
            AttackTab t = newTab(row[S_TITLE]);
            t.target.setText(row[S_TARGET]);
            if (row.length > S_HOST) t.target.setUpdateHostHeader(Boolean.parseBoolean(row[S_HOST]));
            t.positions.setMarkedText(row[S_MARKED]);
            t.payloads.setAttack(t.positions.attackType(), t.positions.positionCount());
            t.showPayloadPane();
        }
        if (attackTabs().isEmpty()) newTab(null);
        // Keep the tab numbering above any restored numeric title.
        for (int i = 0; i < tabs.getTabCount(); i++) {
            try { tabCounter.accumulateAndGet(Integer.parseInt(tabs.getTitleAt(i).trim()), Math::max); }
            catch (NumberFormatException ignored) { /* a renamed tab */ }
        }
    }

    /** The attack configuration as text, one {@code key=value} to a line, for a file or the configuration library. */
    static String configText(java.util.Map<String, String> config) {
        java.util.Properties p = new java.util.Properties();
        p.putAll(config);
        java.io.StringWriter w = new java.io.StringWriter();
        try { p.store(w, "Open Suite Intruder attack configuration"); } catch (java.io.IOException e) { throw new java.io.UncheckedIOException(e); }
        return w.toString();
    }

    /** The reverse of {@link #configText}; text that is not a configuration gives an empty map. */
    static java.util.Map<String, String> configFrom(String text) {
        java.util.Properties p = new java.util.Properties();
        try { p.load(new java.io.StringReader(text == null ? "" : text)); } catch (java.io.IOException | IllegalArgumentException e) { return new java.util.LinkedHashMap<>(); }
        java.util.Map<String, String> m = new java.util.TreeMap<>();
        for (String k : p.stringPropertyNames()) m.put(k, p.getProperty(k));
        return m;
    }

    private static final String CONFIG_KIND = "intruder-attack";

    private JMenuItem item(String text, Runnable run) {
        JMenuItem mi = new JMenuItem(text);
        mi.setFont(Ui.PLAIN);
        mi.addActionListener(e -> run.run());
        return mi;
    }

    private JMenu sub(String text) {
        JMenu m = new JMenu(text);
        m.setFont(Ui.PLAIN);
        return m;
    }

    /** A group of radio rows that set one settings key. */
    private void radios(JMenu into, String key, String def, String[] values, String... labels) {
        ButtonGroup g = new ButtonGroup();
        String now = ctx.settings().get(key, def);
        for (int k = 0; k < values.length; k++) {
            final String value = values[k];
            JRadioButtonMenuItem r = new JRadioButtonMenuItem(labels[k], value.equals(now));
            r.setFont(Ui.PLAIN);
            r.addActionListener(e -> ctx.settings().set(key, value));
            g.add(r);
            into.add(r);
        }
    }

    private void saveConfigToFile() {
        AttackTab t = current();
        if (t == null) return;
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setSelectedFile(new java.io.File("intruder-attack-config.properties"));
        if (fc.showSaveDialog(ctx.frame()) != JFileChooser.APPROVE_OPTION) return;
        try { java.nio.file.Files.writeString(fc.getSelectedFile().toPath(), configText(t.config())); }
        catch (java.io.IOException e) { JOptionPane.showMessageDialog(ctx.frame(), "Could not save: " + e.getMessage(), "Save attack config", JOptionPane.ERROR_MESSAGE); }
    }

    private void loadConfigFromFile() {
        AttackTab t = current();
        if (t == null) return;
        JFileChooser fc = new opensuite.ui.FileChooser();
        if (fc.showOpenDialog(ctx.frame()) != JFileChooser.APPROVE_OPTION) return;
        try {
            java.util.Map<String, String> m = configFrom(java.nio.file.Files.readString(fc.getSelectedFile().toPath()));
            if (m.isEmpty()) { JOptionPane.showMessageDialog(ctx.frame(), "The file does not contain an attack configuration.", "Load attack config", JOptionPane.WARNING_MESSAGE); return; }
            t.applyConfig(m);
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(ctx.frame(), "Could not read: " + e.getMessage(), "Load attack config", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveConfigToLibrary() {
        AttackTab t = current();
        if (t == null) return;
        String name = JOptionPane.showInputDialog(ctx.frame(), "Name for this attack configuration", "Save attack config", JOptionPane.PLAIN_MESSAGE);
        if (name == null || name.isBlank()) return;
        opensuite.ui.LibraryDialog.write(CONFIG_KIND, name.trim(), configText(t.config()));
    }

    private void loadConfigFromLibrary() {
        AttackTab t = current();
        if (t == null) return;
        String name = opensuite.ui.LibraryDialog.pick(ctx.frame(), CONFIG_KIND, "Load attack config");
        if (name == null) return;
        java.util.Map<String, String> m = configFrom(opensuite.ui.LibraryDialog.read(CONFIG_KIND, name));
        if (!m.isEmpty()) t.applyConfig(m);
    }

    private void sendToRepeater() {
        AttackTab t = current();
        if (t == null) return;
        // The request as it stands with the position markers taken out.
        String plain = t.positions.markedText().replace("\u00a7", "");
        byte[] raw = plain.replace("\r\n", "\n").replace("\n", "\r\n").getBytes(java.nio.charset.StandardCharsets.ISO_8859_1);
        ctx.sendTo("repeater", t.target.service(), new opensuite.core.HttpMessage(raw), null, null);
    }

    private void choosePayloadLists() {
        opensuite.core.Settings s = ctx.settings();
        Object[] options = { "Use the built-in lists", "Choose a directory...", "Cancel" };
        String dir = s.get(IntruderSettingsPanel.LISTS_DIR, "");
        boolean custom = "custom".equals(s.get(IntruderSettingsPanel.LISTS, "builtin")) && !dir.isBlank();
        int pick = JOptionPane.showOptionDialog(ctx.frame(),
                "Predefined payload lists are loaded from " + (custom ? dir : "the built-in lists") + ".\n"
              + "Each text file in a custom directory is offered as a list, one payload per line.",
                "Configure predefined payload lists", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[2]);
        if (pick == 0) { s.set(IntruderSettingsPanel.LISTS, "builtin"); return; }
        if (pick != 1) return;
        JFileChooser fc = new opensuite.ui.FileChooser(dir.isBlank() ? null : new java.io.File(dir));
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showOpenDialog(ctx.frame()) != JFileChooser.APPROVE_OPTION) return;
        s.set(IntruderSettingsPanel.LISTS_DIR, fc.getSelectedFile().getAbsolutePath());
        s.set(IntruderSettingsPanel.LISTS, "custom");
    }

    /** The reference's Intruder menu; built afresh each time it opens, so its ticks and tab list are current. */
    @Override public JMenu[] menus() {
        JMenu menu = new JMenu("intruder");
        menu.addMenuListener(new javax.swing.event.MenuListener() {
            @Override public void menuSelected(javax.swing.event.MenuEvent e) { fillMenu(menu); }
            @Override public void menuDeselected(javax.swing.event.MenuEvent e) { }
            @Override public void menuCanceled(javax.swing.event.MenuEvent e) { }
        });
        fillMenu(menu);
        return new JMenu[]{ menu };
    }

    private void fillMenu(JMenu menu) {
        menu.removeAll();
        AttackTab cur = current();
        menu.add(item("Start attack", () -> { if (current() != null) startAttack(current()); }));
        menu.add(item("Open saved attack", () -> ResultsWindow.openSaved(ctx, ctx.frame())));
        menu.add(item("Send to Repeater", this::sendToRepeater));
        menu.addSeparator();
        JMenu save = sub("Save attack config");
        save.add(item("To file", this::saveConfigToFile));
        save.add(item("To configuration library", this::saveConfigToLibrary));
        menu.add(save);
        JMenu load = sub("Load attack config");
        load.add(item("From file", this::loadConfigFromFile));
        load.add(item("From configuration library", this::loadConfigFromLibrary));
        menu.add(load);
        JMenu copy = sub("Copy attack config");
        for (AttackTab t : attackTabs()) {
            if (t == cur) continue;
            copy.add(item("To tab " + tabs.getTitleAt(tabs.indexOfComponent(t)), () -> { if (current() != null) t.applyConfig(current().config()); }));
        }
        if (copy.getItemCount() > 0) copy.addSeparator();
        copy.add(item("To a new tab", () -> {
            AttackTab from = current();
            if (from == null) return;
            java.util.Map<String, String> config = from.config();
            newTab(null).applyConfig(config);
        }));
        menu.add(copy);
        menu.addSeparator();
        JMenu tab = sub("New tab behavior");
        radios(tab, IntruderSettingsPanel.NEW_TAB, "default", new String[]{ "default", "first", "last" },
                "Use default attack config", "Copy config from first tab", "Copy config from last tab");
        menu.add(tab);
        JMenu auto = sub("Automatic payload positions");
        radios(auto, IntruderSettingsPanel.AUTO_PLACE, "replace", new String[]{ "replace", "append" },
                "Replace base parameter value", "Append to base parameter value");
        menu.add(auto);
        menu.addSeparator();
        menu.add(item("Configure predefined payload lists", this::choosePayloadLists));
        menu.add(item("Close attack results preferences", () -> opensuite.ui.SettingsDialog.open(
                ctx.frame() instanceof Window w ? w : null, ctx, "Intruder")));
        for (int k = 0; k < menu.getItemCount(); k++) {
            JMenuItem mi = menu.getItem(k);
            if (mi != null && cur == null && k != 1 && k < 6) mi.setEnabled(false);
        }
    }

    private void startAttack(AttackTab tab) { startAttack(tab.source()); }

    /** Start an attack from a tab's panes, or from those of an attack window being repeated. */
    private void startAttack(AttackSource tab) {
        final TargetPanel target = tab.target();
        final PositionsPanel positions = tab.positions();
        final PayloadsPanel payloads = tab.payloads();
        final OptionsPanel options = tab.options();
        final int positionCount = positions.positionCount();
        // Everything wrong with the configuration is gathered and shown at once,
        // with the choice of going back to put it right or starting regardless.
        List<String> errors = new ArrayList<>();
        if (positionCount == 0) errors.add("No payload positions defined.");

        List<PayloadSet> sets = payloads.activeSets();
        // Feed the marked positions' original values to transforming payload
        // types (character and case substitution) so they have base items.
        List<String> base = originalValues(positions.markedText());
        for (PayloadSet s : sets) s.setBase(base);
        final List<List<String>> materialised = new ArrayList<>();
        PayloadProcessor.collaborator = ctx::collaborator;
        // A sniper attack puts one set into every position in turn. Where a rule
        // works from the position's own value, each position gets payloads of its own.
        boolean perPosition = positions.attackType() == AttackType.SNIPER && sets.size() == 1 && sets.get(0).usesBase();
        for (int k = 0; k < (perPosition ? positionCount : sets.size()); k++) {
            List<String> p = sets.get(perPosition ? 0 : k).payloads(k < base.size() ? base.get(k) : "");
            materialised.add(p);
            if (p.isEmpty() && (!perPosition || k == 0)) errors.add("Payload position " + (k + 1) + ": The payload list is empty.");
        }

        final HttpService svc = target.service();
        if (svc.host().isEmpty()) errors.add("No target host is set.");
        if (!errors.isEmpty()) {
            if (!AttackConfigDialog.ignore(ctx.frame(), errors)) return;
            if (svc.host().isEmpty()) return;   // there is nowhere to send it
        }

        final ResponseGrep grep = options.responseGrep();
        // What each payload was before it was URL-encoded, for "Match against pre-URL-encoded payloads".
        java.util.Map<String, String> originals = new java.util.HashMap<>();
        for (int k = 0; k < (perPosition ? positionCount : sets.size()); k++)
            originals.putAll(sets.get(perPosition ? 0 : k).originals(k < base.size() ? base.get(k) : ""));
        grep.setOriginals(originals);
        String text = positions.markedText();
        final String marked = target.updateHostHeader() ? withHost(text, svc) : text;
        final AttackEngine.Options engineOptions = options.engineOptions();
        final boolean follow = options.followRedirects();
        final int threads = tab.threads();
        final long throttle = tab.throttle();
        final AttackType type = positions.attackType();
        final java.util.Map<String, String> config = tab.config();
        final boolean updateHost = target.updateHostHeader();
        java.util.function.Consumer<HttpMode> launch = mode -> {
            ResultsWindow window = new ResultsWindow(ctx, attackCounter.incrementAndGet(), grep, svc);
            window.setAttack(type, svc, marked, updateHost, config, this::startAttack);
            AttackEngine engine = new AttackEngine(ctx, svc, marked, type, positionCount, materialised, grep,
                    threads, follow, throttle, mode, window, engineOptions);
            window.setSaveToProject(engineOptions.saveToProject);
            window.setOnClose(engine::stop);
            window.setPauseControl(engine::setPaused);
            window.setVisible(true);
            engine.start();
        };
        // HTTP/2 is used where it is preferred and the server speaks it. Finding
        // that out means asking the server, which is not done on the event thread.
        if (!svc.secure() || !options.prefersHttp2(ctx.settings())) { launch.accept(HttpMode.HTTP_1); return; }
        Thread ask = new Thread(() -> {
            HttpMode mode = opensuite.core.NetworkConfig.speaksHttp2(svc) ? HttpMode.HTTP_2 : HttpMode.HTTP_1;
            SwingUtilities.invokeLater(() -> launch.accept(mode));
        }, "intruder-http2-default");
        ask.setDaemon(true);
        ask.start();
    }

    /**
     * Rewrite the request's Host header so it names the target, which is what
     * "Update Host header to match target" asks for. A request with no Host
     * header gains one after the start line.
     */
    static String withHost(String marked, HttpService svc) {
        String host = svc.host() + (svc.defaultPort() ? "" : ":" + svc.port());
        String[] lines = marked.split("\r?\n", -1);
        for (int i = 1; i < lines.length; i++) {
            if (lines[i].isEmpty()) break;                     // end of the headers
            if (lines[i].regionMatches(true, 0, "Host:", 0, 5)) {
                lines[i] = "Host: " + host;
                return String.join("\r\n", lines);
            }
        }
        if (lines.length < 2) return marked;
        StringBuilder sb = new StringBuilder(lines[0]).append("\r\nHost: ").append(host);
        for (int i = 1; i < lines.length; i++) sb.append("\r\n").append(lines[i]);
        return sb.toString();
    }

    /** The original text between each marker pair, for transforming payloads. */
    private static List<String> originalValues(String markedText) {
        List<String> out = new ArrayList<>();
        String[] parts = markedText.split(String.valueOf(PositionsPanel.MARK), -1);
        for (int i = 1; i < parts.length; i += 2) out.add(parts[i]);
        return out;
    }
}