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.

18.2 KB
Raw Blame
package opensuite.target;

import opensuite.core.LogEntry;
import opensuite.core.SuiteContext;
import opensuite.ui.MessageEditor;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.io.Closeable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Compare site maps: four short pages choose the two maps, how requests are
 * paired and what of the responses is compared; the result lists the two maps
 * side by side with what was modified, deleted and added marked in colour.
 */
final class CompareSiteMaps {
    private CompareSiteMaps() {}

    static final Color MODIFIED = new Color(0xF6, 0xC9, 0x8A), DELETED = new Color(0xA9, 0xC8, 0xF0), ADDED = new Color(0xF3, 0xE7, 0x8C);

    static void open(SuiteContext ctx, SiteMap current) { new Wizard(ctx, current).setVisible(true); }

    /** Every requested item in a site map. */
    static List<LogEntry> itemsOf(SiteMap map) {
        List<LogEntry> out = new ArrayList<>();
        for (SiteMap.Node host : map.root().children.values()) {
            for (LogEntry e : host.entries()) if (!map.isLinked(e)) out.add(e);
        }
        return out;
    }

    static final int AGAIN_CAP = 1000;

    /** A request as it would be sent by someone who is not signed in: its cookies and credentials taken off. */
    static opensuite.core.HttpMessage withoutSession(opensuite.core.HttpMessage req) {
        opensuite.core.HttpMessage m = req.copy();
        m.removeHeader("Cookie");
        m.removeHeader("Authorization");
        return m;
    }

    /** Send each request of a map again without its session; the answers make the second map. */
    static List<LogEntry> requestAgain(List<LogEntry> items) {
        List<LogEntry> out = new ArrayList<>();
        opensuite.core.HttpClient client = new opensuite.core.HttpClient();
        int n = 0;
        for (LogEntry e : items) {
            // Only what was really requested before: an item that was only seen is not contacted now.
            if (e.request() == null || e.service() == null || e.response() == null || n++ >= AGAIN_CAP) continue;
            opensuite.core.HttpMessage req = withoutSession(e.request());
            LogEntry made = new LogEntry("compare", e.service(), req);
            try {
                opensuite.core.HttpClient.Result r = client.send(e.service(), req, new opensuite.core.HttpClient.Options());
                if (r != null && r.response != null) made.setResponse(r.response);
            } catch (RuntimeException ignored) { /* no answer: the item shows without a response */ }
            out.add(made);
        }
        return out;
    }

    /** One page's choice of map: the one on screen, or the one in a project file. */
    private static final class Source {
        final JRadioButton current = Ui.radio("Use current site map", true);
        final JRadioButton fromFile = Ui.radio("Load from an Open Suite project file", false);
        /** Only offered for the second map: the first map's requests sent again without the session they were made in. */
        final JRadioButton again = Ui.radio("Request map 1 again without its session (no cookies, no Authorization header)", false);
        boolean second;
        final JTextField file = Ui.field("");
        final JCheckBox inScope = Ui.check("Include in-scope items only", false);

        JComponent panel(Component parent) {
            ButtonGroup g = new ButtonGroup(); g.add(current); g.add(fromFile); g.add(again);
            JButton choose = Ui.button("Choose file...");
            choose.addActionListener(e -> {
                JFileChooser fc = new opensuite.ui.FileChooser();
                if (fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
                    file.setText(fc.getSelectedFile().getAbsolutePath());
                    fromFile.setSelected(true);
                }
            });
            JPanel row = new JPanel(new BorderLayout(8, 0));
            row.setOpaque(false);
            row.setBorder(Ui.pad(0, 24, 0, 0));
            row.add(file, BorderLayout.CENTER);
            row.add(choose, BorderLayout.EAST);
            if (second) return stack(current, fromFile, row, again, Box.createVerticalStrut(10), inScope);
            return stack(current, fromFile, row, Box.createVerticalStrut(10), inScope);
        }

