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.

32.1 KB
Raw Blame
package opensuite.dashboard;

import opensuite.core.SuiteContext;
import opensuite.ui.CustomScopePanel;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * The New scan wizard: a left step rail and a content area, with Cancel /
 * Previous / Next / Scan along the bottom. Only "Scan type" is shown until a
 * type is chosen; the rail then shows that type's steps. Crawl and audit and
 * Crawl share Scan details, Scan configuration, Application login and Resource
 * pool; API-only scan has API definition and API details instead of details
 * and login. The dialog only gathers configuration; the caller reads the
 * getters and starts the scan.
 */
public class NewScanWizard extends JDialog {

    private static final String[] WEB_STEPS = {
            "Scan type", "Scan details", "Scan configuration", "Application login", "Resource pool"};
    private static final String[] WEB_ICONS = {"type", "details", "config", "login", "pool"};
    private static final String[] API_STEPS = {
            "Scan type", "API definition", "API details", "Scan configuration", "Resource pool"};
    private static final String[] API_ICONS = {"type", "api", "details", "config", "pool"};

    private final CardLayout cards = new CardLayout();
    private final JPanel content = new JPanel(cards);
    private final JPanel railPanel = new JPanel();
    private JToggleButton[] rail = new JToggleButton[0];
    private String[] steps = WEB_STEPS;
    private String[] icons = WEB_ICONS;
    private int step;
    private boolean typeChosen;

    private final JRadioButton typeCrawlAudit = new JRadioButton();
    private final JRadioButton typeCrawl = new JRadioButton();
    private final JRadioButton typeApiOnly = new JRadioButton();
    private final JTextArea urls = new JTextArea();
    private final JRadioButton pHttpHttps = Ui.radio("Scan using HTTP & HTTPS", true);
    private final JRadioButton pSpecified = Ui.radio("Scan using my specified protocols", false);
    private final JCheckBox isolated = Ui.check("Run isolated scan", false);
    private final JCheckBox perSite = Ui.check("Run a separate scan for each URL", false);
    private CustomScopePanel scopePanel;
    private final ScanConfigPanel webConfig = new ScanConfigPanel(ScanConfigPanel.Mode.CRAWL_AND_AUDIT);
    private final ScanConfigPanel apiConfig = new ScanConfigPanel(ScanConfigPanel.Mode.AUDIT);
    private ApplicationLoginPanel login;
    private final ApiDefinitionPanel apiDefinition = new ApiDefinitionPanel();
    private final ApiDetailsPanel apiDetails = new ApiDetailsPanel(() -> selectStepNamed("API definition"));
    private final opensuite.ui.ResourcePoolPanel resourcePool = new opensuite.ui.ResourcePoolPanel();

    private JButton prevButton, nextButton, scanButton;
    private boolean started;

