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.

24.6 KB
Raw Blame
package opensuite.dashboard;

import opensuite.ui.Glyphs;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.List;

/**
 * The Live crawl view. It has two faces, chosen with the two buttons at its
 * top: the browser, which is the page the scan's own browser has open now,
 * and the activity, which says in plain words what the scan is doing: its
 * stage, whether it is logged in, what it has found and the requests it sent
 * last. The browser is shown only while it is live: a picture of a page the
 * browser no longer has open would pass for what the scan is doing now. So
 * the view turns to the browser when the browser stage starts and back to
 * the activity when it ends, and the browser face then says it is not
 * crawling, as it did before the stage began.
 */
public final class CrawlGraph extends JPanel {

    private final CardLayout cards = new CardLayout();
    private final JPanel body = new JPanel(cards);
    private final JToggleButton browserFace = Ui.chip("Browser"), activityFace = Ui.chip("Activity");
    private final JPanel faces = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
    private final JLabel stageValue = Ui.label(" "), sessionValue = Ui.label(" "), foundValue = Ui.label(" ");
    private final LatestModel latestModel = new LatestModel();
    private final javax.swing.tree.DefaultMutableTreeNode siteRoot = new javax.swing.tree.DefaultMutableTreeNode("sites");
    private final javax.swing.tree.DefaultTreeModel siteModel = new javax.swing.tree.DefaultTreeModel(siteRoot);
    private final JTree siteTree = new JTree(siteModel);
    private String sitesShown = "";
    private boolean hasActivity;     // the task on show is a scan with something to say
    private Boolean chosen;          // the face picked by hand: true the activity, false the browser; null, not picked
    private final PageView page = new PageView();
    private final JLabel pageTitle = Ui.bold(" ");
    private final StateChip chip = new StateChip();
    private final JTextField address = new JTextField();
    private final JLabel aside = Ui.label(" ");
    private final JPanel head = new JPanel();
    private boolean pageShown;
    private Object liveKey;          // the task whose browser is being shown live
    private long liveAt;             // when its last picture came
    private long textAt;             // when the words above the picture last changed
    private Object lastToken;        // the kept page on show, when not live

    public CrawlGraph() {
        setLayout(new BorderLayout());
        setOpaque(false);
        body.setOpaque(false);
        ButtonGroup pick = new ButtonGroup();
        pick.add(browserFace);
        pick.add(activityFace);
        browserFace.setToolTipText("The page currently or most recently open in the scan's browser");
        activityFace.setToolTipText("Scan activity: stage, session, discovered items and latest requests");
        browserFace.addActionListener(e -> { chosen = Boolean.FALSE; arrange(); });
        activityFace.addActionListener(e -> { chosen = Boolean.TRUE; arrange(); });
        faces.setOpaque(false);
        faces.setBorder(Ui.pad(8, PageView.PAD - 6, 0, PageView.PAD));
        faces.add(browserFace);
        faces.add(activityFace);
        faces.setVisible(false);
        add(faces, BorderLayout.NORTH);
        add(body, BorderLayout.CENTER);
        JPanel empty = new JPanel(new GridBagLayout());
        empty.setOpaque(false);
        JPanel col = new JPanel();
        col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
        col.setOpaque(false);
        JLabel icon = new JLabel(Glyphs.search(56, Theme.BORDER));
        JLabel h = Ui.heading("Not currently crawling");
        JLabel t = Ui.label("Display shows when live crawl is active.");
        t.setForeground(Theme.MUTED);
        for (JComponent c : new JComponent[]{icon, h, t}) { c.setAlignmentX(Component.CENTER_ALIGNMENT); col.add(c); col.add(Box.createVerticalStrut(8)); }
        empty.add(col, new GridBagConstraints());
        body.add(empty, "empty");

        // The activity: three lines of what the scan is doing, then the requests it sent last.
        JPanel facts = new JPanel(new GridBagLayout());
        facts.setOpaque(false);
        GridBagConstraints gc = new GridBagConstraints();
        gc.anchor = GridBagConstraints.WEST;
        gc.insets = new Insets(0, 0, Ui.em(6), Ui.em(18));
        Object[][] rows = {{"Stage", stageValue}, {"Session", sessionValue}, {"Found", foundValue}};
        for (int i = 0; i < rows.length; i++) {
            gc.gridy = i;
            gc.gridx = 0; gc.weightx = 0;
            JLabel k = Ui.label((String) rows[i][0]);
            k.setForeground(Theme.MUTED);
            facts.add(k, gc);
            gc.gridx = 1; gc.weightx = 1;
            facts.add((JLabel) rows[i][1], gc);
        }
        JTable latest = new JTable(latestModel);
        latest.setFont(Ui.PLAIN);
        latest.setFillsViewportHeight(true);
        latest.setRowSelectionAllowed(false);
        latest.setFocusable(false);
        latest.getTableHeader().setReorderingAllowed(false);
        int[] widths = {Ui.em(60), Ui.em(70), Ui.em(60), Ui.em(480), Ui.em(60), Ui.em(80)};
        latest.getTableHeader().setToolTipText("Session: whether the request carried the scan's session headers");
        for (int i = 0; i < widths.length; i++) latest.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        JPanel activityTop = new JPanel(new BorderLayout(0, Ui.em(8)));
        activityTop.setOpaque(false);
        activityTop.add(facts, BorderLayout.NORTH);
        JPanel activity = new JPanel(new BorderLayout(0, Ui.em(6)));
        activity.setOpaque(false);
        activity.setBorder(Ui.pad(12, PageView.PAD, 12, PageView.PAD));
        activity.add(activityTop, BorderLayout.NORTH);
        // On the left, each site of the scan with what the crawl has found at it so far.
        siteTree.setRootVisible(false);
        siteTree.setShowsRootHandles(true);
        siteTree.setFont(Ui.PLAIN);
        JPanel sitesSide = new JPanel(new BorderLayout(0, Ui.em(6)));
        sitesSide.setOpaque(false);
        sitesSide.add(Ui.bold("Sites"), BorderLayout.NORTH);
        sitesSide.add(Ui.scroll(siteTree), BorderLayout.CENTER);
        JPanel latestSide = new JPanel(new BorderLayout(0, Ui.em(6)));
        latestSide.setOpaque(false);
        latestSide.add(Ui.bold("Latest requests"), BorderLayout.NORTH);
        latestSide.add(Ui.scroll(latest), BorderLayout.CENTER);
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sitesSide, latestSide);
        split.setOpaque(false);
        split.setBorder(null);
        split.setResizeWeight(0.3);
        split.setDividerLocation(Ui.em(300));
        activity.add(split, BorderLayout.CENTER);
        body.add(activity, "activity");

