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.

10.7 KB
Raw Blame
package opensuite.ui;

import javax.swing.*;
import java.awt.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import opensuite.core.Debug;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.SuiteContext;
import opensuite.script.RequestDiff;
import opensuite.script.RunResult;
import opensuite.script.Samples;

/**
 * The "Custom actions" side panel of a message editor: scripts that act on
 * the shown request or response. Empty until some exist, with Add samples,
 * Load and New; populated, a list of the actions with Run, and the output of
 * each run. Actions are scripts of the custom-action function in the script
 * library (Extensions > Script library), so one place manages them.
 *
 * <p>An action runs on copies of the request being edited and the response
 * beside it. A request it hands back replaces the edited one as a single
 * undoable change. An action never sends anything.
 */
public final class CustomActionsPanel extends JPanel {

    private static Path dir() { return Path.of(System.getProperty("user.home", "."), ".opensuite", "scripts", "custom-action"); }

    private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss");

    private final MessageEditor host;
    private final CardLayout cards = new CardLayout();
    private final DefaultListModel<String> model = new DefaultListModel<>();
    private final JList<String> list = new JList<>(model);
    private final JButton run = Ui.primaryButton("Run", "run the selected action on this message");
    private final JTextArea output = new JTextArea(8, 20);
    private String lastRun;
    private AtomicBoolean stop;   // the run under way, or null

    /** @param host the editor this panel belongs to; actions work on its request source */
    public CustomActionsPanel(MessageEditor host) {
        this.host = host;
        setLayout(cards);
        setOpaque(false);

        JPanel col = new JPanel();
        col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
        col.setOpaque(false);
        JLabel icon = new JLabel(Glyphs.bolt(64, new Color(0x5C, 0x9A, 0xCF)));
        JLabel h = new JLabel("No custom actions");
        h.setFont(new Font("Dialog", Font.BOLD, 16));
        JTextArea t = Ui.note("Try our sample scripts to see how they work. You can also load scripts from your library or create your own.");
        Ui.sizeNote(t, 240);
        JButton samples = Ui.primaryButton("Add samples", "Add sample custom actions to the library");
        samples.addActionListener(e -> { addSamples(); reload(); });
        JButton load = Ui.button("Load", "Select a script from the library");
        load.setIcon(Glyphs.arrow(14, Theme.ICON, 1));
        load.addActionListener(e -> load());
        JButton neu = Ui.button("New", "Create a custom action");
        neu.setIcon(Glyphs.plus(14, Theme.ICON));
        neu.addActionListener(e -> goToLibrary(null));
        JComponent learn = CustomScopePanel.link("Learn more", () -> Unbuilt.openProject(CustomActionsPanel.this));
        for (JComponent c : new JComponent[]{icon, h, t, samples, Ui.row(load, neu), learn}) {
            c.setAlignmentX(Component.CENTER_ALIGNMENT);
            col.add(c);
            col.add(Box.createVerticalStrut(12));
        }
        JPanel empty = new JPanel(new GridBagLayout());
        empty.setOpaque(false);
        empty.add(col, new GridBagConstraints());
        add(empty, "empty");

        list.setFont(Ui.PLAIN);
        list.setFixedCellHeight(26);
        run.addActionListener(e -> { if (stop != null) stop.set(true); else runSelected(); });
        JButton edit = Ui.button("Edit");
        edit.addActionListener(e -> goToLibrary(list.getSelectedValue()));
        JButton more = Ui.button("Load");
        more.addActionListener(e -> load());

        output.setEditable(false);
        output.setFont(Ui.MONO);
        output.setLineWrap(true);
        JPanel links = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
        links.setOpaque(false);
        links.add(CustomScopePanel.link("edit script", () -> goToLibrary(lastRun)));
        links.add(CustomScopePanel.link("clear", () -> output.setText("")));
        JPanel outHead = new JPanel(new BorderLayout());
        outHead.setOpaque(false);
        outHead.add(Ui.bold("output"), BorderLayout.WEST);
        outHead.add(links, BorderLayout.EAST);
        JPanel out = new JPanel(new BorderLayout(0, 4));
        out.setOpaque(false);
        out.add(outHead, BorderLayout.NORTH);
        out.add(Ui.scroll(output), BorderLayout.CENTER);

        JPanel top = new JPanel(new BorderLayout(0, 6));
        top.setOpaque(false);
        top.add(Ui.scroll(list), BorderLayout.CENTER);
        top.add(Ui.row(run, edit, more), BorderLayout.SOUTH);
        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top, out);
        split.setBorder(null);
        split.setOpaque(false);
        split.setResizeWeight(0.5);