        List<LogEntry> load(SuiteContext ctx, SiteMap map, List<Closeable> keep) throws Exception {
            List<LogEntry> all;
            if (current.isSelected()) all = itemsOf(map);
            else {
                String path = file.getText().trim();
                if (path.isEmpty()) throw new IllegalStateException("Choose a project file.");
                all = opensuite.ui.StateIO.readHistory(new File(path), keep::add);
            }
            if (!inScope.isSelected()) return all;
            List<LogEntry> in = new ArrayList<>();
            for (LogEntry e : all) if (e.service() != null && ctx.scope().isInScope(e.service(), e.requestPath())) in.add(e);
            return in;
        }
    }

    private static JPanel stack(Component... parts) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.setOpaque(false);
        for (Component c : parts) {
            if (c instanceof JComponent j) { j.setAlignmentX(Component.LEFT_ALIGNMENT); j.setOpaque(false); }
            if (c instanceof JPanel j) j.setMaximumSize(new Dimension(Integer.MAX_VALUE, j.getPreferredSize().height));
            p.add(c);
            p.add(Box.createVerticalStrut(6));
        }
        return p;
    }

    private static JComponent page(String title, String text, JComponent body) {
        JPanel p = new JPanel(new BorderLayout(0, 14));
        p.setBackground(Theme.BG);
        p.setBorder(Ui.pad(18, 22, 10, 22));
        JPanel head = new JPanel(new BorderLayout(0, 6));
        head.setOpaque(false);
        head.add(Ui.heading(title), BorderLayout.NORTH);
        JTextArea note = Ui.note(text);
        note.setOpaque(false);
        head.add(note, BorderLayout.CENTER);
        p.add(head, BorderLayout.NORTH);
        p.add(body, BorderLayout.CENTER);
        return p;
    }

    private static final class Wizard extends JDialog {
        private final CardLayout cards = new CardLayout();
        private final JPanel content = new JPanel(cards);
        private final JButton back = Ui.button("Back"), next = Ui.primaryButton("Next", null);
        private int step;
        private static final int PAGES = 4;

        Wizard(SuiteContext ctx, SiteMap map) {
            super(ctx.frame(), "Compare site maps", true);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            Source one = new Source(), two = new Source();
            two.second = true;
            JCheckBox method = Ui.check("HTTP method", true), query = Ui.check("Query string", true), host = Ui.check("Host", true);
            JCheckBox status = Ui.check("Status code", true), headers = Ui.check("Response headers", false),
                    body = Ui.check("Response body", true), space = Ui.check("Ignore differences in white space", true);
            JCheckBox path = Ui.check("URL file path", true);
            path.setEnabled(false);

            content.add(page("Site map 1", "Choose the first site map. This is the one the second is measured against.", one.panel(this)), "0");
            content.add(page("Site map 2", "Choose the second site map: the same application as another user, say, "
                    + "or at another time, saved in another project file.", two.panel(this)), "1");
            content.add(page("Request matching", "Choose what makes a request in one map the same request as one in the other.",
                    stack(path, method, query, host)), "2");
            content.add(page("Response comparison", "Choose what is compared in the responses of requests that match.",
                    stack(status, headers, body, Box.createVerticalStrut(10), space)), "3");

            JButton cancel = Ui.button("Cancel");
            cancel.addActionListener(e -> dispose());
            back.addActionListener(e -> go(step - 1));
            next.addActionListener(e -> {
                if (step < PAGES - 1) { go(step + 1); return; }
                SiteMapDiff.Options o = new SiteMapDiff.Options();
                o.matchMethod = method.isSelected(); o.matchQuery = query.isSelected(); o.matchHost = host.isSelected();
                o.compareStatus = status.isSelected(); o.compareHeaders = headers.isSelected();
                o.compareBody = body.isSelected(); o.ignoreWhitespace = space.isSelected();
                List<Closeable> keep = new ArrayList<>();
                try {
                    List<LogEntry> a = one.load(ctx, map, keep);
                    if (two.again.isSelected()) {
                        // Sent in the background: the result opens when the last answer is in.
                        next.setEnabled(false); back.setEnabled(false);
                        next.setText("Requesting...");
                        new SwingWorker<List<LogEntry>, Void>() {
                            @Override protected List<LogEntry> doInBackground() { return requestAgain(a); }
                            @Override protected void done() {
                                try {
                                    List<LogEntry> b = get();
                                    dispose();
                                    new Result(ctx, SiteMapDiff.compare(a, b, o), keep).setVisible(true);
                                } catch (Exception ex) {
                                    for (Closeable c : keep) try { c.close(); } catch (Exception ignore) { }
                                    dispose();
                                }
                            }
                        }.execute();
                        return;
                    }
                    List<LogEntry> b = two.load(ctx, map, keep);
                    dispose();
                    new Result(ctx, SiteMapDiff.compare(a, b, o), keep).setVisible(true);
                } catch (Exception ex) {
                    for (Closeable c : keep) try { c.close(); } catch (Exception ignore) { }
                    JOptionPane.showMessageDialog(this, ex.getMessage() == null ? "The site map could not be loaded." : ex.getMessage(),
                            "Compare site maps", JOptionPane.WARNING_MESSAGE);
                }
            });
            Ui.sameSize(cancel, back, next);
            JPanel bar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 10));
            bar.setBackground(Theme.BG);
            bar.setBorder(Ui.pad(0, 0, 0, 14));
            bar.add(cancel); bar.add(back); bar.add(next);
            setLayout(new BorderLayout());
            add(content, BorderLayout.CENTER);
            add(bar, BorderLayout.SOUTH);
            go(0);
            setSize(640, 400);
            setLocationRelativeTo(ctx.frame());
        }

        private void go(int i) {
            step = Math.max(0, Math.min(PAGES - 1, i));
            cards.show(content, String.valueOf(step));
            back.setEnabled(step > 0);
            next.setText(step == PAGES - 1 ? "Compare" : "Next");
        }
    }

    /** One map's side of the result: its items, coloured by what became of them. */
    private static final class Side extends AbstractTableModel {
        final List<SiteMapDiff.Row> rows = new ArrayList<>();
        final boolean first;
        private final String[] cols = {"Host", "Method", "URL", "Status code", "Length"};
        Side(List<SiteMapDiff.Row> all, boolean first) {
            this.first = first;
            for (SiteMapDiff.Row r : all) if (item(r) != null) rows.add(r);
        }
        LogEntry item(SiteMapDiff.Row r) { return first ? r.one() : r.two(); }
        @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 Object getValueAt(int r, int c) {
            LogEntry e = item(rows.get(r));
            return switch (c) {
                case 0 -> e.service() == null ? "" : e.service().url();
                case 1 -> e.request() == null ? "" : e.request().method();
                case 2 -> e.pathAndQuery();
                case 3 -> e.status() == 0 ? "" : String.valueOf(e.status());
                default -> e.responseLen() == 0 ? "" : String.valueOf(e.responseLen());
            };
        }
    }

    static Color tint(SiteMapDiff.State s) {
        return switch (s) { case MODIFIED -> MODIFIED; case DELETED -> DELETED; case ADDED -> ADDED; default -> null; };
    }

    private static final class Result extends JFrame {
        private boolean syncing, apart;

        Result(SuiteContext ctx, List<SiteMapDiff.Row> rows, List<Closeable> keep) {
            super("Site map comparison");
            setIconImages(opensuite.ui.AppIcon.images());
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            addWindowListener(new java.awt.event.WindowAdapter() {
                @Override public void windowClosed(java.awt.event.WindowEvent e) {
                    for (Closeable c : keep) try { c.close(); } catch (Exception ignore) { }
                }
            });
            Side a = new Side(rows, true), b = new Side(rows, false);
            JTable ta = table(a), tb = table(b);
            MessageEditor ra = new MessageEditor(ctx, MessageEditor.RESPONSE, false), rb = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
            MessageEditor qa = new MessageEditor(ctx, MessageEditor.REQUEST, false), qb = new MessageEditor(ctx, MessageEditor.REQUEST, false);
            link(ta, a, tb, b, qa, ra);
            link(tb, b, ta, a, qb, rb);

            int[] n = SiteMapDiff.counts(rows);
            JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                    side("Site map 1", a.rows.size() + " items", ta, qa, ra), side("Site map 2", b.rows.size() + " items", tb, qb, rb));
            split.setResizeWeight(0.5);
            split.setBorder(null);

            JPanel key = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 8));
            key.setBackground(Theme.BG);
            key.add(Ui.label("Key:"));
            key.add(chip("Modified: " + n[SiteMapDiff.State.MODIFIED.ordinal()], MODIFIED));
            key.add(chip("Deleted: " + n[SiteMapDiff.State.DELETED.ordinal()], DELETED));
            key.add(chip("Added: " + n[SiteMapDiff.State.ADDED.ordinal()], ADDED));
            key.add(Ui.label("Unchanged: " + n[SiteMapDiff.State.SAME.ordinal()]));
            JCheckBox sync = Ui.check("Sync selection", true);
            sync.setOpaque(false);
            sync.addActionListener(e -> apart = !sync.isSelected());
            key.add(sync);

            setLayout(new BorderLayout());
            add(split, BorderLayout.CENTER);
            add(key, BorderLayout.SOUTH);
            setSize(1300, 780);
            setLocationRelativeTo(ctx.frame());
        }

        private static JLabel chip(String text, Color c) {
            JLabel l = Ui.label(text);
            l.setOpaque(true);
            l.setBackground(c);
            l.setForeground(Color.BLACK);
            l.setBorder(Ui.pad(2, 8, 2, 8));
            return l;
        }

        private static JTable table(Side model) {
            JTable t = new JTable(model);
            Ui.styleTable(t);
            t.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
            t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            t.getColumnModel().getColumn(2).setPreferredWidth(320);
            DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable tb, Object v, boolean sel, boolean focus, int row, int col) {
                    super.getTableCellRendererComponent(tb, v, sel, false, row, col);
                    Color c = tint(model.rows.get(row).state());
                    if (!sel) { setBackground(c == null ? tb.getBackground() : c); setForeground(c == null ? Theme.TEXT : Color.BLACK); }
                    setBorder(Ui.pad(0, 6, 0, 4));
                    return this;
                }
            };
            for (int i = 0; i < t.getColumnCount(); i++) t.getColumnModel().getColumn(i).setCellRenderer(r);
            return t;
        }

        /** Choosing an item shows it below and, unless told not to, chooses its partner on the other side. */
        private void link(JTable mine, Side my, JTable theirs, Side their, MessageEditor req, MessageEditor resp) {
            mine.getSelectionModel().addListSelectionListener(ev -> {
                if (ev.getValueIsAdjusting()) return;
                int row = mine.getSelectedRow();
                if (row < 0) return;
                SiteMapDiff.Row r = my.rows.get(row);
                LogEntry e = my.item(r);
                req.showRequest(e);
                resp.showResponse(e);
                if (syncing || apart) return;
                syncing = true;
                try {
                    int other = their.rows.indexOf(r);
                    if (other >= 0) {
                        theirs.setRowSelectionInterval(other, other);
                        theirs.scrollRectToVisible(theirs.getCellRect(other, 0, true));
                    } else theirs.clearSelection();
                } finally { syncing = false; }
            });
        }

        private static JComponent side(String title, String count, JTable t, MessageEditor req, MessageEditor resp) {
            JPanel head = new JPanel(new BorderLayout());
            head.setBackground(Theme.BG);
            head.setBorder(Ui.pad(8, 10, 6, 10));
            head.add(Ui.heading(title), BorderLayout.WEST);
            head.add(Ui.label(count), BorderLayout.EAST);
            JTabbedPane tabs = new JTabbedPane();
            tabs.setFont(Ui.PLAIN);
            tabs.addTab("Request", req);
            tabs.addTab("Response", resp);
            tabs.setSelectedIndex(1);
            JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, Ui.scroll(t), tabs);
            sp.setResizeWeight(0.45);
            sp.setBorder(null);
            JPanel p = new JPanel(new BorderLayout());
            p.add(head, BorderLayout.NORTH);
            p.add(sp, BorderLayout.CENTER);
            return p;
        }
    }
}