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.

15.8 KB
Raw Blame
package opensuite.proxy;

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

import javax.swing.*;
import java.awt.Color;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * Right-click actions for a history table, in the reference order: scope,
 * scanning, send-to for each tool, record an issue, open in browser,
 * engagement tools, notes and highlight, delete and clear, copy, save, site
 * map, documentation.
 */
public class HistoryContextMenu {

    private final SuiteContext ctx;
    private final JTable table;
    private final HistoryModel model;                               // null: a non-history table, driven by the resolver below
    private final java.util.function.IntFunction<LogEntry> resolver;
    private final java.util.function.Consumer<LogEntry> remover;    // null: no delete action

    public HistoryContextMenu(SuiteContext ctx, JTable table, HistoryModel model) {
        this.ctx = ctx;
        this.table = table;
        this.model = model;
        this.resolver = model::at;
        this.remover = model::remove;
    }

    /**
     * For any table of entries that is not the proxy history model: a
     * row-to-entry resolver and a remover (or null for no delete). The actions
     * that only make sense against the whole history model (clear, new history
     * window) are left off in this mode.
     */
    public HistoryContextMenu(SuiteContext ctx, JTable table,
                              java.util.function.IntFunction<LogEntry> resolver,
                              java.util.function.Consumer<LogEntry> remover) {
        this.ctx = ctx;
        this.table = table;
        this.model = null;
        this.resolver = resolver;
        this.remover = remover;
    }

    /** Repaint after a per-entry change, through the model when there is one. */
    private void refresh() {
        if (model != null) model.fireTableDataChanged(); else table.repaint();
    }

