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.

8.0 KB
Raw Blame
package opensuite.session;

import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.LogEntry;
import opensuite.core.SessionHook;
import opensuite.core.SuiteContext;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Holds the cookie jar, the macros and the session-handling rules, and drives
 * them as the {@link SessionHook} the HttpClient consults around every send.
 *
 * <p>Any tool that passes this on its send options gets: cookies from the jar
 * applied to matching requests, Set-Cookie responses learned back into the jar,
 * and automatic re-authentication when a rule's trigger fires.
 */
public final class SessionManager implements SessionHook {

    private final SuiteContext ctx;
    private final CookieJar jar = new CookieJar();
    private final List<SessionRule> rules = new CopyOnWriteArrayList<>();
    private final List<Macro> macros = new CopyOnWriteArrayList<>();

    public SessionManager(SuiteContext ctx) {
        this.ctx = ctx;
        rules.add(defaultRule());
    }

    /** The rule a new project starts with: the scanner's requests carry the jar's cookies. */
    public static SessionRule defaultRule() {
        SessionRule r = new SessionRule();
        r.name = "Use cookies from the cookie jar";
        r.tools.add("scanner");
        r.trigger = SessionRule.Trigger.NONE;
        return r;
    }

    /** The tools whose traffic can update the cookie jar, and whether each does unless set otherwise. */
    public static final String[] JAR_TOOLS = { "proxy", "scanner", "repeater", "intruder", "sequencer", "extensions" };
    public static String jarKey(String tool) { return "sessions.jar." + tool; }

    /** Whether responses this tool receives update the cookie jar. */
    public boolean learnsFrom(String tool) {
        if (tool == null || ctx == null) return true;
        boolean known = false;
        for (String t : JAR_TOOLS) known |= t.equals(tool);
        if (!known) return true;   // discovery and the like have no tick box of their own
        return "true".equals(ctx.settings().get(jarKey(tool), "proxy".equals(tool) ? "true" : "false"));
    }

    // ---- tracer ----

    /** One thing the session handling did, for the sessions tracer. */
    public record Trace(long time, String tool, String url, String rule, String action) {}

    private static final int TRACE_CAP = 1000;
    private final java.util.ArrayDeque<Trace> trace = new java.util.ArrayDeque<>();
    private final List<Runnable> traceListeners = new CopyOnWriteArrayList<>();
    private volatile boolean tracing;

    /** Tracing costs a little on every request, so it only runs while a tracer window is open. */
    public void setTracing(boolean on) { tracing = on; }
    public boolean tracing() { return tracing; }
    public void addTraceListener(Runnable r) { traceListeners.add(r); }
    public void removeTraceListener(Runnable r) { traceListeners.remove(r); }
    public List<Trace> trace() { synchronized (trace) { return new ArrayList<>(trace); } }
    public void clearTrace() { synchronized (trace) { trace.clear(); } for (Runnable r : traceListeners) r.run(); }

    private void traced(String tool, HttpService svc, HttpMessage req, SessionRule rule, String action) {
        if (!tracing) return;
        String url = svc == null ? "" : svc.url() + (req == null ? "" : req.path());
        synchronized (trace) {
            trace.addLast(new Trace(System.currentTimeMillis(), tool == null ? "" : tool, url, rule == null ? "" : rule.name, action));
            while (trace.size() > TRACE_CAP) trace.removeFirst();
        }
        for (Runnable r : traceListeners) r.run();
    }

    public CookieJar jar()          { return jar; }
    public List<SessionRule> rules(){ return rules; }
    public List<Macro> macros()     { return macros; }

    private final List<Runnable> changeListeners = new CopyOnWriteArrayList<>();
    public void addChangeListener(Runnable r) { changeListeners.add(r); }
    private void fireChanged() { for (Runnable r : changeListeners) r.run(); }

    /**
     * Append a request to a macro, used by the "send to session macro" action.
     * Adds to the last macro, creating a "login" macro if there are none, so the
     * action works whether or not the session-handling window is open.
     */
    public void recordToMacro(HttpService svc, HttpMessage req) {
        if (svc == null || req == null) return;
        Macro m = macros.isEmpty() ? null : macros.get(macros.size() - 1);
        if (m == null) { m = new Macro("login"); macros.add(m); }
        m.items.add(new Macro.Item(svc, req.copy()));
        if (ctx != null) ctx.alert("session", "added a request to macro '" + m.name + "'");
        fireChanged();
    }

    public Macro macro(String name) {
        if (name == null) return null;
        for (Macro m : macros) if (name.equals(m.name)) return m;
        return null;
    }

    // ---- SessionHook ----

    @Override public void beforeSend(String tool, HttpService svc, HttpMessage req) {
        if (svc == null || req == null || !req.isRequest()) return;
        SessionRule apply = null;
        for (SessionRule r : rules) if (r.useCookieJar && r.appliesTo(tool, svc)) { apply = r; break; }
        if (apply == null) return;
        String before = req.header("Cookie");
        String merged = jar.headerFor(svc, req, before);
        if (merged != null && !merged.isEmpty()) req.setHeader("Cookie", merged);
        traced(tool, svc, req, apply, merged == null || merged.isEmpty() || merged.equals(before)
                ? "No cookies in the jar for this request" : "Set the Cookie header from the jar: " + merged);
    }

    @Override public boolean afterResponse(String tool, HttpService svc, HttpMessage req, HttpMessage resp) {
        if (svc == null || resp == null) return false;
        if (learnsFrom(tool)) {
            jar.updateFrom(svc, resp);
            if (tracing && resp.hasHeader("Set-Cookie")) traced(tool, svc, req, null, "Updated the cookie jar from the response");
        }
        for (SessionRule r : rules) {
            if (r.appliesTo(tool, svc) && r.triggered(resp)) {
                Macro m = macro(r.macroName);
                if (m != null) {
                    traced(tool, svc, req, r, "Session invalid (status " + resp.statusCode() + "); ran macro '" + m.name + "' and resent the request");
                    runMacro(m);
                    return true; // re-auth, then retry once
                }
                traced(tool, svc, req, r, "Session invalid, but macro '" + r.macroName + "' does not exist");
            }
        }
        return false;
    }

    /** Run a macro now, logging its traffic so it is visible in the Logger. */
    public Map<String, String> runMacro(Macro m) {
        if (m == null) return Map.of();
        Macro.Recorder rec = ctx == null ? null : (svc, rq, rp) -> {
            LogEntry e = new LogEntry("session", svc, rq);
            e.setResponse(rp);
            ctx.store().add(e);
            ctx.siteMapChanged(e);
        };
        Map<String, String> vals = m.run(jar, rec);
        if (ctx != null) {
            ctx.alert("session", "ran macro '" + m.name + "'"
                    + (vals.isEmpty() ? "" : ", extracted " + vals.keySet()));
        }
        return vals;
    }

    // ---- persistence ----

    public State snapshot() {
        State s = new State();
        s.jar = jar.all();
        s.rules = new ArrayList<>(rules);
        s.macros = new ArrayList<>(macros);
        return s;
    }

    public void restore(State s) {
        if (s == null) return;
        jar.clear();
        if (s.jar != null) for (Cookie c : s.jar) jar.set(c);
        rules.clear();
        if (s.rules != null) rules.addAll(s.rules);
        macros.clear();
        if (s.macros != null) macros.addAll(s.macros);
    }

    public static final class State implements Serializable {
        private static final long serialVersionUID = 1L;
        public List<Cookie> jar;
        public List<SessionRule> rules;
        public List<Macro> macros;
    }
}