        JPanel full = new JPanel(new BorderLayout());
        full.setOpaque(false);
        full.setBorder(Ui.pad(8, 8, 8, 8));
        full.add(split, BorderLayout.CENTER);
        add(full, "list");
        reload();
    }

    /** The compiler loads in the background once the panel is first shown, so the first run is quick. */
    @Override public void addNotify() {
        super.addNotify();
        if (host.context() != null) host.context().scripts().warmUp();
    }

    private void runSelected() {
        if (list.getSelectedValue() == null && !model.isEmpty()) list.setSelectedIndex(0);
        String name = list.getSelectedValue();
        SuiteContext ctx = host.context();
        if (name == null || ctx == null) return;
        String source;
        try {
            source = Files.readString(dir().resolve(name + ".java"));
        } catch (java.io.IOException e) {
            append(name, List.of("  failed: the script could not be read: " + e.getMessage()));
            return;
        }
        MessageEditor src = host.requestSource();
        HttpService svc = src.service();
        HttpMessage request = src.message().copy();
        HttpMessage response = host != src && host.message().raw().length > 0 ? host.message().copy() : null;

        AtomicBoolean thisRun = new AtomicBoolean();
        stop = thisRun;
        lastRun = name;
        setRunning(true);
        Thread t = new Thread(() -> {
            RunResult r = ctx.scripts().runCustomAction(source, svc, request, response, CustomActionsPanel::toClipboard, thisRun);
            SwingUtilities.invokeLater(() -> finish(name, request, r));
        }, "opensuite-script-call");
        t.setDaemon(true);
        t.start();
    }

    private void finish(String action, HttpMessage before, RunResult r) {
        stop = null;
        setRunning(false);
        List<String> lines = new ArrayList<>();
        for (String l : r.log()) lines.add("  " + l);
        if (r.logCut()) lines.add("  [output cut at 1000 lines / 64 KB]");
        if (r.status() != RunResult.Status.OK) {
            String[] err = r.error().split("\n");
            lines.add("  failed: " + err[0]);
            for (int i = 1; i < err.length; i++) lines.add("          " + err[i]);
        } else {
            List<String> changes = r.newRequest() == null ? List.of() : RequestDiff.summarise(before, r.newRequest());
            if (!changes.isEmpty()) {
                host.requestSource().replaceMessageUndoably(r.newRequest());
                lines.add("  request changed:");
                for (String c : changes) lines.add("    " + c);
            }
            lines.add("  ok in " + r.millis() + " ms");
        }
        append(action, lines);
    }

    private void setRunning(boolean on) {
        run.setText(on ? "Stop" : "Run");
        run.setToolTipText(on ? "stop the action that is running" : "run the selected action on this message");
    }

    private void append(String action, List<String> lines) {
        StringBuilder sb = new StringBuilder();
        if (output.getDocument().getLength() > 0) sb.append('\n');
        sb.append(LocalTime.now().format(TIME)).append("  ").append(action).append('\n');
        for (String l : lines) sb.append(l).append('\n');
        output.append(sb.toString());
        output.setCaretPosition(output.getDocument().getLength());
    }

    private static void toClipboard(String text) {
        SwingUtilities.invokeLater(() -> {
            try {
                MessageActions.clip(text);
            } catch (RuntimeException e) {
                Debug.error("custom action: the clipboard could not be set", e);
            }
        });
    }

    private void reload() {
        String selected = list.getSelectedValue();
        model.clear();
        if (Files.isDirectory(dir())) {
            try (var ds = Files.newDirectoryStream(dir(), "*.java")) {
                for (Path p : ds) model.addElement(p.getFileName().toString().replaceAll("\\.java$", ""));
            } catch (java.io.IOException ignore) { }
        }
        if (selected != null) list.setSelectedValue(selected, true);
        cards.show(this, model.isEmpty() ? "empty" : "list");
    }

    private void addSamples() {
        try {
            Files.createDirectories(dir());
            for (var e : Samples.CUSTOM_ACTIONS.entrySet()) {
                Path f = dir().resolve(e.getKey() + ".java");
                if (!Files.exists(f)) Files.writeString(f, e.getValue());
            }
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(this, "Could not write the samples: " + e.getMessage(), "Add samples", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void load() {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("Load a script (scripts run with your permissions; load only code you trust)");
        if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
        try {
            Files.createDirectories(dir());
            Path src = fc.getSelectedFile().toPath();
            String base = src.getFileName().toString().replaceAll("\\.[^.]+$", "");
            Files.copy(src, dir().resolve(base + ".java"), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(this, "Could not load: " + e.getMessage(), "Load", JOptionPane.ERROR_MESSAGE);
        }
        reload();
    }

    /** Open the script library, on {@code script} when one is named. */
    private void goToLibrary(String script) {
        if (script != null && host.context() != null) { host.context().scripts().openInLibrary(script); return; }
        for (Frame f : Frame.getFrames()) if (f instanceof SuiteFrame sf) { sf.selectTool("extensions"); break; }
    }
}