    public void install() {
        // Hotkeys reach this menu's items through the table.
        table.putClientProperty(opensuite.ui.Hotkeys.MENU, (java.util.function.Supplier<JPopupMenu>) this::build);
        table.addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(MouseEvent e)  { maybe(e); }
            @Override public void mouseReleased(MouseEvent e) { maybe(e); }
            private void maybe(MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                int row = table.rowAtPoint(e.getPoint());
                if (row >= 0 && !table.isRowSelected(row)) table.setRowSelectionInterval(row, row);
                build().show(table, e.getX(), e.getY());
            }
        });
    }

    private List<LogEntry> selected() {
        List<LogEntry> out = new ArrayList<>();
        for (int r : table.getSelectedRows()) {
            LogEntry e = resolver.apply(table.convertRowIndexToModel(r));
            if (e != null) out.add(e);
        }
        return out;
    }

    private JPopupMenu build() {
        JPopupMenu menu = new JPopupMenu();
        List<LogEntry> sel = selected();
        if (sel.isEmpty()) return menu;
        LogEntry first = sel.get(0);
        boolean single = sel.size() == 1;
        String path = first.request() == null ? "/" : first.request().path();

        // The heading is the item's URL in bold black, on the rows' text edge; it is not a row and does not light up.
        JLabel title = new JLabel(Ui.truncate(first.url(), 60));
        title.setFont(Ui.BOLD);
        title.setForeground(Theme.TEXT);
        title.setBorder(Ui.pad(3, 29, 3, 10));
        menu.add(title);
        menu.addSeparator();

        // Scope.
        boolean inScope = single && ctx.scope().isInScope(first);
        if (inScope) {
            addK(menu, "Remove from scope", null, () -> {
                ctx.scope().removeUrl(first.service(), path, false);
                ctx.scopeChanged();
            });
        } else {
            addK(menu, single ? "Add to scope" : "Add selection to scope", null, () -> {
                for (LogEntry e : sel) ctx.scope().includeUrl(e.service(), e.request() == null ? "/" : e.request().path(), false);
                ctx.scopeChanged();
            });
        }

        menu.addSeparator();
        // Scanning: the live passive audit covers passive; an active scan of the item goes to the dashboard.
        addK(menu, "Scan", null, () -> scan(sel, true));
        addK(menu, "Passive scan selected message", null, () -> scan(sel, false));
        addK(menu, "Active scan selected message", null, () -> scan(sel, true));

        menu.addSeparator();
        // Send to each tool in the reference's order and then the browser rows; the tools only Open Suite sends to follow.
        List<String> order = List.of("intruder", "repeater", "sequencer", "organizer", "comparer");
        List<String> sinks = ctx.sinkNames();
        List<String> ordered = new ArrayList<>();
        for (String t : order) if (sinks.contains(t)) ordered.add(t);
        int referenceSends = ordered.size();
        for (String t : sinks) if (!ordered.contains(t) && !isEngagement(t)) ordered.add(t);
        for (int n = 0; n < ordered.size(); n++) {
            String tool = ordered.get(n);
            if (n == referenceSends) browserRows(menu, first);
            String label = "Send to " + capitalise(tool);
            String hk = switch (tool) { case "intruder" -> "Ctrl+I"; case "repeater" -> "Ctrl+R"; case "organizer" -> "Ctrl+O"; default -> null; };
            if (ctx.sinkTakesSingleItem(tool)) {
                if (first.request() != null) addK(menu, label + " (request)", hk, () -> ctx.sendTo(tool, first.service(), first.request().copy(), null, null));
                if (first.response() != null) addK(menu, label + " (response)", null, () -> ctx.sendTo(tool, first.service(), null, first.response().copy(), null));
            } else {
                addK(menu, label, hk, () -> { for (LogEntry e : sel) ctx.sendTo(tool, e.service(),
                        e.request() == null ? null : e.request().copy(), e.response() == null ? null : e.response().copy(), null); });
            }
        }

        if (ordered.size() == referenceSends) browserRows(menu, first);
        menu.addSeparator();

        // Engagement tools.
        JMenu eng = sub("Engagement tools");
        for (String t : sinks) if (isEngagement(t)) {
            String label = opensuite.ui.Engagement.label(t);
            addK(eng, label, null, () -> ctx.sendTo(t, first.service(), first.request() == null ? null : first.request().copy(),
                    first.response() == null ? null : first.response().copy(), null));
        }
        addK(eng, "Schedule task", null, () -> JOptionPane.showMessageDialog(table, "Scheduled tasks are configured under Settings > Tasks > Schedule tasks.", "Schedule task", JOptionPane.INFORMATION_MESSAGE));
        menu.add(eng);
        JMenu record = sub("Record an issue");
        addK(record, "Create a new issue", null, () -> newIssue(first));
        addK(record, "Add to existing issue", null, () -> addToIssue(first));
        menu.add(record);
        menu.addSeparator();
        if (model != null) {
            addK(menu, "Show new history window", null, () -> newHistoryWindow());
            menu.addSeparator();
        }

        // Annotate.
        addK(menu, "Add notes", null, () -> {
            String v = JOptionPane.showInputDialog(table, "Notes:", first.notes());
            if (v != null) { first.setNotes(v); refresh(); }
        });
        JMenu highlight = sub("Highlight");
        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(first.service().host());
            mi.setFont(Ui.PLAIN);
            if (!c[0].isEmpty()) { mi.setOpaque(true); mi.setBackground(Color.decode(c[0])); }
            else mi.setBorder(BorderFactory.createDashedBorder(Theme.BORDER));
            mi.addActionListener(e -> { for (LogEntry en : sel) en.setHighlight(c[1].equals("none") ? "" : c[1]); refresh(); });
            highlight.add(mi);
        }
        menu.add(highlight);

        // Delete / clear.
        if (remover != null) {
            addK(menu, single ? "Delete item" : "Delete selected items", null, () -> { for (LogEntry e : sel) remover.accept(e); });
        }
        if (model != null) {
            addK(menu, "Clear history", null, () -> {
                if (JOptionPane.showConfirmDialog(table, "Clear the entire history?", "Clear history", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) model.clear();
            });
        }

        // Copy / save.
        addK(menu, single ? "Copy URL" : "Copy selected URLs", null, () -> {
            StringBuilder sb = new StringBuilder();
            for (LogEntry e : sel) sb.append(e.url()).append('\n');
            clip(sb.toString().trim());
        });
        addK(menu, "Copy as curl command (bash)", null, () -> clip(curl(first)));
        if (first.response() != null) addK(menu, "Copy links in response", null, () -> clip(links(first)));
        addK(menu, "Save item", null, () -> saveItem(first));
        addK(menu, "Add to site map", null, () -> { for (LogEntry e : sel) ctx.siteMapChanged(e); });
        menu.addSeparator();
        addK(menu, "Proxy history documentation", null, () -> opensuite.ui.Unbuilt.openProject(table));
        return menu;
    }

    // ---- actions ----

    /** Hand the chosen requests to the scanner: an audit of each, or a passive read of each. */
    private void scan(List<LogEntry> sel, boolean active) {
        if (!ctx.hasSink("scanner")) {
            ctx.alert("proxy", "The scanner is not available in this window");
            return;
        }
        for (LogEntry e : sel) {
            if (e.request() == null) continue;
            ctx.sendTo("scanner", e.service(), e.request().copy(),
                    e.response() == null ? null : e.response().copy(), active ? "active" : "passive");
        }
    }

    private void newIssue(LogEntry e) {
        JTextField title = Ui.field("");
        JComboBox<Issue.Severity> sev = Ui.combo(Issue.Severity.values());
        JComboBox<Issue.Confidence> conf = Ui.combo(Issue.Confidence.values());
        JTextArea detail = new JTextArea(5, 30);
        detail.setFont(Ui.PLAIN);
        JPanel form = Ui.vbox(Ui.form("Issue name:", title, "Severity:", sev, "Confidence:", conf), Ui.label("Detail:"), Ui.scroll(detail));
        form.setBorder(Ui.pad(10, 10, 10, 10));
        if (JOptionPane.showConfirmDialog(table, form, "Create a new issue", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return;
        if (title.getText().isBlank()) return;
        Issue i = new Issue(title.getText().strip(), (Issue.Severity) sev.getSelectedItem(), (Issue.Confidence) conf.getSelectedItem(),
                e.service(), e.request() == null ? "/" : e.request().path(), "", detail.getText(), "", "", e.request(), e.response());
        ctx.addIssue(i);
    }

    private void addToIssue(LogEntry e) {
        List<Issue> issues = ctx.issues();
        if (issues.isEmpty()) { JOptionPane.showMessageDialog(table, "No issues exist. Create a new issue instead.", "Add to existing issue", JOptionPane.INFORMATION_MESSAGE); return; }
        Object pick = JOptionPane.showInputDialog(table, "Issue:", "Add to existing issue", JOptionPane.PLAIN_MESSAGE, null,
                issues.stream().map(Issue::title).toArray(), issues.get(0).title());
        if (pick != null) ctx.alert("proxy", "Added " + e.url() + " as evidence to \"" + pick + "\"");
    }

    private void openInBrowser(LogEntry e) {
        try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(e.url())); }
        catch (Exception ex) { clip(e.url()); JOptionPane.showMessageDialog(table, "Could not open a browser. The URL has been copied to the clipboard.", "Open in browser", JOptionPane.INFORMATION_MESSAGE); }
    }

    private void newHistoryWindow() {
        JFrame f = new JFrame("Proxy history");
        JTable t = new JTable(model);
        Ui.styleTable(t);
        f.setContentPane(Ui.scroll(t));
        f.setSize(1000, 600);
        f.setLocationRelativeTo(table);
        f.setVisible(true);
    }

    private static String curl(LogEntry e) {
        HttpMessage r = e.request();
        if (r == null) return "";
        StringBuilder sb = new StringBuilder("curl -i -s -k -X $'").append(r.method()).append("' ");
        for (String h : r.headerLines()) sb.append("-H $'").append(h.replace("'", "\\'")).append("' ");
        if (r.body().length > 0) sb.append("--data-binary $'").append(new String(r.body(), java.nio.charset.StandardCharsets.ISO_8859_1).replace("'", "\\'")).append("' ");
        sb.append("$'").append(e.url()).append("'");
        return sb.toString();
    }

    private static String links(LogEntry e) {
        String body = new String(e.response().body(), java.nio.charset.StandardCharsets.ISO_8859_1);
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("(?i)(?:href|src|action)\\s*=\\s*[\"']([^\"'#]+)").matcher(body);
        java.util.Set<String> out = new java.util.LinkedHashSet<>();
        while (m.find()) out.add(m.group(1));
        return String.join("\n", out);
    }

    private void saveItem(LogEntry e) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setSelectedFile(new java.io.File("item-" + e.number() + ".txt"));
        if (fc.showSaveDialog(table) != JFileChooser.APPROVE_OPTION) return;
        try (java.io.FileOutputStream out = new java.io.FileOutputStream(fc.getSelectedFile())) {
            if (e.request() != null) out.write(e.request().raw());
            out.write("\n\n".getBytes());
            if (e.response() != null) out.write(e.response().raw());
        } catch (java.io.IOException ex) { JOptionPane.showMessageDialog(table, "Could not save: " + ex.getMessage()); }
    }

    // ---- helpers ----

    private static boolean isEngagement(String t) { return opensuite.ui.Engagement.isEngagement(t); }
    private static String capitalise(String s) { return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1); }
    /** "Open response in browser" and "Request in browser". */
    private void browserRows(JPopupMenu menu, LogEntry first) {
        if (first.response() != null) addK(menu, "Open response in browser", null,
                () -> opensuite.ui.MessageActions.openResponseInBrowser(
                        table, ctx, first.service(), first.request(), first.response()));
        JMenu inBrowser = sub("Request in browser");
        addK(inBrowser, "In original session", null, () -> openInBrowser(first));
        addK(inBrowser, "In current browser session", null, () -> openInBrowser(first));
        menu.add(inBrowser);
    }

    private static void clip(String s) { java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(s), null); }

    private static JMenu sub(String text) {
        JMenu m = new JMenu(text);
        m.setFont(Ui.PLAIN);
        return m;
    }

    private void addK(JComponent menu, String label, String hotkey, Runnable action) {
        JMenuItem mi = new JMenuItem(label);
        mi.setFont(Ui.PLAIN);
        // The key shown is the one the action is bound to now, which Settings > Hotkeys can change.
        String bound = opensuite.ui.Hotkeys.bindingOf(ctx.settings(), label);
        KeyStroke stroke = opensuite.ui.Hotkeys.keyStroke(bound.isEmpty() && hotkey != null
                && opensuite.ui.Hotkeys.bound(ctx.settings(), hotkey) == null ? hotkey : bound);
        if (stroke != null) mi.setAccelerator(stroke);
        mi.addActionListener(e -> action.run());
        menu.add(mi);
    }
}