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.

13.1 KB
Raw Blame
package opensuite.target;

import opensuite.core.Issue;
import opensuite.engine.ZapApi;
import opensuite.engine.ZapEngine;
import opensuite.spider.Cdp.JsonValue;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

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

/**
 * The Target > Issues tab: a catalogue of every issue the scan engine can
 * detect, an "Issue definitions" reference. Populated from the engine's
 * active and passive scan rules, loaded lazily the first time it is shown.
 * Laid out as the reference lays its own out: the list on the left under a
 * heading, the chosen definition on the right, Open in browser above it.
 */
public class IssueDefinitionsPanel extends JPanel {

    /** Where the engine's own page for a rule lives. */
    static final String RULE_PAGE = "https://www.zaproxy.org/docs/alerts/";

    private final Model model = new Model();
    private final JTextPane detail = new JTextPane();
    private final Supplier<List<Issue>> raised;
    private final JButton open = Ui.button("Open in browser", "Open the scan engine's page for the selected definition");
    private JTable table;
    private boolean loaded;

    public IssueDefinitionsPanel() { this(List::of); }

    /** @param raised the issues found so far; a rule's typical severity is the highest it has actually been raised at */
    public IssueDefinitionsPanel(Supplier<List<Issue>> raised) {
        super(new BorderLayout());
        this.raised = raised == null ? List::of : raised;
        setBackground(Theme.BG);

        JLabel title = Ui.heading("Issue definitions");
        JLabel note = Ui.label("This listing contains the definitions of all issues that can be detected by the scan engine.");
        note.setForeground(Theme.TEXT);
        open.setIcon(globe());
        open.setIconTextGap(8);
        open.setBorder(Ui.pad(3, 11, 3, 21));
        open.setEnabled(false);
        open.addActionListener(e -> openSelected());
        JPanel head = new JPanel(null) {
            @Override public Dimension getPreferredSize() { return new Dimension(400, 69); }
            @Override public void doLayout() {
                title.setBounds(10, 8, 400, Ui.tall(22));
                note.setBounds(10, 37, Math.max(0, getWidth() - 20), 18);
                open.setBounds(getWidth() - 157, 10, 147, Ui.tall(22));
            }
        };
        head.setOpaque(false);
        head.add(title);
        head.add(note);
        head.add(open);

        table = new JTable(model);
        Ui.styleTable(table);
        Ui.exactWidths(table, 307, 100, 101);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        javax.swing.table.TableRowSorter<Model> sorter = new opensuite.ui.NumberSorter<>(model);
        // Severities sort by weight and type indexes by number, not as text.
        sorter.setComparator(1, java.util.Comparator.comparingInt(IssueDefinitionsPanel::weight));
        sorter.setComparator(2, java.util.Comparator.comparingLong(IssueDefinitionsPanel::number));
        sorter.setSortKeys(List.of(new RowSorter.SortKey(2, SortOrder.ASCENDING)));
        table.setRowSorter(sorter);
        table.getSelectionModel().addListSelectionListener(e -> showDetail());

        detail.setEditorKit(Theme.htmlKit());
        detail.setEditable(false);
        detail.setFont(Ui.PLAIN);
        detail.setBorder(Ui.pad(8, 14, 8, 13));
        detail.setBackground(Theme.BG);
        detail.addHyperlinkListener(e -> {
            if (e.getEventType() == javax.swing.event.HyperlinkEvent.EventType.ACTIVATED && e.getURL() != null)
                opensuite.ui.AboutDialog.open(e.getURL().toString());
        });

        JScrollPane left = Ui.scroll(table), right = Ui.scroll(detail);
        left.setBorder(BorderFactory.createEmptyBorder());
        right.setBorder(BorderFactory.createEmptyBorder());
        left.setMinimumSize(new Dimension(120, 60));
        left.getVerticalScrollBar().setPreferredSize(new Dimension(8, 0));
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
        split.setUI(new javax.swing.plaf.basic.BasicSplitPaneUI() {
            @Override public javax.swing.plaf.basic.BasicSplitPaneDivider createDefaultDivider() {
                return new javax.swing.plaf.basic.BasicSplitPaneDivider(this) {
                    // Three hairlines down its length, as the reference marks this divider.
                    @Override public void paint(Graphics g) {
                        g.setColor(Theme.BG);
                        g.fillRect(0, 0, getWidth(), getHeight());
                        g.setColor(Theme.BORDER);
                        for (int x : new int[]{ 2, 5, 8 }) g.fillRect(x, 0, 1, getHeight());
                    }
                };
            }
        });
        split.setDividerSize(10);
        split.setBorder(BorderFactory.createEmptyBorder());
        split.setContinuousLayout(true);
        split.setDividerLocation(514);

        JPanel body = new JPanel(new BorderLayout());
        body.setOpaque(false);
        body.setBorder(BorderFactory.createCompoundBorder(Ui.pad(0, 10, 10, 10), BorderFactory.createMatteBorder(1, 1, 1, 1, Theme.BORDER)));
        body.add(split, BorderLayout.CENTER);

        add(head, BorderLayout.NORTH);
        add(body, BorderLayout.CENTER);

        addHierarchyListener(e -> {
            if ((e.getChangeFlags() & java.awt.event.HierarchyEvent.SHOWING_CHANGED) != 0
                    && isShowing() && !loaded) load();
        });
    }

