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.

43.5 KB
Raw Blame
package opensuite.intruder;

import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.SuiteContext;
import opensuite.ui.MessageEditor;
import opensuite.ui.Ui;

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

/**
 * A detached window showing the live results of one Intruder attack: a sortable
 * table of exchanges, request and response viewers, a status line and a
 * progress bar. There is one window per attack.
 */
public class ResultsWindow extends JFrame {

    /** One row of attack output. */
    public record Result(int number, String payload, HttpService svc, HttpMessage request,
                         HttpMessage response, int status, int length, long millis,
                         String error, Object[] extra, long sentAt, long firstByte) {
        /** A result whose sending time and time to the first byte are not known. */
        public Result(int number, String payload, HttpService svc, HttpMessage request,
                      HttpMessage response, int status, int length, long millis, String error, Object[] extra) {
            this(number, payload, svc, request, response, status, length, millis, error, extra, 0, -1);
        }
    }

    /** The columns every attack has, before any the response matching adds. */
    private static final int FIXED = 11;
    /** The height of the row of tabs with the rule under it. */
    private static final int TAB_ROW = 46;
    private final int fixedColumns = FIXED;
    private final DefaultTableModel model;
    private final JTable table;
    private final List<Result> rows = new ArrayList<>();

    private final opensuite.ui.MessagePair pair;
    private final JLabel status = Ui.label("Waiting");
    private final ThinBar progress = new ThinBar();
    private java.util.function.Consumer<Boolean> pauseControl;
    private Runnable repeat;
    private boolean paused;

    private final List<String> extraNames;
    private final Class<?>[] extraClasses;
    /** True for an attack opened from a file: nothing is running, so there is nothing to pause or stop. */
    private final boolean saved;
    private final SuiteContext suite;

