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.0 KB
Raw Blame
package opensuite.core;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Shared services every tool reaches for: history, scope, alerts, settings,
 * and the routes that move a message from one tool to another.
 */
public class SuiteContext {

    public interface MessageSink {
        /** Receive a message sent from another tool. */
        void receive(HttpService service, HttpMessage request, HttpMessage response, String caption);

        /**
         * True when the tool stores one blob per send rather than a
         * request/response pair, so the sender must pick exactly one of the two
         * and leave the other null. The comparer is the only such tool: it
         * compares two items the user chose, so handing it both halves of one
         * exchange loads two items from a single click and makes a pair the user
         * never asked for.
         */
        default boolean singleItem() { return false; }
    }

    public interface AlertListener { void alertRaised(Alert a); }

    public interface ScopeListener { void scopeChanged(); }

    public interface SiteMapListener {
        void siteMapChanged(LogEntry e);
        /** A request that was seen to be wanted and was not made: listed in the map as unrequested. */
        default void siteMapSeen(LogEntry e) {}
        /** The whole history was replaced (a project was restored): rebuild once from {@code all}. */
        default void siteMapReloaded(List<LogEntry> all) {}
    }

    public interface IssueListener {
        void issueAdded(Issue i);
        /** An existing finding gained another affected location (de-dup hit). */
        default void issueUpdated(Issue i) {}
        /** All issues were replaced at once (a project was restored): refresh once. */
        default void issuesReloaded() {}
    }

    public interface TaskListener { void taskChanged(ScanTask t); }

    private final MessageStore store = new MessageStore();

    // Bumped on every change worth saving, so the autosave can skip a write
    // when nothing has happened since the last one.
    private final java.util.concurrent.atomic.AtomicLong changes = new java.util.concurrent.atomic.AtomicLong();
    { store.addListener(new MessageStore.Listener() {
        @Override public void entryAdded(LogEntry e)   { changes.incrementAndGet(); }
        @Override public void entryUpdated(LogEntry e) { changes.incrementAndGet(); }
    }); }

    /** A counter that moves whenever the session changes in a way a project file records. */
    public long changeStamp() { return changes.get(); }
    public void touch() { changes.incrementAndGet(); }
    private final WebSocketStore wsStore = new WebSocketStore();
    private final Scope scope = new Scope();
    private final Settings settings = new Settings();
    // The out-of-band collaborator session, shared by the scanner's blind checks
    // and the collaborator tab so one registration and one poll loop serve both.
    private final opensuite.oast.Collaborator collaborator = new opensuite.oast.Collaborator(settings);
    private final opensuite.script.ScriptEngine scripts = new opensuite.script.ScriptEngine();
    // Session handling: the cookie jar, macros and rules, shared by every tool
    // that sends through the HttpClient session hook.
    private final opensuite.session.SessionManager sessions = new opensuite.session.SessionManager(this);
    // Upstream proxy chaining: installed as the HttpClient's proxy provider so
    // every tool's outbound traffic can be routed through an HTTP or SOCKS proxy.
    private final UpstreamProxyManager upstreamProxies = new UpstreamProxyManager(settings);
    { HttpClient.setProxyProvider(upstreamProxies); NetworkConfig.bind(settings); PlatformAuth.bind(settings); }

    // Settings > Project > Scope, "Drop all out-of-scope requests": no tool sends
    // a request outside the scope chosen there, the suite's or a custom one.
    public static final String DROP_OUT_OF_SCOPE = "scope.dropOutOfScope", DROP_MODE = "scope.outOfScope.mode",
            DROP_CUSTOM = "scope.outOfScope.custom";
    private final StoredScope dropScope = new StoredScope(settings, DROP_CUSTOM);
    /** The URLs whose responses never end (Settings > Network > HTTP > Streaming responses). */
    private final StoredScope streaming = new StoredScope(settings, "http.streaming.scope");

    /** The custom scope of "Drop all out-of-scope requests". */
    public Scope dropScope() { return dropScope.scope(); }
    public Scope streamingScope() { return streaming.scope(); }

    /** Keep the scopes held in the settings as they now are; called when any scope is edited. */
    public void saveDropScope() { dropScope.save(); streaming.save(); }

    /** Why a request to this place is dropped, or null when it may be sent. */
    public String dropReason(HttpService svc, HttpMessage request) {
        if (!settings.getBool(DROP_OUT_OF_SCOPE, false)) return null;
        Scope sc = "custom".equals(settings.get(DROP_MODE, "suite")) ? dropScope.scope() : scope;
        String path = "/";
        try { if (request != null && request.path() != null) path = request.path(); } catch (RuntimeException ignored) { }
        boolean in;
        try { in = sc.isInScope(svc, path); } catch (RuntimeException e) { in = true; }
        return in ? null : "dropped: out of scope (Settings > Project > Scope)";
    }