    /** A plain globe: a circle, its equator and one meridian. */
    private static Icon globe() {
        return new Icon() {
            @Override public int getIconWidth() { return 14; }
            @Override public int getIconHeight() { return 14; }
            @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.setColor(c.isEnabled() ? Theme.TEXT : Theme.MUTED);
                g2.setStroke(new BasicStroke(1.1f));
                g2.draw(new java.awt.geom.Ellipse2D.Float(x + 0.7f, y + 0.7f, 12.6f, 12.6f));
                g2.draw(new java.awt.geom.Ellipse2D.Float(x + 4.2f, y + 0.7f, 5.6f, 12.6f));
                g2.draw(new java.awt.geom.Line2D.Float(x + 0.7f, y + 7f, x + 13.3f, y + 7f));
                g2.dispose();
            }
        };
    }

    private void load() {
        loaded = true;
        ZapEngine ze = ZapEngine.shared();
        if (ze == null || !ze.available()) {
            detail.setText("<html><body style='font-family:sans-serif'><i>Scan engine (ZAP) not installed. "
                    + "Run ./fetch-zap.sh to add it.</i></body></html>");
            return;
        }
        new Thread(() -> {
            try {
                ze.start();
                ZapApi api = ze.api();
                List<Def> defs = new ArrayList<>();
                for (JsonValue s : api.activeScanners())
                    defs.add(new Def(nz(ZapApi.str(s, "name")), "active", nz(ZapApi.str(s, "id")), nz(ZapApi.str(s, "cweId")), nz(ZapApi.str(s, "wascId"))));
                for (JsonValue s : api.passiveScanners())
                    defs.add(new Def(nz(ZapApi.str(s, "name")), "passive", nz(ZapApi.str(s, "id")), "", ""));
                List<Issue> seen = raised.get();
                SwingUtilities.invokeLater(() -> {
                    model.set(defs, seen);
                    if (table.getRowCount() > 0) table.setRowSelectionInterval(0, 0);
                });
            } catch (Exception ex) {
                SwingUtilities.invokeLater(() -> detail.setText(
                        "<html><body style='font-family:sans-serif'><i>Could not load issue definitions: "
                        + esc(String.valueOf(ex.getMessage())) + "</i></body></html>"));
            }
        }, "issue-defs-load").start();
    }

    private Def selected() {
        int r = table.getSelectedRow();
        return r < 0 ? null : model.at(table.convertRowIndexToModel(r));
    }

    private void openSelected() {
        Def d = selected();
        if (d != null && d.id.matches("\\d+")) opensuite.ui.AboutDialog.open(RULE_PAGE + number(d.id) + "/");
    }

    private void showDetail() {
        Def d = selected();
        open.setEnabled(d != null && d.id.matches("\\d+"));
        if (d == null) { detail.setText(""); return; }
        detail.setText(describe(d, model.severityOf(d)));
        detail.setCaretPosition(0);
    }

    private static final int TITLE_GAP = 5, FIRST_GAP = 15, HEAD_GAP = 18, TEXT_GAP = 6;

    /** The definition as the right-hand pane shows it, in the reference's order of headings. */
    static String describe(Def d, String severity) {
        // Spacing measured from the reference: heading, then its text 27px on, the next heading 40px after that.
        String h = "<p style='margin:" + HEAD_GAP + "px 0 0 0'><b>", t = "<p style='margin:" + TEXT_GAP + "px 0 0 0'>", l = "<ul style='margin:" + TEXT_GAP + "px 0 0 18px;padding:0'>";
        StringBuilder b = new StringBuilder("<html><body style='font-family:sans-serif;font-size:10px;margin:0'>");
        b.append("<p style='font-size:11px;margin:" + TITLE_GAP + "px 0 0 0'><b>").append(esc(d.name)).append("</b></p>");
        b.append("<p style='margin:" + FIRST_GAP + "px 0 0 0'><b>").append("Description</b></p>").append(t)
         .append(d.type.equals("active")
                 ? "An active scan rule: the engine sends crafted requests to each insertion point and raises this issue when the response indicates the vulnerability."
                 : "A passive scan rule: the engine raises this issue from traffic that has already passed through the proxy, without sending any additional requests.")
         .append("</p>");
        b.append(h).append("References</b></p>").append(l).append("<li><a href='").append(RULE_PAGE).append(number(d.id)).append("/'>The scan engine's page for this rule</a></li></ul>");
        if (number(d.cwe) > 0 || number(d.wasc) > 0) {
            b.append(h).append("Vulnerability classifications</b></p>").append(l);
            if (number(d.cwe) > 0) b.append("<li><a href='https://cwe.mitre.org/data/definitions/").append(number(d.cwe)).append(".html'>CWE-").append(number(d.cwe)).append("</a></li>");
            if (number(d.wasc) > 0) b.append("<li>WASC-").append(number(d.wasc)).append("</li>");
            b.append("</ul>");
        }
        b.append(h).append("Typical severity</b></p>").append(t).append(esc(severity)).append("</p>");
        b.append(h).append("Type index</b></p>").append(t).append(esc(d.id)).append("</p>");
        return b.append("</body></html>").toString();
    }

    /**
     * The severity a rule is typically raised at. The engine's rule list does
     * not say, so it is the highest this rule has been raised at in this
     * project; before it has been raised at all, there is nothing to go on.
     */
    static String typicalSeverity(String id, List<Issue> raised) {
        long want = number(id);
        Issue.Severity top = null;
        if (want > 0 && raised != null) for (Issue i : raised) {
            if (i.moduleId() == want && (top == null || i.severity().ordinal() < top.ordinal())) top = i.severity();
        }
        return top == null ? "Varies" : top.label();
    }

    static long number(String s) {
        try { return s == null ? -1 : Long.parseLong(s.trim()); } catch (NumberFormatException e) { return -1; }
    }

    /** Heavier first: High, Medium, Low, Information, then rules with nothing to go on. */
    static int weight(String severity) {
        for (Issue.Severity s : Issue.Severity.values()) if (s.label().equalsIgnoreCase(severity)) return s.ordinal();
        return Issue.Severity.values().length;
    }

    private static String nz(String s) { return s == null ? "" : s; }
    private static String esc(String s) {
        return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }

    record Def(String name, String type, String id, String cwe, String wasc) {}

    private static final class Model extends AbstractTableModel {
        private final String[] cols = {"Name", "Typical severity", "Type index"};
        private List<Def> rows = new ArrayList<>();
        private List<Issue> seen = List.of();
        void set(List<Def> d, List<Issue> raised) { rows = d; seen = raised == null ? List.of() : raised; fireTableDataChanged(); }
        Def at(int r) { return r >= 0 && r < rows.size() ? rows.get(r) : null; }
        String severityOf(Def d) { return typicalSeverity(d.id, seen); }
        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return String.class; }
        @Override public Object getValueAt(int r, int c) {
            Def d = rows.get(r);
            return switch (c) { case 0 -> d.name; case 1 -> severityOf(d); default -> d.id; };
        }
    }
}