    public NewScanWizard(SuiteContext ctx, Frame owner) {
        super(owner, "New scan", true);
        // Cancel and Scan both dispose; make the window-manager close do the
        // same rather than only hiding this heavy five-step dialog.
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        content.add(buildScanType(), "Scan type");
        content.add(buildScanDetails(ctx), "Scan details");
        content.add(stepPanel("Scan configuration", null, webConfig), "Scan configuration");
        webConfig.requireChoice();
        apiConfig.requireChoice();
        login = new ApplicationLoginPanel(ctx, this::targetUrls);
        content.add(stepPanel("Application login", "Configure how the scan logs in and maintains its session.", login), "Application login");
        content.add(stepPanel("Resource pool", "Specify the resources the scan may use.", resourcePool), "Resource pool");
        content.add(stepPanel("API definition", "Upload the definition of the API to scan.", apiDefinition), "API definition");
        content.add(stepPanel("API details", "Endpoints included in the scan.", apiDetails), "API details");
        content.add(stepPanel("Scan configuration ", null, apiConfig), "API configuration");
        apiDefinition.onChange(() -> apiDetails.show(apiDefinition.endpoints(), apiDefinition.source(), apiDefinition.baseUrl()));

        railPanel.setLayout(new BoxLayout(railPanel, BoxLayout.Y_AXIS));
        // The step list is a narrow white column with a line down its right side, as the reference's.
        railPanel.setBackground(Theme.CARD);
        JPanel railWrap = new JPanel(new BorderLayout());
        railWrap.add(railPanel, BorderLayout.NORTH);
        railWrap.setBackground(Theme.CARD);
        railWrap.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Ui.GRID));
        railWrap.setPreferredSize(new Dimension(RAIL_WIDTH + 8 * Ui.fontGrowth(), 10));
        buildRail();

        setLayout(new BorderLayout());
        add(railWrap, BorderLayout.WEST);
        add(content, BorderLayout.CENTER);
        add(buildButtons(), BorderLayout.SOUTH);
        selectStep(0);
        revealSteps(false);

        setSize(1000 + 70 * Ui.fontGrowth(), 680 + 40 * Ui.fontGrowth());
        setLocationRelativeTo(owner);
    }

    // ---- getters the caller reads after the dialog closes ----

    public boolean started()       { return started; }
    public boolean crawlAndAudit() { return typeCrawlAudit.isSelected() || typeApiOnly.isSelected(); }
    public boolean apiOnly()       { return typeApiOnly.isSelected(); }
    public boolean isolated()      { return isolated.isSelected(); }
    /** Whether every URL listed is to be its own crawl and audit, with its own tasks, rather than one job for all. */
    public boolean perSite()       { return perSite.isSelected() && targetUrls().size() > 1; }
    public int threads()           { return resourcePool.concurrency(); }
    public opensuite.core.ResourcePool resourcePool() { return resourcePool.selected(); }
    public ApplicationLoginPanel login() { return login; }
    public ApiDefinitionPanel apiDefinition() { return apiDefinition; }

    public String targetUrl() {
        java.util.List<String> all = targetUrls();
        return all.isEmpty() ? "" : all.get(0);
    }

    /** Every URL to scan: the list typed in, or the API's endpoints. */
    /** Fill in the address the scan was asked for from elsewhere; the rest is still the user's to choose. */
    public void startOn(String url) { urls.setText(url); }

    public java.util.List<String> targetUrls() {
        if (typeApiOnly.isSelected()) return apiDefinition.seedUrls();
        java.util.List<String> out = new java.util.ArrayList<>();
        for (String line : urls.getText().split("\n")) {
            String t = line.trim();
            if (!t.isEmpty()) out.add(t);
        }
        return out;
    }

    /** The engine settings implied by the chosen configuration. */
    public opensuite.engine.ScanConfig config() {
        return typeApiOnly.isSelected() ? apiConfig.config() : webConfig.config();
    }

    /** The scope the user drew up under "Detailed scope configuration", or null for the default. */
    public opensuite.core.Scope customScope() {
        return scopePanel == null || scopePanel.isEmpty() ? null : scopePanel.scope();
    }

    // ---- left rail ----

    private void buildRail() {
        railPanel.removeAll();
        rail = new JToggleButton[steps.length];
        ButtonGroup g = new ButtonGroup();
        for (int i = 0; i < steps.length; i++) {
            final int idx = i;
            JToggleButton b = new JToggleButton(
                    "<html><div style='text-align:center'>" + railLabel(steps[i]) + "</div></html>");
            b.setFont(Ui.PLAIN);
            b.setFocusable(false);
            b.setContentAreaFilled(false);
            b.setOpaque(true);
            b.setBackground(Theme.CARD);
            b.setHorizontalTextPosition(SwingConstants.CENTER);
            b.setVerticalTextPosition(SwingConstants.BOTTOM);
            b.setBorder(Ui.pad(12, 4, 12, 4));
            b.setAlignmentX(Component.CENTER_ALIGNMENT);
            b.setMaximumSize(new Dimension(Integer.MAX_VALUE, 80 + 6 * Ui.fontGrowth()));
            b.addActionListener(e -> selectStep(idx));
            g.add(b);
            rail[i] = b;
            railPanel.add(b);
        }
        railPanel.revalidate();
        railPanel.repaint();
    }

    private void revealSteps(boolean show) {
        for (int k = 1; k < rail.length; k++) rail[k].setVisible(show);
        railPanel.revalidate();
        railPanel.repaint();
    }

    private String cardFor(int i) {
        String s = steps[i];
        return "Scan configuration".equals(s) && typeApiOnly.isSelected() ? "API configuration" : s;
    }

    private void selectStepNamed(String name) {
        for (int i = 0; i < steps.length; i++) if (steps[i].equals(name)) { selectStep(i); return; }
    }

    private void selectStep(int i) {
        if (!typeChosen) i = 0;
        step = Math.max(0, Math.min(steps.length - 1, i));
        for (int k = 0; k < rail.length; k++) {
            boolean on = k == step;
            rail[k].setSelected(on);
            rail[k].setBackground(on ? Theme.CONTROL : Theme.CARD);
            rail[k].setForeground(on ? Color.WHITE : Theme.TEXT);
            rail[k].setIcon(railIcon(icons[k], on ? Color.WHITE : Theme.MUTED));
        }
        cards.show(content, cardFor(step));
        // The login step reads the browser's session for the targets as they now stand.
        if ("Application login".equals(cardFor(step))) login.refresh();
        updateButtons();
    }

    // ---- step panels ----

    private JComponent buildScanType() {
        ButtonGroup g = new ButtonGroup();
        g.add(typeCrawlAudit); g.add(typeCrawl); g.add(typeApiOnly);
        JPanel cardsRow = new JPanel(new GridLayout(1, 3, 10, 0));
        cardsRow.setOpaque(false);
        cardsRow.add(typeCard(typeCrawlAudit, "Crawl and audit",
                "Maps the attack surface and identifies vulnerabilities. Scans the web application and any detected APIs"));
        cardsRow.add(typeCard(typeCrawl, "Crawl",
                "Maps the attack surface of the web application and any detected APIs"));
        cardsRow.add(typeCard(typeApiOnly, "API-only scan",
                "Offers additional configuration options"));
        JPanel wrap = new JPanel(new BorderLayout());
        wrap.setOpaque(false);
        wrap.add(cardsRow, BorderLayout.NORTH);
        return stepPanel("Scan type", "Select the type of scan you'd like to run.", wrap);
    }

    private static final int RAIL_WIDTH = 112;

    /** A step's name as the list shows it: on one line when short, else broken after its first word. */
    static String railLabel(String step) {
        String t = step.strip();
        int sp = t.indexOf(' ');
        return sp < 0 || t.length() <= 12 ? t : t.substring(0, sp) + "<br>" + t.substring(sp + 1);
    }

    /**
     * One scan type to choose: a rounded grey card with its dot to the left of
     * its name and description. The chosen card is white with a thin blue
     * line around it, as the reference draws it.
     */
    private JComponent typeCard(JRadioButton radio, String title, String desc) {
        JPanel card = new JPanel(new BorderLayout(14, 0)) {
            @Override protected void paintComponent(Graphics g0) {
                Graphics2D g = (Graphics2D) g0.create();
                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                boolean on = radio.isSelected();
                g.setColor(on ? Theme.CARD : Theme.SURFACE);
                g.fill(new java.awt.geom.RoundRectangle2D.Double(0.5, 0.5, getWidth() - 1, getHeight() - 1, 12, 12));
                if (on) {
                    g.setColor(Theme.CONTROL);
                    g.draw(new java.awt.geom.RoundRectangle2D.Double(0.5, 0.5, getWidth() - 1, getHeight() - 1, 12, 12));
                }
                g.dispose();
            }
        };
        card.setOpaque(false);
        card.setBorder(Ui.pad(26, 24, 16, 22));
        radio.setOpaque(false);
        JPanel dot = new JPanel(new GridBagLayout());
        dot.setOpaque(false);
        dot.add(radio);
        JTextArea text = Ui.note(desc);
        text.setForeground(Theme.TEXT);
        JPanel words = new JPanel(new BorderLayout(0, 12));
        words.setOpaque(false);
        JLabel name = Ui.bold(title);
        name.setFont(name.getFont().deriveFont(name.getFont().getSize2D() + 1f));
        words.add(name, BorderLayout.NORTH);
        words.add(text, BorderLayout.CENTER);
        card.add(dot, BorderLayout.WEST);
        card.add(words, BorderLayout.CENTER);
        card.setPreferredSize(new Dimension(230, 146 + 10 * Ui.fontGrowth()));
        Ui.wholeCardSelects(card, radio);
        radio.addActionListener(e -> onTypeChosen());
        radio.addItemListener(e -> card.repaint());
        return card;
    }

    /** A scan type was chosen: show its steps and enable Scan. */
    private void onTypeChosen() {
        String[] want = typeApiOnly.isSelected() ? API_STEPS : WEB_STEPS;
        if (!typeChosen || want != steps) {
            steps = want;
            icons = typeApiOnly.isSelected() ? API_ICONS : WEB_ICONS;
            buildRail();
        }
        typeChosen = true;
        revealSteps(true);
        selectStep(step);
        updateButtons();
    }

    /**
     * The sites the user's own browsing reached, newest first. Traffic the
     * scanner made is not counted: an address a crawl happened upon is not
     * one the user chose.
     */
    private static java.util.List<String> seenSites(SuiteContext ctx) {
        java.util.LinkedHashSet<String> out = new java.util.LinkedHashSet<>();
        try {
            java.util.List<opensuite.core.LogEntry> all = ctx.store().all();
            for (int i = all.size() - 1, looked = 0; i >= 0 && looked < 20000; i--, looked++) {
                opensuite.core.LogEntry e = all.get(i);
                if (e == null || e.service() == null || !"proxy".equals(e.tool()) || out.contains(e.service().url())) continue;
                // Only a site that has answered for itself, not a gateway's "could not reach it".
                if (e.error() != null && !e.error().isBlank()) continue;
                opensuite.core.HttpMessage answer = e.response();
                if (answer != null && answer.statusCode() > 0 && answer.statusCode() < 500) out.add(e.service().url());
            }
        } catch (RuntimeException ignored) { }
        return new java.util.ArrayList<>(out);
    }

    /**
     * Where a scan of a scope rule's host would start, when the rule itself
     * does not say: it names a host for any protocol or any port. The URL is
     * offered only when the user's own browsing reached exactly one site that
     * the rule covers. With none, or with several, nothing is offered: which
     * address to scan is the user's to state, never the tool's to guess.
     */
    static java.util.List<String> startingUrls(String protocol, String host, String port, java.util.Collection<String> seen) {
        boolean anyProtocol = protocol == null || protocol.isBlank() || "any".equalsIgnoreCase(protocol);
        boolean anyPort = port == null || !port.matches("\\d+");
        java.util.List<String> out = new java.util.ArrayList<>();
        for (String site : seen) {
            try {
                opensuite.core.HttpService svc = opensuite.core.HttpService.parse(site);
                if (!svc.host().equalsIgnoreCase(host)) continue;
                if (!anyProtocol && !site.toLowerCase(java.util.Locale.ROOT).startsWith(protocol.toLowerCase(java.util.Locale.ROOT) + "://")) continue;
                if (!anyPort && svc.port() != Integer.parseInt(port)) continue;
                String u = svc.url() + "/";
                if (!out.contains(u)) out.add(u);
            } catch (RuntimeException ignored) { }
        }
        return out.size() == 1 ? out : new java.util.ArrayList<>();
    }

    /** The same for a prefix rule written without a protocol: "host", "host:port" or either with a path. */
    static java.util.List<String> prefixUrls(String prefix, java.util.Collection<String> seen) {
        int slash = prefix.indexOf('/');
        String hostPort = slash < 0 ? prefix : prefix.substring(0, slash);
        String path = slash < 0 ? "/" : prefix.substring(slash);
        int colon = hostPort.lastIndexOf(':');
        boolean port = colon > 0 && hostPort.substring(colon + 1).matches("\\d+");
        java.util.List<String> out = new java.util.ArrayList<>();
        for (String u : startingUrls("any", port ? hostPort.substring(0, colon) : hostPort, port ? hostPort.substring(colon + 1) : "", seen))
            out.add(u.substring(0, u.length() - 1) + path);
        return out;
    }

    private JComponent buildScanDetails(SuiteContext ctx) {
        urls.setFont(Ui.MONO);
        StringBuilder sb = new StringBuilder();
        java.util.List<String> seen = null;
        try {
            for (var r : ctx.scope().include()) {
                if (!r.enabled) continue;
                if (r.isPrefix()) {
                    String p = r.prefix;
                    if (!p.contains("://")) {
                        // A prefix with no protocol does not say where to start: see startingUrls.
                        if (seen == null) seen = seenSites(ctx);
                        for (String u : prefixUrls(p, seen)) sb.append(u).append('\n');
                        continue;
                    }
                    if (!p.substring(p.indexOf("://") + 3).contains("/")) p = p + "/";
                    sb.append(p).append('\n');
                } else {
                    String host = opensuite.core.Scope.display(r.host);
                    if (!host.isBlank() && host.matches("[A-Za-z0-9.-]+")) {
                        if (seen == null) seen = seenSites(ctx);
                        for (String u : startingUrls(r.protocol, host, opensuite.core.Scope.display(r.port), seen)) sb.append(u).append('\n');
                    }
                }
            }
        } catch (Exception ignored) {}
        urls.setText(sb.toString());

        JScrollPane sp = Ui.scroll(urls);
        sp.setPreferredSize(new Dimension(500, 160));
        JTextArea urlsNote = Ui.note("Open Suite will begin crawling from these URLs, and by default includes everything "
                + "beneath the specified URLs' folders. One URL per line.");

        ButtonGroup pg = new ButtonGroup();
        pg.add(pHttpHttps); pg.add(pSpecified);
        JPanel protoRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        protoRow.setOpaque(false);
        protoRow.add(pHttpHttps); protoRow.add(Box.createHorizontalStrut(18)); protoRow.add(pSpecified);

        // Detailed scope configuration: an expander revealing the full scope control.
        scopePanel = new CustomScopePanel(sb.toString());
        scopePanel.setVisible(false);
        JButton scopeToggle = new JButton("› Detailed scope configuration");
        scopeToggle.setFont(Ui.PLAIN);
        scopeToggle.setBorder(Ui.pad(2, 0, 2, 0));
        scopeToggle.setContentAreaFilled(false);
        scopeToggle.setFocusPainted(false);
        scopeToggle.setHorizontalAlignment(SwingConstants.LEFT);
        scopeToggle.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        scopeToggle.addActionListener(e -> {
            boolean now = !scopePanel.isVisible();
            scopePanel.setVisible(now);
            scopeToggle.setText((now ? "⌄ " : "› ") + "Detailed scope configuration");
        });

        isolated.setToolTipText("The scan's findings are kept with the task rather than merged into the site map and issue log");

        // The page is as wide as the window gives it: notes wrap rather than push it sideways.
        JPanel body = new FitWidth();
        body.setOpaque(false);
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1;
        int row = 0;
        c.gridy = row++; c.fill = GridBagConstraints.BOTH; c.ipady = 120; body.add(sp, c);
        c.fill = GridBagConstraints.HORIZONTAL; c.ipady = 0;
        c.gridy = row++; c.insets = new Insets(6, 0, 14, 0); body.add(urlsNote, c);
        c.gridy = row++; c.insets = new Insets(0, 0, 6, 0); body.add(sectionLabel("Protocol settings"), c);
        c.gridy = row++; c.insets = new Insets(0, 0, 6, 0); body.add(protoRow, c);
        c.gridy = row++; c.insets = new Insets(0, 0, 6, 0); body.add(scopeToggle, c);
        c.gridy = row++; c.insets = new Insets(0, 0, 14, 0); body.add(scopePanel, c);
        c.gridy = row++; c.insets = new Insets(0, 0, 6, 0); body.add(sectionLabel("Advanced scan parameters"), c);
        c.gridy = row++; c.insets = new Insets(0, 0, 4, 0);
        body.add(Ui.note("Results from isolated scans do not appear in the Target site map or Issue activity log."), c);
        c.gridy = row++; c.insets = new Insets(0, 0, 0, 0); body.add(isolated, c);
        perSite.setToolTipText("With several URLs listed, each gets its own tasks on the dashboard, to pause, stop or report on by itself");
        perSite.setOpaque(false);
        c.gridy = row++; c.insets = new Insets(6, 0, 0, 0); body.add(perSite, c);
        c.gridy = row; c.weighty = 1; c.fill = GridBagConstraints.BOTH; body.add(Box.createGlue(), c);

        return stepPanel("URLs to scan", "Define the URLs to scan. Open Suite will begin crawling from these URLs.", clear(Ui.scrollPlain(body)));
    }

    /** A grid that takes the width of the scroll pane it sits in and scrolls only downwards. */
    private static final class FitWidth extends JPanel implements Scrollable {
        FitWidth() { super(new GridBagLayout()); }
        @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); }
        @Override public int getScrollableUnitIncrement(Rectangle r, int o, int d) { return 16; }
        @Override public int getScrollableBlockIncrement(Rectangle r, int o, int d) { return 160; }
        @Override public boolean getScrollableTracksViewportWidth() { return true; }
        @Override public boolean getScrollableTracksViewportHeight() { return false; }
    }

    /** A scrolling page with no frame or ground of its own: it sits on the step's, level with its heading. */
    private static JScrollPane clear(JScrollPane sp) {
        sp.setOpaque(false);
        sp.getViewport().setOpaque(false);
        return sp;
    }

    private JComponent stepPanel(String title, String subtitle, JComponent body) {
        JPanel p = new JPanel(new BorderLayout(0, 10));
        p.setBackground(Theme.BG);
        p.setBorder(Ui.pad(16, 20, 16, 20));
        JPanel titles = new JPanel(new BorderLayout());
        titles.setOpaque(false);
        titles.add(Ui.heading(title), BorderLayout.NORTH);
        if (subtitle != null) titles.add(Ui.note(subtitle), BorderLayout.CENTER);
        p.add(titles, BorderLayout.NORTH);
        p.add(body, BorderLayout.CENTER);
        return p;
    }

    private static JLabel sectionLabel(String text) {
        JLabel l = Ui.bold(text);
        l.setAlignmentX(Component.LEFT_ALIGNMENT);
        return l;
    }

    // ---- bottom buttons ----

    private JComponent buildButtons() {
        JButton help = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.help(), "About the New scan wizard", () ->
                JOptionPane.showMessageDialog(this, "Select a scan type, then complete the steps on the left.\n"
                        + "The Scan button starts the task on the dashboard.", "New scan", JOptionPane.INFORMATION_MESSAGE));
        JButton cancel = Ui.button("Cancel");
        prevButton = Ui.button("← Previous");
        nextButton = Ui.button("Next →");
        scanButton = Ui.button("Scan");
        scanButton.setIcon(scanMarkIcon(java.awt.Color.WHITE, 1.25f));   // white, as the word beside it is on this button
        scanButton.setHorizontalTextPosition(SwingConstants.LEADING);
        scanButton.setIconTextGap(6);
        scanButton.setEnabled(false);
        cancel.addActionListener(e -> { started = false; dispose(); });
        prevButton.addActionListener(e -> selectStep(step - 1));
        nextButton.addActionListener(e -> selectStep(step + 1));
        scanButton.addActionListener(e -> doScan());

        JPanel bar = new JPanel(new BorderLayout());
        bar.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Ui.GRID));
        JPanel l = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 6));
        l.add(help);
        JPanel r = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 6));
        Ui.sameSize(cancel, prevButton, nextButton, scanButton);
        r.add(cancel); r.add(prevButton); r.add(nextButton); r.add(scanButton);
        bar.add(l, BorderLayout.WEST);
        bar.add(r, BorderLayout.EAST);
        return bar;
    }

    private void updateButtons() {
        prevButton.setEnabled(step > 0);
        nextButton.setEnabled(typeChosen && step < steps.length - 1);
        scanButton.setEnabled(typeChosen);
        scanButton.putClientProperty(Theme.PRIMARY, typeChosen ? Boolean.TRUE : Boolean.FALSE);
        scanButton.repaint();
    }

    private void doScan() {
        if (typeApiOnly.isSelected()) {
            if (apiDefinition.endpoints().isEmpty()) {
                selectStepNamed("API definition");
                JOptionPane.showMessageDialog(this, "Upload an API definition first.", "New scan", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (targetUrls().isEmpty()) {
                selectStepNamed("API definition");
                JOptionPane.showMessageDialog(this, "The definition has no base URL. Enter the definition's URL so that the server can be identified.",
                        "New scan", JOptionPane.WARNING_MESSAGE);
                return;
            }
        } else {
            if (!webConfig.chosen()) {
                selectStepNamed("Scan configuration");
                JOptionPane.showMessageDialog(this, "Select a scan configuration.", "New scan", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (targetUrl().isEmpty()) {
                selectStep(1);
                JOptionPane.showMessageDialog(this, "Enter at least one URL to scan.", "New scan", JOptionPane.WARNING_MESSAGE);
                return;
            }
            if (opensuite.core.HttpService.parse(targetUrl()) == null) {
                selectStep(1);
                JOptionPane.showMessageDialog(this, "Could not parse that URL. Use the form https://host/path.", "New scan", JOptionPane.WARNING_MESSAGE);
                return;
            }
        }
        if (typeApiOnly.isSelected() && !apiConfig.chosen()) {
            selectStepNamed("Scan configuration");
            JOptionPane.showMessageDialog(this, "Select a scan configuration.", "New scan", JOptionPane.WARNING_MESSAGE);
            return;
        }
        started = true;
        dispose();
    }

    // ---- icons ----

    /**
     * The scan mark, in a box 16 units square: a sweep opening to the right
     * from a point on the left, with a short trace across it. Drawn with the
     * stroke and colour already set.
     */
    static void drawScanMark(Graphics2D g) {
        java.awt.geom.Path2D.Double sweep = new java.awt.geom.Path2D.Double();
        sweep.moveTo(1.3, 8.0);
        sweep.lineTo(12.0, 1.7);
        sweep.quadTo(16.4, 8.0, 12.0, 14.3);
        sweep.closePath();
        g.draw(sweep);
        java.awt.geom.Path2D.Double trace = new java.awt.geom.Path2D.Double();
        trace.moveTo(6.1, 8.9); trace.lineTo(7.9, 7.3); trace.lineTo(8.9, 9.0); trace.lineTo(10.9, 7.4);
        g.draw(trace);
    }

    /**
     * The scan mark as a small icon beside a word: after Scan on its button,
     * before Crawling on a task's card, beside Task configuration. With no
     * colour given it takes the colour of the text it sits beside.
     */
    public static Icon scanMarkIcon(Color col, float stroke) {
        final double f = (15 + Ui.fontGrowth() / 2.0) / 16.0;
        final int size = (int) Math.round(16 * f);
        return new Icon() {
            @Override public int getIconWidth() { return size; }
            @Override public int getIconHeight() { return size; }
            @Override public void paintIcon(java.awt.Component c, java.awt.Graphics gr, int x, int y) {
                Graphics2D g = (Graphics2D) gr.create();
                g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
                g.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_PURE);
                g.translate(x, y);
                g.scale(f, f);
                g.setColor(col != null ? col : c.getForeground());
                g.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                drawScanMark(g);
                g.dispose();
            }
        };
    }

    /** A step's icon for the rail, drawn as it is painted so it stays sharp at any size. */
    static Icon railIcon(String kind, Color col) {
        final double f = (20 + Ui.fontGrowth() / 2.0) / 22.0;
        final int size = (int) Math.round(22 * f);
        return new Icon() {
            @Override public int getIconWidth() { return size; }
            @Override public int getIconHeight() { return size; }
            @Override public void paintIcon(java.awt.Component c, java.awt.Graphics gr, int x, int y) {
                Graphics2D g = (Graphics2D) gr.create();
                g.translate(x, y);
                g.scale(f, f);
                paintRail(g, kind, col);
                g.dispose();
            }
        };
    }

    private static void paintRail(Graphics2D g, String kind, Color col) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setColor(col);
        g.setStroke(new BasicStroke(1.45f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        switch (kind) {
            case "type" -> {
                // The scan mark's sweep without its trace, and a second curve
                // beyond it: the kinds of scan that can be sent out.
                g.translate(1.6, 2.6);
                g.scale(1.05, 1.05);
                java.awt.geom.Path2D.Double sweep = new java.awt.geom.Path2D.Double();
                sweep.moveTo(1.3, 8.0);
                sweep.lineTo(11.0, 1.9);
                sweep.quadTo(15.0, 8.0, 11.0, 14.1);
                sweep.closePath();
                g.draw(sweep);
                java.awt.geom.Path2D.Double outer = new java.awt.geom.Path2D.Double();
                outer.moveTo(14.0, 1.5);
                outer.quadTo(18.6, 8.0, 14.0, 14.5);
                g.draw(outer);
            }
            case "details" -> {
                g.translate(2.6, 2.6);
                g.scale(1.05, 1.05);
                drawScanMark(g);
            }
            case "config" -> {
                java.awt.geom.Path2D.Float gear = new java.awt.geom.Path2D.Float();
                double cx = 11, cy = 11, ro = 8.2, ri = 6.2;
                for (int i = 0; i < 16; i++) {
                    double a = Math.PI * i / 8 - Math.PI / 16;
                    double r = (i % 2 == 0) ? ro : ri;
                    double x = cx + r * Math.cos(a), y = cy + r * Math.sin(a);
                    if (i == 0) gear.moveTo(x, y); else gear.lineTo(x, y);
                }
                gear.closePath();
                g.draw(gear);
                g.drawOval(8, 8, 6, 6);
            }
            case "login" -> {
                g.drawLine(3, 11, 13, 11);
                g.drawLine(9, 7, 13, 11);
                g.drawLine(9, 15, 13, 11);
                g.drawLine(13, 3, 18, 3); g.drawLine(18, 3, 18, 19); g.drawLine(18, 19, 13, 19);
            }
            case "pool" -> {
                g.draw(new java.awt.geom.Arc2D.Float(3f, 4f, 15f, 15f, 90, 270, java.awt.geom.Arc2D.PIE));
                g.draw(new java.awt.geom.Arc2D.Float(6f, 1f, 15f, 15f, 0, 90, java.awt.geom.Arc2D.PIE));
            }
            case "api" -> {
                // Curly braces: a definition document.
                g.drawArc(3, 3, 6, 8, 90, 180);
                g.drawArc(3, 11, 6, 8, 90, 180);
                g.drawArc(13, 3, 6, 8, -90, 180);
                g.drawArc(13, 11, 6, 8, -90, 180);
                g.drawLine(9, 11, 13, 11);
            }
        }
    }
}