        // The page view: two lines that never change height or place, then the picture.
        // The first line is the page's title, the second its state, its address and a short note.
        JPanel shown = new JPanel(new BorderLayout());
        shown.setOpaque(false);
        pageTitle.setMinimumSize(new Dimension(0, pageTitle.getPreferredSize().height));
        address.setEditable(false);
        address.setFont(Ui.PLAIN);
        address.setForeground(Theme.TEXT);
        address.setBackground(Theme.CONTENT);
        address.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Theme.BORDER), Ui.pad(3, 8, 3, 8)));
        aside.setForeground(Theme.MUTED);
        aside.setHorizontalAlignment(SwingConstants.RIGHT);
        FontMetrics fm = aside.getFontMetrics(aside.getFont());
        aside.setPreferredSize(new Dimension(Math.max(fm.stringWidth("Last seen 00:00:00"), fm.stringWidth("00 browsers open")) + 4,
                aside.getPreferredSize().height));
        // The title on the left with the state and its note on the right, then the address
        // the full width, then the picture: all three share the same left and right edges.
        JPanel state = new JPanel(new BorderLayout(10, 0));
        state.setOpaque(false);
        state.add(aside, BorderLayout.CENTER);
        state.add(chip, BorderLayout.EAST);
        JPanel top = new JPanel(new BorderLayout(12, 0));
        top.setOpaque(false);
        top.add(pageTitle, BorderLayout.CENTER);
        top.add(state, BorderLayout.EAST);
        head.setLayout(new BorderLayout(0, 6));
        head.setOpaque(false);
        head.setBorder(Ui.pad(10, PageView.PAD, 8, PageView.PAD));
        head.add(top, BorderLayout.NORTH);
        head.add(address, BorderLayout.CENTER);
        shown.add(head, BorderLayout.NORTH);
        // A page taller than the tab runs on below and is scrolled to.
        JScrollPane scroller = new JScrollPane(page, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroller.setBorder(BorderFactory.createEmptyBorder());
        scroller.setOpaque(false);
        scroller.getViewport().setOpaque(false);
        scroller.getVerticalScrollBar().setUnitIncrement(Ui.em(28));
        page.onWidth = w -> {
            // The header is kept exactly as wide as the picture under it.
            int right = Math.max(PageView.PAD, shown.getWidth() - PageView.PAD - w);
            java.awt.Insets now = head.getInsets();
            if (now.right != right) { head.setBorder(Ui.pad(10, PageView.PAD, 8, right)); head.revalidate(); }
        };
        shown.add(scroller, BorderLayout.CENTER);
        body.add(shown, "page");
        arrange();
    }

    /** Put the right face on show: the one picked by hand, or the browser when it has a page and the activity when it has not. */
    private void arrange() {
        boolean activity = hasActivity && (chosen != null ? chosen : !pageShown);
        faces.setVisible(hasActivity);
        (activity ? activityFace : browserFace).setSelected(true);
        cards.show(body, activity ? "activity" : pageShown ? "page" : "empty");
    }

    /**
     * How long a page stays on show before the view moves to the next one. A
     * crawl opens pages faster than they can be read, so the view shows fewer
     * of them, each for long enough; the picture and the words above it always
     * belong to the same page. While the browser stays on one page, the
     * picture keeps up with it.
     */
    static final long HOLD_MS = 1500;
    private String shownUrl;

    /**
     * Show the page a scan's browser has open now, as that browser drew it.
     * {@code fitted} is the picture already brought to the size on show, when
     * the caller did that off the window's thread; it may be null.
     */
    public void setPage(Object key, java.awt.image.BufferedImage image, java.awt.image.BufferedImage fitted, int cssWidth,
                        String url, String title, int pages) {
        long now = System.currentTimeMillis();
        boolean fresh = !pageShown || liveKey != key || lastToken != null;
        liveKey = key;
        liveAt = now;
        if (!fresh && !held(shownUrl, url, textAt, now)) return;   // the page on show has not had its time yet
        lastToken = null;
        if (fresh || !java.util.Objects.equals(url, shownUrl)) { shownUrl = url; textAt = now; }
        page.set(image, fitted, cssWidth);
        words(title, url, StateChip.LIVE, "Live", pages == 1 ? "1 browser open" : pages + " browsers open");
        if (!pageShown) { pageShown = true; arrange(); }
    }

    /** Whether a picture of {@code next} may be shown now: it is the page on show, or that page has had its time. */
    static boolean held(String shown, String next, long shownAt, long now) {
        return java.util.Objects.equals(shown, next) || now - shownAt >= HOLD_MS;
    }

    /**
     * How long after its last live picture a browser is still taken to be at
     * work. A crawl closes one browser and opens the next with a pause
     * between; without this the view would turn to the activity and back at
     * every such pause.
     */
    static final int GRACE_MS = 5000;
    private final javax.swing.Timer settle = new javax.swing.Timer(GRACE_MS, e -> notLive(liveKey));
    { settle.setRepeats(false); }

    /**
     * The browser is at work, on a page that is not to be shown: one the scan
     * refused to request. What is on show stays, and stays live.
     */
    public void stillLive(Object key) {
        if (key == liveKey) liveAt = System.currentTimeMillis();
    }

    /**
     * The scan on show has no browser open now: its browser stage is over,
     * has not begun, or the scan is paused or finished. The picture is taken
     * down and the view goes back to the activity, whichever face had been
     * picked while the browser was live.
     */
    public void notLive(Object key) {
        // A live picture came a moment ago: the browser may only be between two pages. Look again when its time is up.
        long since = System.currentTimeMillis() - liveAt;
        if (key == liveKey && since < GRACE_MS) {
            if (pageShown) { settle.setInitialDelay((int) (GRACE_MS - since) + 50); settle.restart(); }
            return;
        }
        settle.stop();
        liveKey = null;
        lastToken = null;
        if (!pageShown) return;
        pageShown = false;
        page.set(null, null, 0);
        chosen = null;
        arrange();
    }

    private void words(String title, String url, int kind, String state, String note) {
        String t = title == null || title.isBlank() ? "(untitled page)" : title.strip();
        if (!t.equals(pageTitle.getText())) pageTitle.setText(t);
        String u = url == null ? "" : url;
        if (!u.equals(address.getText())) { address.setText(u); address.setCaretPosition(0); }
        chip.set(kind, state);
        if (!note.equals(aside.getText())) aside.setText(note);
    }

    /** The picture at the size it would be shown at now. Safe to call from any thread. */
    public java.awt.image.BufferedImage prepare(java.awt.image.BufferedImage image, int cssWidth) {
        int w = page.roomW;
        if (image == null || w <= 0) return null;
        Dimension d = PageImage.fitSize(image.getWidth(), image.getHeight(), cssWidth, w, page.uiScale);
        return d.width <= 0 ? null : PageImage.scaled(image, d.width, d.height);
    }

    /** The state of the view in a word, with a dot in its colour. Always the same width, so nothing beside it moves. */
    private static final class StateChip extends JComponent {
        static final int LIVE = 0, PAUSED = 1, IDLE = 2;
        private static final String[] WORDS = {"Live", "Paused", "Finished", "Not crawling"};
        private int kind = IDLE;
        private String word = "";
        void set(int k, String w) { if (k != kind || !w.equals(word)) { kind = k; word = w; revalidate(); repaint(); } }
        @Override public Dimension getPreferredSize() {
            FontMetrics fm = getFontMetrics(Ui.PLAIN);
            return new Dimension(fm.stringWidth(word) + Ui.em(34), fm.getHeight() + Ui.em(8));
        }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setFont(Ui.PLAIN);
            FontMetrics fm = g2.getFontMetrics();
            int w = getWidth() - 1, h = getHeight() - 1;
            g2.setColor(Theme.SURFACE);
            g2.fillRoundRect(0, 0, w, h, h, h);
            double d = Ui.em(8);
            g2.setColor(kind == LIVE ? Theme.OK : kind == PAUSED ? new Color(0xD9, 0x8E, 0x04) : Theme.MUTED);
            g2.fill(new Ellipse2D.Double(Ui.em(10), (getHeight() - d) / 2.0, d, d));
            g2.setColor(Theme.TEXT);
            g2.drawString(word, Ui.em(10) + (int) Math.round(d) + Ui.em(6), (getHeight() - fm.getHeight()) / 2 + fm.getAscent());
            g2.dispose();
        }
    }

    /**
     * The picture of a page: the full width of the view, its left edge under
     * the header's, keeping its shape. It is drawn dot for dot on the screen,
     * so nothing softens it on the way.
     */
    private static final class PageView extends JComponent implements Scrollable {
        static final int PAD = 12;
        private java.awt.image.BufferedImage image, fitted;
        private int cssWidth;
        private int toldWidth = -1;
        volatile int roomW;                 // the width there is for the picture, in screen dots
        volatile double uiScale = 1;
        java.util.function.IntConsumer onWidth = w -> { };

        void set(java.awt.image.BufferedImage img, java.awt.image.BufferedImage ready, int css) {
            image = img; fitted = ready; cssWidth = css;
            revalidate();
            repaint();
        }

        /** The size the picture is shown at, in screen dots, for the width the view has now. */
        private Dimension shownSize() {
            java.awt.GraphicsConfiguration gc = getGraphicsConfiguration();
            double sx = gc == null ? 1 : Math.max(1, gc.getDefaultTransform().getScaleX());
            uiScale = sx;
            Container view = getParent();
            Container pane = view == null ? null : view.getParent();
            int across = pane != null ? pane.getWidth() : getWidth();
            // Room is always left for the scroll bar, shown or not, so the picture does not change size when it comes and goes.
            int bar = pane instanceof JScrollPane sp ? sp.getVerticalScrollBar().getPreferredSize().width : 0;
            roomW = (int) Math.floor((across - PAD - Math.max(PAD, bar)) * sx);
            if (image == null || roomW <= 0) return new Dimension(0, 0);
            return PageImage.fitSize(image.getWidth(), image.getHeight(), cssWidth, roomW, sx);
        }

        @Override public Dimension getPreferredSize() {
            Dimension d = shownSize();
            int w = (int) Math.ceil(d.width / uiScale);
            if (image != null && w != toldWidth) { toldWidth = w; SwingUtilities.invokeLater(() -> onWidth.accept(w)); }
            return new Dimension(w + 2 * PAD, (int) Math.ceil(d.height / uiScale) + 2 * PAD);
        }

        @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); }
        @Override public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) { return Ui.em(28); }
        @Override public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) { return Math.max(Ui.em(28), r.height - Ui.em(28)); }
        @Override public boolean getScrollableTracksViewportWidth() { return true; }
        @Override public boolean getScrollableTracksViewportHeight() { return false; }

        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            Dimension d = shownSize();
            if (image == null || d.width <= 0) { g2.dispose(); return; }
            if (fitted == null || fitted.getWidth() != d.width || fitted.getHeight() != d.height)
                fitted = PageImage.scaled(image, d.width, d.height);
            // Screen dots from here on: the picture is already the size it is shown at.
            java.awt.geom.AffineTransform at = g2.getTransform();
            double sx = at.getScaleX() <= 0 ? 1 : at.getScaleX();
            int x = (int) Math.round(at.getTranslateX() + PAD * sx);
            int y = (int) Math.round(at.getTranslateY() + 2 * sx);
            java.awt.Shape clip = g2.getClip();
            g2.setTransform(new java.awt.geom.AffineTransform());
            if (clip != null) g2.setClip(at.createTransformedShape(clip));
            g2.drawImage(fitted, x, y, null);
            g2.setColor(Theme.BORDER);
            g2.drawRect(x, y, d.width - 1, d.height - 1);
            g2.dispose();
        }
    }

    /** How many of a scan's requests the activity keeps to scroll back through. */
    public static final int HISTORY = 1000;

    /**
     * The scan's latest requests, newest at the top, each under its number in
     * the log as every other history shows it. The rows are read from the
     * entries as they are drawn, so only the ones in view cost anything.
     */
    static final class LatestModel extends javax.swing.table.AbstractTableModel {
        private static final String[] COLS = {"#", "Time", "Method", "Address", "Status", "Session"};
        private final java.text.SimpleDateFormat hms = new java.text.SimpleDateFormat("HH:mm:ss");
        private List<opensuite.core.LogEntry> rows = List.of();
        private java.util.Set<String> session = java.util.Set.of();

        /** Returns whether anything changed. */
        boolean set(List<opensuite.core.LogEntry> newestFirst, java.util.Set<String> sessionHeaders) {
            boolean same = newestFirst.size() == rows.size() && session.equals(sessionHeaders)
                    && (rows.isEmpty() || (rows.get(0) == newestFirst.get(0) && rows.get(rows.size() - 1) == newestFirst.get(newestFirst.size() - 1)));
            if (same) return false;
            rows = newestFirst;
            session = sessionHeaders;
            fireTableDataChanged();
            return true;
        }

        @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 boolean isCellEditable(int r, int c) { return false; }
        @Override public Object getValueAt(int r, int c) {
            if (r < 0 || r >= rows.size()) return "";
            opensuite.core.LogEntry e = rows.get(r);
            try {
                switch (c) {
                    case 0: return e.number();
                    case 1: return e.time() == null ? "" : hms.format(e.time());
                    case 2: return e.request().method();
                    case 3: return e.service().url() + e.request().requestTarget();
                    case 4: return e.response() == null ? "" : String.valueOf(e.response().statusCode());
                    default:
                        if (session.isEmpty()) return "";
                        for (String name : session) if (e.request().header(name) != null) return "Sent";
                        return "Not sent";
                }
            } catch (RuntimeException unreadable) {
                return "";
            }
        }
    }

    /**
     * Say what the scan on show is doing. {@code latest} is its last requests,
     * newest first; {@code sessionHeaders} the names of the headers that carry
     * its session, to say of each request whether it was sent with them.
     */
    public void setActivity(String stage, String session, String found, List<opensuite.core.LogEntry> latest,
                            java.util.Set<String> sessionHeaders) {
        if (!stage.equals(stageValue.getText())) stageValue.setText(stage);
        if (!session.equals(sessionValue.getText())) sessionValue.setText(session);
        if (!found.equals(foundValue.getText())) foundValue.setText(found);
        // The table is only told when its rows have changed, so it does not flicker.
        latestModel.set(latest, sessionHeaders);
        if (!hasActivity) { hasActivity = true; arrange(); }
    }

    /**
     * The tree of sites: one line for each site of the scan, saying how it
     * stands, with the paths found at it underneath. The map keeps the sites
     * in the order they are scanned.
     */
    public void setSites(java.util.Map<String, List<String>> sites) {
        String now = sites.toString();
        if (now.equals(sitesShown)) return;      // nothing new: the tree is left alone and keeps its place
        boolean first = sitesShown.isEmpty();
        sitesShown = now;
        java.util.Set<Integer> open = new java.util.HashSet<>();
        for (int i = 0; i < siteRoot.getChildCount(); i++)
            if (siteTree.isExpanded(new javax.swing.tree.TreePath(new Object[]{siteRoot, siteRoot.getChildAt(i)}))) open.add(i);
        siteRoot.removeAllChildren();
        for (java.util.Map.Entry<String, List<String>> e : sites.entrySet()) {
            javax.swing.tree.DefaultMutableTreeNode site = new javax.swing.tree.DefaultMutableTreeNode(e.getKey());
            for (String path : e.getValue()) site.add(new javax.swing.tree.DefaultMutableTreeNode(path));
            siteRoot.add(site);
        }
        siteModel.reload();
        for (int i = 0; i < siteRoot.getChildCount(); i++)
            if (open.contains(i) || (first && sites.size() == 1))
                siteTree.expandPath(new javax.swing.tree.TreePath(new Object[]{siteRoot, siteRoot.getChildAt(i)}));
    }

    /** The task on show is not a scan: there is nothing to say and no browser to show. */
    public void clear() {
        if (hasActivity) { hasActivity = false; arrange(); }
    }
}