    {
        HttpClient.setGate(this::dropReason);
        NetworkConfig.setStreamTest((svc, path) -> !streaming.scope().isEmpty() && streaming.scope().isInScope(svc, path));
    }
    // The Organizer's shelf of saved items, persisted with the project.
    private final opensuite.organizer.OrganizerStore organizer = new opensuite.organizer.OrganizerStore();
    private final List<Alert> alerts = new ArrayList<>();
    private final List<Issue> issues = new ArrayList<>();
    private final java.util.concurrent.ConcurrentHashMap<String, Issue> issueByKey =
            new java.util.concurrent.ConcurrentHashMap<>();
    private final List<ScanTask> tasks = new ArrayList<>();

    // Read from the thread that saves a project while the window thread may be
    // changing it, so access is synchronized and sinkNames() copies.
    private final Map<String, MessageSink> sinks = java.util.Collections.synchronizedMap(new LinkedHashMap<>());
    private final List<AlertListener> alertListeners = new CopyOnWriteArrayList<>();
    private final List<ScopeListener> scopeListeners = new CopyOnWriteArrayList<>();
    private final List<SiteMapListener> siteMapListeners = new CopyOnWriteArrayList<>();
    private final List<IssueListener> issueListeners = new CopyOnWriteArrayList<>();
    private final List<TaskListener> taskListeners = new CopyOnWriteArrayList<>();
    // The autosave and restore threads walk this list while a tool loaded at run
    // time may be registered or removed from another thread.
    private final List<ToolModule> tools = new CopyOnWriteArrayList<>();
    // State saved for a tool that was not registered when its project was opened
    // (an extension that loads later), by tool name, until the tool registers.
    private final java.util.concurrent.ConcurrentHashMap<String, java.io.Serializable> heldToolStates =
            new java.util.concurrent.ConcurrentHashMap<>();

    // Live passive scanning: the proxy consults this to route in-scope traffic
    // through the scan engine. Null = no live scanning.
    private volatile java.util.function.Function<HttpService, UpstreamProxy> liveScanRouter;

    private java.awt.Frame frame;
    // The project file this session is bound to, chosen at startup. Null for a
    // temporary in-memory project; used as the default target for "save state".
    private volatile java.io.File projectFile;
    private volatile int proxyPort = -1;
    private volatile String caSpki = "";
    private volatile String browserBinary = "";

    public MessageStore store()   { return store; }
    public WebSocketStore wsStore() { return wsStore; }
    public Scope scope()          { return scope; }
    public Settings settings()    { return settings; }

    private final TrafficLog trafficLog = new TrafficLog(settings);
    { store.addListener(trafficLog); }
    private final RestApi restApi = new RestApi(this);
    /** The service of Settings > Suite > REST API. */
    public RestApi restApi() { return restApi; }

    /** The log files of Settings > Project > Logging. */
    public TrafficLog trafficLog() { return trafficLog; }
    public opensuite.oast.Collaborator collaborator() { return collaborator; }
    /** Compiles and runs the script library's scripts, one run at a time. */
    public opensuite.script.ScriptEngine scripts() { return scripts; }
    public opensuite.session.SessionManager sessions() { return sessions; }
    public UpstreamProxyManager upstreamProxies() { return upstreamProxies; }
    public opensuite.organizer.OrganizerStore organizer() { return organizer; }
    public List<ToolModule> tools(){ return tools; }

    public java.awt.Frame frame() { return frame; }
    public void setFrame(java.awt.Frame f) { this.frame = f; }

    public java.io.File projectFile() { return projectFile; }
    public void setProjectFile(java.io.File f) {
        this.projectFile = f;
        Runnable r = onProjectFile;
        if (r != null) r.run();
    }
    private volatile Runnable onProjectFile;
    /** Told whenever the session is bound to another project file, or to none. */
    public void onProjectFile(Runnable r) { this.onProjectFile = r; }

    // True while a project is being opened, so a listener can tell a scope
    // that arrived from the file apart from one the user just added.
    private volatile boolean restoring;
    public boolean restoring() { return restoring; }
    public void setRestoring(boolean b) { this.restoring = b; }

    /** Proxy routing info, set by the proxy tool, used by the browser crawler. */
    public java.util.function.Function<HttpService, UpstreamProxy> liveScanRouter() { return liveScanRouter; }
    public void setLiveScanRouter(java.util.function.Function<HttpService, UpstreamProxy> r) { this.liveScanRouter = r; }