    /** Only the row of tabs: the views they choose between are laid out elsewhere. */
    private final JTabbedPane tabs = new JTabbedPane() {
        @Override public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            if (getTabCount() == 0) return d;
            Rectangle r = getUI().getTabBounds(this, 0);
            return new Dimension(d.width, r == null || r.height == 0 ? d.height : r.y + r.height);
        }
    };
    private final JPanel body = new JPanel(new BorderLayout());
    private final JPanel mainView = new JPanel(new BorderLayout());
    private final JButton captureButton = Ui.filterButton();
    private final JButton viewButton = Ui.filterButton();
    private final JCheckBox applyCapture = Ui.switchBox("Apply capture filter", false);

    public ResultsWindow(SuiteContext ctx, int attackNumber, ResponseGrep grep, HttpService svc) {
        this(ctx, attackNumber + ". Intruder attack of " + (svc == null ? "" : svc.url()), grep.columnNames(), grep.columnClasses(), false);
    }

    private ResultsWindow(SuiteContext ctx, String title, List<String> extraNames, Class<?>[] extraClasses, boolean saved) {
        super(title);
        this.extraNames = new ArrayList<>(extraNames);
        this.extraClasses = extraClasses;
        this.saved = saved;
        this.suite = ctx;
        if (!saved) LIVE.add(this);
        setIconImages(opensuite.ui.AppIcon.images());
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override public void windowClosing(java.awt.event.WindowEvent e) { confirmClose(); }
        });

        List<String> cols = new ArrayList<>(List.of(
                "Request", "Payload", "Status code", "Time of day", "Response received", "Response completed",
                "Error", "Timeout", "Length", "Cookies", "Comment"));
        cols.addAll(extraNames);

        model = new DefaultTableModel(cols.toArray(), 0) {
            @Override public boolean isCellEditable(int r, int c) { return c == 10; }
            @Override public Class<?> getColumnClass(int c) {
                if (c >= FIXED) return extraClasses[c - FIXED];
                return switch (c) {
                    case 0, 2, 8 -> Integer.class;
                    case 4, 5 -> Long.class;
                    case 6, 7 -> Boolean.class;
                    default -> String.class;
                };
            }
        };
        table = new JTable(model) {
            /** A highlighted row keeps its colour under whatever the cell shows, unless it is the chosen row. */
            @Override public Component prepareRenderer(javax.swing.table.TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                int at = convertRowIndexToModel(row);
                Color tint = at < rows.size() ? highlights.get(rows.get(at).number()) : null;
                if (tint != null && !isRowSelected(row)) { c.setBackground(tint); c.setForeground(Color.BLACK); }
                return c;
            }
        };
        Ui.styleTable(table);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { if (e.isPopupTrigger()) rowMenu(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { if (e.isPopupTrigger()) rowMenu(e); }
        });
        // Figures stand at the left of their cells like everything else, and a
        // result that neither failed nor timed out leaves those cells empty.
        final javax.swing.table.TableCellRenderer plain = table.getDefaultRenderer(Object.class);
        for (Class<?> k : new Class<?>[]{ Integer.class, Long.class }) table.setDefaultRenderer(k, plain);
        javax.swing.table.TableCellRenderer flag = (t, v, sel, foc, r, c) ->
                plain.getTableCellRendererComponent(t, Boolean.TRUE.equals(v) ? "\u2713" : "", sel, foc, r, c);
        table.getColumnModel().getColumn(6).setCellRenderer(flag);
        table.getColumnModel().getColumn(7).setCellRenderer(flag);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setColumnSelectionAllowed(false);
        table.setRowSorter(new opensuite.ui.NumberSorter<>(table.getModel()));
        // Newest first, so the latest result is on the top row while an attack runs.
        table.getRowSorter().setSortKeys(List.of(new javax.swing.RowSorter.SortKey(0, javax.swing.SortOrder.DESCENDING)));
        table.getTableHeader().setToolTipText("Click a column header to sort by that column");
        opensuite.ui.RowSelection.watch(table, r -> r >= 0 && r < rows.size() ? rows.get(r) : null, this::showSelected);
        int[] widths = new int[cols.size()];
        int[] measured = { 159, 397, 191, 180, 162, 162, 127, 127, 159, 200, 398 };
        System.arraycopy(measured, 0, widths, 0, FIXED);
        for (int i = FIXED; i < widths.length; i++) widths[i] = 130;
        Ui.proportionalWidths(table, widths);

        for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) allColumns.add(table.getColumnModel().getColumn(i));
        defaultColumns();

        JScrollPane tableScroll = Ui.scrollPlain(table);
        tableScroll.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        tableScroll.getVerticalScrollBar().setUnitIncrement(25);
        JPanel tableWrap = new JPanel(new BorderLayout());
        tableWrap.setOpaque(false);
        tableWrap.setBorder(Ui.pad(0, 20, 2, 19));
        tableWrap.add(tableScroll, BorderLayout.CENTER);

        MessageEditor reqEditor = new MessageEditor(ctx, MessageEditor.REQUEST, false);
        MessageEditor respEditor = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
        respEditor.setInspectorOnly();
        pair = new opensuite.ui.MessagePair(reqEditor, respEditor);
        pair.setBlankBackground(opensuite.ui.Theme.BG);
        pair.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, opensuite.ui.Theme.BG));   // the editors stand clear of the divider

        JSplitPane outer = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tableWrap, pair);
        outer.setDividerSize(1);
        outer.setBorder(null);
        Ui.balance(outer, 0.2255);

        // Two bars, as in the reference: what is kept, with the switch that
        // applies it, then what is shown, with the table's menu.
        captureButton.addActionListener(e -> askFilter(true));
        viewButton.addActionListener(e -> askFilter(false));
        applyCapture.setToolTipText("Store only results that match the capture filter");
        applyCapture.setBorder(Ui.pad(0, 2, 0, 0));
        applyCapture.setPreferredSize(new Dimension(applyCapture.getPreferredSize().width, Ui.tall(22)));
        JPanel captureBar = Ui.filterBar(captureButton, applyCapture);
        captureBar.setBorder(Ui.pad(10, 20, 5, 19));
        JButton kebab = opensuite.ui.Glyphs.menuButton("Columns", this::columnMenu);
        kebab.setBorder(Ui.pad(3, 10, 3, 0));
        kebab.setPreferredSize(new Dimension(kebab.getPreferredSize().width, Ui.tall(22)));
        JPanel viewBar = Ui.filterBar(viewButton, kebab);
        viewBar.setBorder(Ui.pad(5, 20, 10, 19));
        describeFilters();

        JPanel south = new JPanel(new BorderLayout(8, 0));
        south.setBackground(opensuite.ui.Theme.BG);
        south.setBorder(Ui.pad(1, 5, 4, 3));
        south.add(status, BorderLayout.WEST);
        south.add(progress, BorderLayout.CENTER);

        JPanel results = new JPanel(new BorderLayout());
        results.setBackground(opensuite.ui.Theme.BG);
        results.add(Ui.vbox(captureBar, viewBar), BorderLayout.NORTH);
        results.add(outer, BorderLayout.CENTER);
        results.add(south, BorderLayout.SOUTH);

        // The row of tabs runs the full width, over the side panes as well, so
        // the tabs hold nothing themselves and only choose which view is in front.
        tabs.setFont(Ui.PLAIN);
        addView("Results", results);

        mainView.setBackground(opensuite.ui.Theme.BG);
        mainView.add(views, BorderLayout.CENTER);
        tabs.addChangeListener(e -> {
            int i = tabs.getSelectedIndex();
            if (i >= 0) viewCards.show(views, tabs.getTitleAt(i));
        });

        body.setBackground(opensuite.ui.Theme.BG);
        JPanel tabRow = new JPanel(new BorderLayout());
        tabRow.setBackground(opensuite.ui.Theme.BG);
        tabRow.setBorder(Ui.pad(9, 20, 0, 0));   // the tabs draw the rule under themselves
        tabRow.add(tabs, BorderLayout.CENTER);
        tabRow.setPreferredSize(new Dimension(10, TAB_ROW));
        body.add(Ui.vbox(buildHeader(title), tabRow), BorderLayout.NORTH);
        body.add(mainView, BorderLayout.CENTER);

        JMenuBar bar = new JMenuBar();
        bar.add(liveMenu("Attack", this::attackItems));
        bar.add(liveMenu("Save", this::saveItems));
        getContentPane().setLayout(new BorderLayout());
        if (ctx == null || ctx.settings().getBool("ui.mergeTitleBar", !opensuite.core.Os.MAC)) opensuite.ui.TitleBar.install(this, bar);
        else setJMenuBar(bar);
        getContentPane().add(body, BorderLayout.CENTER);

        // As wide as the screen less 60px either side, and as tall as it allows.
        Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        int w = Math.max(900, screen.width - 120);
        setBounds(screen.x + (screen.width - w) / 2, screen.y, w, screen.height);
    }

    /**
     * Give the window the attack it shows: its positions on a tab of their own
     * and its payloads, resource pool and settings in panes at the side.
     *
     * @param config the attack tab's configuration, as {@code AttackTab.config()} gives it
     * @param again  starts an attack from this window's own panes as they now stand, for Attack &gt; Repeat
     */
    void setAttack(AttackType type, HttpService svc, String marked, boolean updateHost,
                   java.util.Map<String, String> config, java.util.function.Consumer<IntruderTool.AttackSource> again) {
        this.attackConfig = config == null ? null : new java.util.LinkedHashMap<>(config);
        PositionsPanel positions = new PositionsPanel();
        TargetPanel target = new TargetPanel();
        target.set(svc);
        target.setUpdateHostHeader(updateHost);
        target.lock();
        positions.setTargetRow(target);
        positions.setAttackType(type);
        positions.setMarkedText(marked);
        positions.hideStart();
        addView("Positions", positions);

        PayloadsPanel payloads = new PayloadsPanel();
        payloads.setAttack(type, positions.positionCount());
        opensuite.ui.ResourcePoolPanel pool = new opensuite.ui.ResourcePoolPanel("attack");
        OptionsPanel options = new OptionsPanel();
        if (suite != null) options.applyDefaults(suite.settings());
        opensuite.ui.FormState.apply(payloads, under(config, "payloads/"));
        opensuite.ui.FormState.apply(pool, under(config, "pool/"));
        opensuite.ui.FormState.apply(options, under(config, "settings/"));
        payloads.setAttack(type, positions.positionCount());   // count again now the lists are filled
        // Whatever has been changed here since goes into the attack that Repeat starts.
        this.repeat = again == null ? null
                : () -> again.accept(new IntruderTool.AttackSource(target, positions, payloads, options, pool));

        body.remove(mainView);
        body.add(opensuite.ui.SideDock.build(mainView, List.of(
                new opensuite.ui.SideDock.Item("Payloads", payloads, opensuite.ui.Glyphs.section(18, opensuite.ui.Theme.TEXT)),
                new opensuite.ui.SideDock.Item("Resource pool", pool, 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))),
                false, true, 520, "Intruder settings", () -> {
                    if (suite != null) opensuite.ui.SettingsDialog.open(this, suite, "Intruder");
                }), BorderLayout.CENTER);
        body.revalidate();
    }

    private final CardLayout viewCards = new CardLayout();
    private final JPanel views = new JPanel(viewCards);

    private void addView(String name, Component view) {
        views.add(view, name);
        JPanel nothing = new JPanel();
        nothing.setPreferredSize(new Dimension(0, 0));
        tabs.addTab(name, nothing);
    }

    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<>();
        if (m == null) return out;
        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;
    }

    /** The line under the title bar: a mark that brings the main window forward, the attack's name, and its menus. */
    private JComponent buildHeader(String title) {
        JButton back = opensuite.ui.Glyphs.button(backMark(), "Show the main window", () -> {
            if (suite != null && suite.frame() != null) suite.frame().toFront();
        });
        back.setBorder(BorderFactory.createEmptyBorder());
        JLabel name = new JLabel(title);
        name.setFont(Ui.HEADING.deriveFont(Font.BOLD, (float) Ui.em(13)));
        name.setForeground(opensuite.ui.Theme.TAB_TEXT_ON);
        JPanel west = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        west.setOpaque(false);
        west.add(back);
        west.add(Box.createHorizontalStrut(16));
        west.add(name);

        JButton attack = dropButton("Attack", 104, this::attackItems);
        JButton save = dropButton("Save", 91, this::saveItems);
        JButton help = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.help(), "About attack results",
                opensuite.ui.EmptyState::openDocs);
        help.setBorder(BorderFactory.createEmptyBorder());
        JPanel east = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        east.setOpaque(false);
        east.add(attack);
        east.add(Box.createHorizontalStrut(11));
        east.add(save);
        east.add(Box.createHorizontalStrut(20));
        east.add(help);

        JPanel head = new JPanel(new BorderLayout());
        head.setBackground(opensuite.ui.Theme.BG);
        head.setBorder(Ui.pad(0, 21, 0, 20));
        head.setPreferredSize(new Dimension(10, Ui.tall(68) - 2));
        head.add(centred(west), BorderLayout.WEST);
        head.add(centred(east), BorderLayout.EAST);
        return head;
    }

    private static JComponent centred(JComponent c) {
        JPanel p = new JPanel(new GridBagLayout());
        p.setOpaque(false);
        p.add(c);
        return p;
    }

    /** Our own mark for going back to the main window: an arrow to the left inside a tag that points the same way. */
    private static Icon backMark() {
        return new Icon() {
            @Override public int getIconWidth() { return 20; }
            @Override public int getIconHeight() { return 20; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                g2.translate(x, y);
                g2.setColor(opensuite.ui.Theme.TEXT);
                g2.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                java.awt.geom.Path2D.Double tag = new java.awt.geom.Path2D.Double();
                tag.moveTo(2, 10); tag.lineTo(9, 3); tag.lineTo(17, 3); tag.lineTo(17, 17); tag.lineTo(9, 17); tag.closePath();
                g2.draw(tag);
                g2.draw(new java.awt.geom.Line2D.Double(7.5, 10, 13.5, 10));
                g2.draw(new java.awt.geom.Line2D.Double(7.5, 10, 10, 7.5));
                g2.draw(new java.awt.geom.Line2D.Double(7.5, 10, 10, 12.5));
                g2.dispose();
            }
        };
    }

    /** A button that drops a menu: its word, then the mark that says so. */
    private JButton dropButton(String text, int width, java.util.function.Supplier<List<JMenuItem>> items) {
        JButton b = Ui.button(text);
        b.setIcon(opensuite.ui.Glyphs.fold(opensuite.ui.Theme.TEXT, false));
        b.setHorizontalTextPosition(SwingConstants.LEFT);
        b.setIconTextGap(12);
        int tall = b.getPreferredSize().height;
        b.setBorder(Ui.pad(3, 11, 3, 4));
        b.setPreferredSize(new Dimension(Math.round(width * opensuite.ui.Theme.FONT_SIZE / 13f), tall));
        b.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            for (JMenuItem it : items.get()) m.add(it);
            // The menu's right edge stands under the button's.
            int w = Math.max(m.getPreferredSize().width + 7, 92);
            m.setPopupSize(w, m.getPreferredSize().height);
            m.show(b, b.getWidth() + 1 - w, b.getHeight());
        });
        return b;
    }

    /** A menu on the title bar whose items are made afresh each time it opens. */
    private static JMenu liveMenu(String text, java.util.function.Supplier<List<JMenuItem>> items) {
        JMenu m = new JMenu(text);
        m.setFont(Ui.PLAIN);
        m.addMenuListener(new javax.swing.event.MenuListener() {
            @Override public void menuSelected(javax.swing.event.MenuEvent e) {
                m.removeAll();
                for (JMenuItem it : items.get()) m.add(it);
            }
            @Override public void menuDeselected(javax.swing.event.MenuEvent e) { }
            @Override public void menuCanceled(javax.swing.event.MenuEvent e) { }
        });
        return m;
    }

    private static JMenuItem item(String text, boolean enabled, Runnable action) {
        JMenuItem it = new JMenuItem(text);
        it.setFont(Ui.PLAIN);
        it.setEnabled(enabled);
        it.addActionListener(e -> action.run());
        return it;
    }

    private List<JMenuItem> attackItems() {
        return List.of(
                item(paused ? "Resume" : "Pause", !saved && !done && pauseControl != null, () -> {
                    paused = !paused;
                    pauseControl.accept(paused);
                    status.setText(paused ? "Paused" : "Running");
                }),
                item("Repeat", repeat != null, () -> repeat.run()));
    }

    private List<JMenuItem> saveItems() {
        return List.of(
                item("Results table", true, this::exportCsv),
                item("Server responses", true, this::saveResponses),
                item("Attack configuration", attackConfig != null, this::saveConfiguration),
                item("Project File", true, this::saveWithProject));
    }

    /** The attack tab's configuration, kept for Save > Attack configuration. */
    private java.util.Map<String, String> attackConfig;

    /** Write every response the attack kept to one file, each under a line that names its request. */
    private void saveResponses() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Save server responses");
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        try (java.io.OutputStream out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(fc.getSelectedFile()))) {
            int kept = 0;
            for (Result r : new ArrayList<>(rows)) {
                if (r.response() == null) continue;
                String payload = r.payload() == null ? "" : r.payload();
                out.write(("======== request " + r.number() + (payload.isEmpty() ? "" : " payload " + payload) + " ========\r\n")
                        .getBytes(java.nio.charset.StandardCharsets.UTF_8));
                out.write(r.response().raw());
                out.write("\r\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
                kept++;
            }
            status.setText("Saved " + kept + " responses to " + fc.getSelectedFile().getName());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not save the responses: " + ex.getMessage(), "Save server responses", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** Write the attack's type, payloads, resource pool and settings to a file. */
    private void saveConfiguration() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Save attack configuration");
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        java.util.Properties props = new java.util.Properties();
        props.putAll(attackConfig);
        try (java.io.Writer w = new java.io.OutputStreamWriter(new java.io.FileOutputStream(fc.getSelectedFile()), java.nio.charset.StandardCharsets.UTF_8)) {
            props.store(w, getTitle());
            status.setText("Saved the configuration to " + fc.getSelectedFile().getName());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not save the configuration: " + ex.getMessage(), "Save attack configuration", JOptionPane.ERROR_MESSAGE);
        }
    }

    private static final java.time.format.DateTimeFormatter TIME_OF_DAY = java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss d MMM yyyy");

    /** The cookies a response sets, as name=value pairs. */
    private static String cookies(HttpMessage response) {
        if (response == null) return "";
        StringBuilder sb = new StringBuilder();
        String head = new String(response.raw(), 0, Math.min(response.raw().length, 65536), java.nio.charset.StandardCharsets.ISO_8859_1);
        for (String line : head.split("\r?\n")) {
            if (line.isEmpty()) break;
            if (!line.regionMatches(true, 0, "Set-Cookie:", 0, 11)) continue;
            String pair = line.substring(11).trim();
            int semi = pair.indexOf(';');
            if (semi >= 0) pair = pair.substring(0, semi);
            if (sb.length() > 0) sb.append("; ");
            sb.append(pair);
        }
        return sb.toString();
    }

    /** Every column, in the model's order, shown or not. */
    private final List<javax.swing.table.TableColumn> allColumns = new ArrayList<>();
    /** Left out until they are asked for: Time of day, Response completed and Cookies. */
    private static final java.util.Set<Integer> OPTIONAL = java.util.Set.of(3, 5, 9);

    private boolean shown(javax.swing.table.TableColumn col) {
        javax.swing.table.TableColumnModel cm = table.getColumnModel();
        for (int i = 0; i < cm.getColumnCount(); i++) if (cm.getColumn(i) == col) return true;
        return false;
    }

    /** Show or hide a column, keeping the shown ones in the model's order. */
    private void setShown(javax.swing.table.TableColumn col, boolean show) {
        javax.swing.table.TableColumnModel cm = table.getColumnModel();
        if (show == shown(col)) return;
        if (!show) { if (cm.getColumnCount() > 1) cm.removeColumn(col); return; }
        cm.addColumn(col);
        int at = 0;
        for (javax.swing.table.TableColumn other : allColumns) {
            if (other == col) break;
            if (shown(other)) at++;
        }
        cm.moveColumn(cm.getColumnCount() - 1, at);
    }

    private void defaultColumns() {
        for (javax.swing.table.TableColumn col : allColumns) setShown(col, !OPTIONAL.contains(col.getModelIndex()));
    }

    /** The table's menu: a tick for each column, then the way back to the usual ones. */
    private JPopupMenu columnMenu() {
        JPopupMenu m = new JPopupMenu();
        for (javax.swing.table.TableColumn col : allColumns) {
            // A tick box before each name, as on a form, not the menu's bare tick.
            JMenuItem it = new JMenuItem(String.valueOf(col.getHeaderValue()), UIManager.getIcon("CheckBox.icon"));
            it.setSelected(shown(col));
            it.setIconTextGap(8);
            it.setFont(Ui.PLAIN);
            it.addActionListener(e -> setShown(col, !shown(col)));
            m.add(it);
        }
        JMenuItem restore = new JMenuItem("Restore default", opensuite.ui.Glyphs.restore(14, opensuite.ui.Theme.TEXT));
        restore.setFont(Ui.PLAIN);
        restore.addActionListener(e -> defaultColumns());
        m.add(restore);
        return m;
    }

    private AttackFilter captureFilter = new AttackFilter();
    private AttackFilter viewFilter = new AttackFilter();
    /** The requests whose rows are highlighted, by number, with the colour of each. */
    private final java.util.Map<Integer, Color> highlights = new java.util.HashMap<>();

    /** Open the capture filter or the view filter and take up what is chosen there. */
    private void askFilter(boolean capture) {
        AttackFilter chosen = AttackFilterDialog.ask(this, capture, capture ? captureFilter : viewFilter);
        if (chosen == null) return;
        if (capture) captureFilter = chosen;
        else { viewFilter = chosen; applyViewFilter(); }
        describeFilters();
    }

    private void describeFilters() {
        captureButton.setText("Capture filter: " + captureFilter.summary("Capturing all items"));
        viewButton.setText("View filter: " + viewFilter.summary("Showing all items"));
    }

    /** Whether the capture filter, when it is applied, keeps this result. */
    private boolean captured(Result r) {
        return !applyCapture.isSelected() || captureFilter.accepts(r, "", false);
    }

    /** The progress line: thin, round-ended, filled as far as the attack has got. */
    private static final class ThinBar extends JComponent {
        private int max = 1, value;
        void setMaximum(int m) { max = Math.max(1, m); repaint(); }
        int getMaximum() { return max; }
        void setValue(int v) { value = Math.max(0, Math.min(max, v)); repaint(); }
        int getValue() { return value; }
        @Override public Dimension getPreferredSize() { return new Dimension(100, 14); }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int h = 6, y = (getHeight() - h) / 2 - 1;
            g2.setColor(Ui.GRID);
            g2.fillRoundRect(0, y, getWidth(), h, h, h);
            int w = (int) Math.round(getWidth() * (value / (double) max));
            if (w > 0) {
                g2.setColor(opensuite.ui.Theme.CONTROL);
                g2.fillRoundRect(0, y, Math.max(w, h), h, h, h);
            }
            g2.dispose();
        }
    }

    @SuppressWarnings("unchecked")
    /** Hide the rows the view filter does not want. */
    private void applyViewFilter() {
        if (!(table.getRowSorter() instanceof javax.swing.table.TableRowSorter<?> rs)) return;
        @SuppressWarnings("unchecked")
        javax.swing.table.TableRowSorter<javax.swing.table.TableModel> sorter = (javax.swing.table.TableRowSorter<javax.swing.table.TableModel>) rs;
        final AttackFilter f = viewFilter;
        if (f.all()) { sorter.setRowFilter(null); return; }
        sorter.setRowFilter(new javax.swing.RowFilter<javax.swing.table.TableModel, Integer>() {
            @Override public boolean include(Entry<? extends javax.swing.table.TableModel, ? extends Integer> e) {
                int row = e.getIdentifier();
                if (row < 0 || row >= rows.size()) return true;
                Result r = rows.get(row);
                Object comment = e.getValue(10);
                return f.accepts(r, comment == null ? "" : comment.toString(), highlights.containsKey(r.number()));
            }
        });
    }

    /** The menu on a row: the colour it is picked out in, and its comment. */
    private void rowMenu(java.awt.event.MouseEvent e) {
        int view = table.rowAtPoint(e.getPoint());
        if (view < 0) return;
        if (!table.isRowSelected(view)) table.setRowSelectionInterval(view, view);
        final int[] chosen = table.getSelectedRows();
        JPopupMenu m = new JPopupMenu();
        JMenu highlight = new JMenu("Highlight");
        highlight.setFont(Ui.PLAIN);
        for (String[] c : new String[][]{ { "", "None" }, { "#ff6b6b", "Red" }, { "#ffa94d", "Orange" }, { "#ffe066", "Yellow" },
                { "#8ce99a", "Green" }, { "#66d9e8", "Cyan" }, { "#74c0fc", "Blue" }, { "#faa2c1", "Pink" }, { "#e599f7", "Magenta" },
                { "#ced4da", "Grey" } }) {
            JMenuItem mi = new JMenuItem(c[1]);
            mi.setFont(Ui.PLAIN);
            if (!c[0].isEmpty()) { mi.setOpaque(true); mi.setBackground(Color.decode(c[0])); mi.setForeground(Color.BLACK); }
            mi.addActionListener(a -> {
                for (int v : chosen) {
                    int number = rows.get(table.convertRowIndexToModel(v)).number();
                    if (c[0].isEmpty()) highlights.remove(number); else highlights.put(number, Color.decode(c[0]));
                }
                if (viewFilter.highlightedOnly) applyViewFilter();
                table.repaint();
            });
            highlight.add(mi);
        }
        m.add(highlight);
        JMenuItem comment = new JMenuItem("Add comment");
        comment.setFont(Ui.PLAIN);
        comment.addActionListener(a -> {
            int row = table.convertRowIndexToModel(chosen[0]);
            Object now = model.getValueAt(row, 10);
            String typed = JOptionPane.showInputDialog(this, "Comment:", now == null ? "" : now.toString());
            if (typed == null) return;
            for (int v : chosen) model.setValueAt(typed, table.convertRowIndexToModel(v), 10);
            if (viewFilter.notesOnly) applyViewFilter();
        });
        m.add(comment);
        m.show(table, e.getX(), e.getY());
    }

    private void exportCsv() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Export results to CSV");
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
        try (java.io.PrintWriter w = new java.io.PrintWriter(fc.getSelectedFile(), java.nio.charset.StandardCharsets.UTF_8)) {
            int cols = model.getColumnCount();
            StringBuilder header = new StringBuilder();
            for (int c = 0; c < cols; c++) { if (c > 0) header.append(','); header.append(csv(model.getColumnName(c))); }
            w.println(header);
            for (int r = 0; r < model.getRowCount(); r++) {
                StringBuilder line = new StringBuilder();
                for (int c = 0; c < cols; c++) {
                    if (c > 0) line.append(',');
                    Object v = model.getValueAt(r, c);
                    line.append(csv(v == null ? "" : v.toString()));
                }
                w.println(line);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Export failed: " + ex.getMessage());
        }
    }

    private static String csv(String s) {
        if (s.contains(",") || s.contains("\"") || s.contains("\n")) {
            return '"' + s.replace("\"", "\"\"") + '"';
        }
        return s;
    }

    public void setPauseControl(java.util.function.Consumer<Boolean> c) { this.pauseControl = c; }

    /** Save this attack to a file that Intruder > Open saved attack reads back. */
    private boolean saveAttack() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("save attack");
        fc.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Saved attack (*." + AttackFile.EXTENSION + ")", AttackFile.EXTENSION));
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return false;
        java.io.File f = fc.getSelectedFile();
        if (!f.getName().contains(".")) f = new java.io.File(f.getParentFile(), f.getName() + "." + AttackFile.EXTENSION);
        if (f.exists() && JOptionPane.showConfirmDialog(this, f.getName() + " already exists. Replace it?", "Save attack",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) return false;
        try (java.io.OutputStream out = new java.io.FileOutputStream(f)) {
            AttackFile.write(out, getTitle(), extraNames, extraClasses, new ArrayList<>(rows));
            status.setText("Saved to " + f.getName());
            return true;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not save the attack: " + ex.getMessage(), "Save attack", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    /** Ask for a saved attack file and show it in a results window of its own. */
    public static void openSaved(SuiteContext ctx, Component parent) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Open saved attack");
        // Attacks kept with the project are in the folder beside its file.
        if (ctx != null && ctx.projectFile() != null && attackFolder(ctx.projectFile()).isDirectory()) {
            fc.setCurrentDirectory(attackFolder(ctx.projectFile()));
        }
        fc.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Saved attack (*." + AttackFile.EXTENSION + ")", AttackFile.EXTENSION));
        if (fc.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION) return;
        java.io.File f = fc.getSelectedFile();
        try (java.io.InputStream in = new java.io.FileInputStream(f)) {
            AttackFile.Saved s = AttackFile.read(in);
            String title = (s.title() == null || s.title().isBlank() ? "Intruder attack" : s.title()) + " (saved: " + f.getName() + ")";
            ResultsWindow w = new ResultsWindow(ctx, title, s.extraColumns(), s.extraClasses(), true);
            w.setTotal(s.results().size());
            for (Result r : s.results()) w.addResult(r);
            w.finished();
            w.setVisible(true);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(parent, "Could not open the attack: " + ex.getMessage(), "Open saved attack", JOptionPane.ERROR_MESSAGE);
        }
    }

    /** Attack windows that are open or running out of sight, newest last. */
    private static final List<ResultsWindow> LIVE = new java.util.concurrent.CopyOnWriteArrayList<>();
    public static List<ResultsWindow> live() { return LIVE; }

    private volatile boolean done;

    /**
     * Closing follows Settings &gt; Tools &gt; Intruder: a running attack carries
     * on out of sight, is deleted, or the user is asked; a finished one is
     * saved with the project, kept in memory (out of sight, still listed under
     * Intruder > Attack results), deleted, or the user is asked.
     */
    private void confirmClose() {
        if (saved || keptWithProject) { discard(); return; }
        opensuite.core.Settings s = suite == null ? null : suite.settings();
        if (!done) {
            String how = s == null ? "ask" : s.get(IntruderSettingsPanel.CLOSE_RUNNING, "ask");
            if ("ask".equals(how)) {
                opensuite.ui.NoticeDialog.Answer a = opensuite.ui.NoticeDialog.ask(this, opensuite.ui.NoticeDialog.Kind.INFO,
                        "Close attack?", "This attack is still running. If continued in the background, it remains listed under "
                                + "Intruder > Attack results.", null, null, "Remember my choice", 1,
                        "Continue in background", "Discard");
                how = a.button() == 0 ? "background" : a.button() == 1 ? "delete" : "cancel";
                if (a.ticked() && !a.dismissed() && s != null) s.set(IntruderSettingsPanel.CLOSE_RUNNING, how);
            }
            if ("background".equals(how)) setVisible(false);   // still listed under Intruder > Attack results
            else if ("delete".equals(how)) discard();
            return;
        }
        String how = s == null ? "ask" : s.get(IntruderSettingsPanel.CLOSE_FINISHED, "ask");
        if ("ask".equals(how)) {
            opensuite.ui.NoticeDialog.Answer a = opensuite.ui.NoticeDialog.ask(this, opensuite.ui.NoticeDialog.Kind.INFO,
                    "Save attack?", "If you keep the attack in memory, you can open it again from Intruder > Attack results "
                            + "until you close Open Suite.", null, null, "Remember my choice", 2,
                    "Save to project file", "Keep in memory", "Discard");
            how = a.button() == 0 ? "save" : a.button() == 1 ? "memory" : a.button() == 2 ? "delete" : "cancel";
            if (a.ticked() && !a.dismissed() && s != null) s.set(IntruderSettingsPanel.CLOSE_FINISHED, how);
        }
        if ("save".equals(how)) { if (saveWithProject()) discard(); }
        else if ("memory".equals(how)) setVisible(false);
        else if ("delete".equals(how)) discard();
    }

    /** Stop the attack if it is running and let the window go. */
    private void discard() {
        if (!saved && !done && onClose != null) onClose.run();
        LIVE.remove(this);
        dispose();
    }

    /**
     * Keep a finished attack with the project: in a folder beside the project
     * file, where Intruder > Open saved attack starts looking. A project that
     * has no file yet asks where to put it instead.
     */
    private boolean saveWithProject() {
        java.io.File project = suite == null ? null : suite.projectFile();
        if (project == null) return saveAttack();
        java.io.File dir = attackFolder(project);
        if (!dir.isDirectory() && !dir.mkdirs()) return saveAttack();
        String base = getTitle().replaceAll("[^A-Za-z0-9._-]+", "-");
        java.io.File f = new java.io.File(dir, base + "." + AttackFile.EXTENSION);
        for (int n = 2; f.exists(); n++) f = new java.io.File(dir, base + "-" + n + "." + AttackFile.EXTENSION);
        try (java.io.OutputStream out = new java.io.FileOutputStream(f)) {
            AttackFile.write(out, getTitle(), extraNames, extraClasses, new ArrayList<>(rows));
            return true;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Could not save the attack: " + ex.getMessage(), "Save attack", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    /** Where a project keeps its saved attacks: a folder named after the project file. */
    public static java.io.File attackFolder(java.io.File project) {
        return new java.io.File(project.getAbsoluteFile().getParentFile(), project.getName() + ".attacks");
    }

    private Runnable onClose;
    public void setOnClose(Runnable r) { this.onClose = r; }

    /** Set the total number of requests expected. */
    public void setTotal(int total) {
        SwingUtilities.invokeLater(() -> {
            progress.setMaximum(Math.max(total, 1));
            progress.setValue(0);
            status.setText(saved ? "Finished" : "Running");
        });
    }

    /** Append one completed result. Safe to call off the EDT. */
    public void addResult(Result r) {
        SwingUtilities.invokeLater(() -> {
            progress.setValue(progress.getValue() + 1);
            if (!captured(r)) return;
            rows.add(r);
            Object[] row = new Object[model.getColumnCount()];
            row[0] = r.number();
            row[1] = r.payload();
            row[2] = r.status() > 0 ? r.status() : null;
            // When the request went out; how long the first byte took, and the whole response.
            row[3] = (r.sentAt() > 0 ? java.time.LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(r.sentAt()),
                    java.time.ZoneId.systemDefault()) : java.time.LocalDateTime.now()).format(TIME_OF_DAY);
            row[4] = r.response() != null ? (r.firstByte() >= 0 ? Math.min(r.firstByte(), r.millis()) : r.millis()) : null;
            row[5] = r.response() != null ? r.millis() : null;
            boolean failed = r.error() != null && !r.error().isEmpty();
            boolean timedOut = failed && r.error().toLowerCase().contains("timed out");
            row[6] = failed && !timedOut;
            row[7] = timedOut;
            row[8] = r.response() != null ? r.length() : null;
            row[9] = cookies(r.response());
            row[10] = "";
            for (int i = 0; i < r.extra().length && FIXED + i < row.length; i++) {
                row[FIXED + i] = r.extra()[i];
            }
            model.addRow(row);
        });
    }

    /** Settings > Save attack: write the attack beside the project file when it finishes. */
    public void setSaveToProject(boolean on) { saveToProject = on; }
    private volatile boolean saveToProject;
    private volatile boolean keptWithProject;

    public void finished() {
        done = true;
        if (saveToProject && !keptWithProject) {
            SwingUtilities.invokeLater(() -> { if (!keptWithProject && saveWithProject()) keptWithProject = true; });
        }
        SwingUtilities.invokeLater(() -> { progress.setValue(progress.getMaximum()); status.setText("Finished"); });
    }

    /** The attack auto-paused on result {@code number}; tell the user why. */
    public void autoPaused(int number) {
        SwingUtilities.invokeLater(() -> { paused = true; status.setText("Paused at request " + number); });
    }

    private void showSelected() {
        int view = table.getSelectedRow();
        if (view < 0) { pair.setBlank(true); return; }
        int modelRow = table.convertRowIndexToModel(view);
        if (modelRow < 0 || modelRow >= rows.size()) return;
        Result r = rows.get(modelRow);
        pair.request().setMessage(r.svc(), r.request() == null ? new HttpMessage(new byte[0]) : r.request());
        if (r.response() != null) pair.response().setMessage(r.svc(), r.response(), r.request());
        else pair.response().setMessage(r.svc(), new HttpMessage(new byte[0]));
        pair.setBlank(false);
        String error = r.error();
        table.setToolTipText(error == null || error.isEmpty() ? null : error);
    }
}