    public int proxyPort()            { return proxyPort; }
    public void setProxyPort(int p)   { this.proxyPort = p; }
    public String caSpki()            { return caSpki; }
    public void setCaSpki(String s)   { this.caSpki = s == null ? "" : s; }
    public String browserBinary()     { return browserBinary; }
    public void setBrowserBinary(String b) { this.browserBinary = b == null ? "" : b; }

    /** Enter a tool in the suite. A tool entered twice is entered once. */
    public void registerTool(ToolModule t) {
        if (!tools.contains(t)) tools.add(t);
    }

    /** Take a tool away: one loaded at run time, when it is removed. It gets no more saved-state questions and no restore. */
    public void unregisterTool(ToolModule t) {
        while (tools.remove(t)) { }
    }

    /**
     * Keep a tool's saved state until the tool registers, for a tool that was not
     * loaded when its project was opened. Nothing is kept for a null name or state.
     */
    public void holdToolState(String toolName, java.io.Serializable state) {
        if (toolName != null && state != null) heldToolStates.put(toolName, state);
    }

    /** The state held for {@code toolName}, and forget it; null when none is held. */
    public java.io.Serializable takeHeldToolState(String toolName) {
        return toolName == null ? null : heldToolStates.remove(toolName);
    }

    // ---- routing between tools ----

    /**
     * Register a destination for "send to <name>". One registered by an
     * extension is not kept raw: a stand-in is kept that offers each message
     * to the extension's own thread.
     */
    public void registerSink(String toolName, MessageSink sink) {
        ExtensionRunner r = ExtensionCaller.calling();
        if (r == null) {
            sinks.put(toolName, sink);
            return;
        }
        MessageSink standIn = r.sink(sink);
        r.onUnload(() -> { synchronized (sinks) { sinks.remove(toolName, standIn); } });
        sinks.put(toolName, standIn);
    }

    /** Take the destination for "send to <name>" away: it leaves the Send to menus at once, and sends to it do nothing. */
    public void unregisterSink(String toolName) { sinks.remove(toolName); }

    public boolean hasSink(String toolName) { return sinks.containsKey(toolName); }

    /** See {@link MessageSink#singleItem()}. False for an unknown tool. */
    public boolean sinkTakesSingleItem(String toolName) {
        MessageSink s = sinks.get(toolName);
        return s != null && s.singleItem();
    }

    /**
     * The tools a message can be sent to from a "Send to" menu. The scanner is
     * left out: it is reached through the menus' own Scan entries.
     */
    public List<String> sinkNames() {
        List<String> out;
        synchronized (sinks) { out = new ArrayList<>(sinks.keySet()); }
        out.remove("scanner");
        return out;
    }

    public void sendTo(String toolName, HttpService svc, HttpMessage req, HttpMessage resp, String caption) {
        MessageSink s = sinks.get(toolName);
        if (s != null) s.receive(svc, req, resp, caption);
        for (java.util.function.Consumer<String> l : sendListeners) l.accept(toolName);
    }

    private final List<java.util.function.Consumer<String>> sendListeners = new java.util.concurrent.CopyOnWriteArrayList<>();
    /** Be told the tool name whenever something is sent to a tool, so the shell can badge its tab. */
    public void addSendListener(java.util.function.Consumer<String> l) {
        sendListeners.add(ExtensionCaller.admit(sendListeners, java.util.function.Consumer.class, l));
    }
    /** Stop being told what is sent; a tool that leaves takes its listener with it. */
    public void removeSendListener(java.util.function.Consumer<String> l) { ExtensionCaller.withdraw(sendListeners, l); }

    private final List<java.util.function.BiConsumer<String, Integer>> countListeners = new java.util.concurrent.CopyOnWriteArrayList<>();
    /** Be told a tool's count of things not yet looked at, so the shell can show it on the tool's tab. */
    public void addCountListener(java.util.function.BiConsumer<String, Integer> l) { countListeners.add(l); }
    /** Say how many things in a tool have not been looked at yet. Nought takes the count off its tab. */
    public void setToolCount(String toolName, int count) {
        for (java.util.function.BiConsumer<String, Integer> l : countListeners) l.accept(toolName, Math.max(0, count));
    }

    // ---- scan launcher ----
    // Starting a scan lives in the dashboard; a right-click in the site map or
    // history starts one through here without those tools depending on each other.

    /** Starts a crawl (and, when {@code audit}, an audit) of a URL. */
    public interface ScanLauncher { void launch(String url, boolean audit); }

    private volatile ScanLauncher scanLauncher;

    public void setScanLauncher(ScanLauncher l) { this.scanLauncher = l; }

    private volatile Runnable pauseAll;
    /** The task owner (the dashboard) says how every running task is paused. */
    public void setPauseAll(Runnable r) { this.pauseAll = r; }

    /** Pause every running task; returns false when nothing owns the tasks yet. */
    public boolean pauseAllTasks() {
        Runnable r = pauseAll;
        if (r == null) return false;
        r.run();
        return true;
    }

    private volatile Runnable resumeAll;
    /** The task owner says how every paused task is set running again. */
    public void setResumeAll(Runnable r) { this.resumeAll = r; }

    /** Resume every paused task; returns false when nothing owns the tasks yet. */
    public boolean resumeAllTasks() {
        Runnable r = resumeAll;
        if (r == null) return false;
        r.run();
        return true;
    }

    private volatile java.util.function.Consumer<String> scanWindow;
    /** The scan owner says how the new scan window is opened on an address. */
    public void setScanWindow(java.util.function.Consumer<String> w) { this.scanWindow = w; }

    /** Open the new scan window with {@code url} filled in; nothing starts until the user says so. */
    public void openScan(String url) {
        java.util.function.Consumer<String> w = scanWindow;
        if (w != null) w.accept(url);
    }

    /** True once a scan engine owner (the dashboard) has registered a launcher. */
    public boolean canScan() { return scanLauncher != null; }

    /** Start a scan of {@code url}; crawl and audit when {@code audit}, crawl only otherwise. */
    public void launchScan(String url, boolean audit) {
        ScanLauncher l = scanLauncher;
        if (l != null && url != null && !url.isBlank()) l.launch(url, audit);
    }

    // ---- history ----

    public LogEntry record(String tool, HttpService svc, HttpMessage req) {
        LogEntry e = new LogEntry(tool, svc, req);
        store.add(e);
        return e;
    }

    public void siteMapChanged(LogEntry e) {
        for (SiteMapListener l : siteMapListeners) l.siteMapChanged(e);
    }

    /** List in the site map a request that was seen to be wanted (a link, a call a page tried to make) and was not made. */
    public void siteMapSeen(LogEntry e) {
        for (SiteMapListener l : siteMapListeners) l.siteMapSeen(e);
    }

    /** Tell the site map listeners the history was replaced wholesale. */
    public void siteMapReloaded(List<LogEntry> all) {
        for (SiteMapListener l : siteMapListeners) l.siteMapReloaded(all);
    }

    public void addSiteMapListener(SiteMapListener l) { siteMapListeners.add(ExtensionCaller.admit(siteMapListeners, SiteMapListener.class, l)); }
    /** Stop being told of site map changes; a tool that leaves takes its listener with it. */
    public void removeSiteMapListener(SiteMapListener l) { ExtensionCaller.withdraw(siteMapListeners, l); }

    // ---- issues ----

    /**
     * Add a scanner issue, de-duplicated. Returns true if newly added. When the
     * same finding is seen again (a de-dup hit), its new location is recorded on
     * the existing issue rather than dropped, so a site-wide finding keeps every
     * affected path without being stored once per URL.
     */
    public boolean addIssue(Issue i) {
        if (i == null) return false;
        Issue existing = issueByKey.putIfAbsent(i.dedupeKey(), i);
        if (existing != null) {
            // Same finding seen again: record this scan as a finder and the new
            // location, so each task's view shows the issues it found even though
            // the issue itself is stored once.
            boolean changed = existing.addLocation(i.path(), i.param());
            changed |= existing.addFoundBy(i.source());
            if (changed) {
                touch();
                for (IssueListener l : issueListeners) l.issueUpdated(existing);
            }
            return false;
        }
        synchronized (issues) { issues.add(i); }
        touch();
        for (IssueListener l : issueListeners) l.issueAdded(i);
        return true;
    }

    /** The issue already held for the same finding as {@code i}, or null. */
    public Issue existingIssue(Issue i) {
        return i == null ? null : issueByKey.get(i.dedupeKey());
    }

    /** Remove the issues matching {@code p}; returns how many were removed. */
    public int removeIssuesWhere(java.util.function.Predicate<Issue> p) {
        java.util.List<Issue> removed = new ArrayList<>();
        synchronized (issues) {
            issues.removeIf(i -> {
                if (p.test(i)) { issueByKey.remove(i.dedupeKey()); removed.add(i); return true; }
                return false;
            });
        }
        if (!removed.isEmpty()) {
            touch();
            for (IssueListener l : issueListeners) l.issuesReloaded();
        }
        return removed.size();
    }

    /** Issues were edited in place (not added): refresh the views once. */
    public void issuesChanged() {
        for (IssueListener l : issueListeners) l.issuesReloaded();
    }

    public List<Issue> issues() {
        synchronized (issues) { return new ArrayList<>(issues); }
    }

    /**
     * Replace all issues (used when restoring a saved project). Listeners get
     * one {@code issuesReloaded} rather than an event per issue.
     */
    public void restoreIssues(List<Issue> saved) {
        synchronized (issues) {
            issues.clear();
            issueByKey.clear();
            if (saved != null) {
                for (Issue i : saved) {
                    if (i != null && issueByKey.putIfAbsent(i.dedupeKey(), i) == null) issues.add(i);
                }
            }
        }
        for (IssueListener l : issueListeners) l.issuesReloaded();
    }

    public void addIssueListener(IssueListener l) { issueListeners.add(ExtensionCaller.admit(issueListeners, IssueListener.class, l)); }
    /** Stop being told of issues; a tool that leaves takes its listener with it. */
    public void removeIssueListener(IssueListener l) { ExtensionCaller.withdraw(issueListeners, l); }

    // ---- scan tasks ----

    public void addTask(ScanTask t) {
        synchronized (tasks) { tasks.add(t); }
        taskChanged(t);
    }

    public void removeTask(ScanTask t) {
        synchronized (tasks) { tasks.remove(t); }
        taskChanged(t);
    }

    public List<ScanTask> tasks() {
        synchronized (tasks) { return new ArrayList<>(tasks); }
    }

    /** The scans worth saving: everything but the always-present live passive audit. */
    public List<ScanTask.Snapshot> taskSnapshots() {
        List<ScanTask.Snapshot> out = new ArrayList<>();
        for (ScanTask t : tasks()) {
            if (t.type() != ScanTask.Type.LIVE_PASSIVE) out.add(t.snapshot());
        }
        return out;
    }

    /**
     * Put a project's saved scans back on the dashboard, replacing any scans of
     * this session; the live passive audit stays. Each comes back finished.
     */
    public void restoreTasks(List<ScanTask.Snapshot> saved) {
        List<ScanTask> restored = new ArrayList<>();
        if (saved != null) for (ScanTask.Snapshot s : saved) if (s != null) restored.add(ScanTask.fromSnapshot(s));
        synchronized (tasks) {
            tasks.removeIf(t -> t.type() != ScanTask.Type.LIVE_PASSIVE);
            tasks.addAll(restored);
        }
        for (ScanTask t : restored) taskChanged(t);
    }

    public void taskChanged(ScanTask t) {
        touch();
        for (TaskListener l : taskListeners) l.taskChanged(t);
    }

    public void addTaskListener(TaskListener l) { taskListeners.add(ExtensionCaller.admit(taskListeners, TaskListener.class, l)); }
    /** Stop being told of scan tasks; a tool that leaves takes its listener with it. */
    public void removeTaskListener(TaskListener l) { ExtensionCaller.withdraw(taskListeners, l); }

    // ---- alerts ----

    public synchronized void alert(String tool, String message) {
        if (!alerts.isEmpty()) {
            Alert last = alerts.get(alerts.size() - 1);
            if (last.tool.equals(tool == null ? "suite" : tool) && last.message.equals(message)) {
                last.repeats++;
                for (AlertListener l : alertListeners) l.alertRaised(last);
                return;
            }
        }
        Alert a = new Alert(tool, message);
        alerts.add(a);
        for (AlertListener l : alertListeners) l.alertRaised(a);
    }

    public synchronized List<Alert> alerts() { return new ArrayList<>(alerts); }
    public synchronized void clearAlerts()   { alerts.clear(); }
    public void addAlertListener(AlertListener l) { alertListeners.add(ExtensionCaller.admit(alertListeners, AlertListener.class, l)); }
    /** Stop being told of events; a tool that leaves takes its listener with it. */
    public void removeAlertListener(AlertListener l) { ExtensionCaller.withdraw(alertListeners, l); }

    // ---- scope ----

    public void scopeChanged() { touch(); for (ScopeListener l : scopeListeners) l.scopeChanged(); }
    public void addScopeListener(ScopeListener l) { scopeListeners.add(ExtensionCaller.admit(scopeListeners, ScopeListener.class, l)); }
    /** Stop being told of scope changes; a tool that leaves takes its listener with it. */
    public void removeScopeListener(ScopeListener l) { ExtensionCaller.withdraw(scopeListeners, l); }
}