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.9 KB
Raw Blame
package opensuite.gate;

import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.core.scanner.HostProcess;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpSender;
import org.zaproxy.zap.extension.ascan.ActiveScan;
import org.zaproxy.zap.extension.ascan.ExtensionActiveScan;
import org.zaproxy.zap.extension.script.ScriptVars;
import org.zaproxy.zap.network.HttpSenderListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * Holds a scan's requests while Open Suite says so, and puts the scan's
 * session on the requests it lets through.
 *
 * <p><b>The hold.</b> The engine's own pause is soft: tests already under way
 * go on sending. This is a hard stop. Open Suite sets a variable naming the
 * sites to hold, the engine scans the hold is for, and a time to hold them
 * until; each request one of those scans is about to send to one of those
 * sites waits here until the variable is cleared or its time passes. Open
 * Suite keeps moving the time forward while it wants the hold, so a hold
 * cannot outlive Open Suite by more than a few seconds. A hold that names no
 * scan holds every scan of the site, as the first version of this add-on did.
 *
 * <p><b>The session.</b> Open Suite sets a second variable holding the
 * session's headers and cookies for a scan's sites. A crawler's request is
 * given them outright. An auditor's request is given them unless the check
 * that built the request has changed that very header or cookie: a test of
 * the session cookie has to reach the application as the test wrote it, and
 * putting the real session back over it would leave nothing tested. A value
 * counts as changed when it is neither the session's value now nor one the
 * session had earlier in the scan.
 *
 * <p><b>The rules.</b> A new audit is given a listener ({@link RuleWatch})
 * as its first request passes here, so Open Suite can be told which rules
 * have been started on which addresses.
 *
 * <p>The hold comes first, so a request that waited goes out with the session
 * as it is when it is let go: after a new login, the new one. Logins, manual
 * requests and proxied browsing are never touched.
 */
public class ExtensionGate extends ExtensionAdaptor implements HttpSenderListener {

    /** A hold is a variable with this prefix; its value is "untilMillis token token ...". */
    public static final String PREFIX = "opensuite.hold.";
    /** A session is a variable with this prefix; its value is one rule to a line. */
    public static final String SESSION = "opensuite.sess.";

    public ExtensionGate() {
        super("ExtensionOpenSuiteGate");
    }

    @Override
    public void hook(ExtensionHook hook) {
        super.hook(hook);
        hook.addHttpSenderListener(this);
        hook.addApiImplementor(new GateApi());
    }

    @Override public boolean canUnload() { return true; }
    @Override public String getAuthor() { return "Open Suite"; }
    @Override public String getDescription() { return "Holds scanner requests while a scan's session is being restored or the scan is paused, applies the scan's session, and reports which rules an audit has run on which addresses."; }
    @Override public String getUIName() { return "Open Suite gate"; }

    /** Before the header rules (order 0), so a typed header of the same name still has the last word, as it had. */
    @Override public int getListenerOrder() { return -100; }

    @Override
    public void onHttpRequestSend(HttpMessage msg, int initiator, HttpSender sender) {
        if (initiator != HttpSender.ACTIVE_SCANNER_INITIATOR && initiator != HttpSender.SPIDER_INITIATOR
                && initiator != HttpSender.AJAX_SPIDER_INITIATOR) return;
        // An audit probes the site before its first rule runs: its first request is in time to start listening to it.
        if (initiator == HttpSender.ACTIVE_SCANNER_INITIATOR) RuleWatch.watchNew();
        String site, url;
        try {
            org.apache.commons.httpclient.URI u = msg.getRequestHeader().getURI();
            int port = u.getPort();
            if (port < 0) port = "https".equalsIgnoreCase(u.getScheme()) ? 443 : 80;
            site = u.getHost() + ":" + port;
            url = u.toString();
        } catch (Exception e) {
            return;
        }
        try {
            while (held(site, ScriptVars.getGlobalVars(), System.currentTimeMillis(), initiator, sender, Thread.currentThread().getName()))
                Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        try {
            applySessions(msg, url, initiator == HttpSender.ACTIVE_SCANNER_INITIATOR, ScriptVars.getGlobalVars());
        } catch (RuntimeException e) {
            // A request is never lost to a fault here: it goes out as it was.
        }
    }

    @Override
    public void onHttpResponseReceive(HttpMessage msg, int initiator, HttpSender sender) { }

    // ------------------------------------------------------------- the hold

    /** Whether any hold that has not run out names this site and, where it names scans, the scan sending this request. */
    private static boolean held(String site, Map<String, String> vars, long now, int initiator, HttpSender sender, String thread) {
        for (Map.Entry<String, String> v : vars.entrySet()) {
            if (!v.getKey().startsWith(PREFIX) || v.getValue() == null) continue;
            String[] parts = v.getValue().trim().split("\\s+");
            if (!GateRules.holds(parts, site, now)) continue;
            List<String> scans = GateRules.scansOf(parts);
            if (scans.isEmpty()) return true;   // a hold on the site, whoever is scanning it
            for (String scan : scans) if (isScan(scan, initiator, sender, thread)) return true;
        }
        return false;
    }

    private static boolean isScan(String scan, int initiator, HttpSender sender, String thread) {
        if (scan.equals("J")) return initiator == HttpSender.AJAX_SPIDER_INITIATOR;
        if (scan.startsWith("S")) return initiator == HttpSender.SPIDER_INITIATOR && GateRules.crawlThread(thread, scan.substring(1));
        if (scan.startsWith("A")) return initiator == HttpSender.ACTIVE_SCANNER_INITIATOR && auditSender(scan.substring(1), sender);
        return false;
    }

    /** An audit sends through senders of its own, one for each host it is auditing. */
    private static boolean auditSender(String id, HttpSender sender) {
        try {
            ExtensionActiveScan ext = Control.getSingleton().getExtensionLoader().getExtension(ExtensionActiveScan.class);
            ActiveScan scan = ext == null ? null : ext.getScan(Integer.parseInt(id));
            if (scan == null) return false;
            for (HostProcess hp : scan.getHostProcesses()) if (hp.getHttpSender() == sender) return true;
            return false;
        } catch (RuntimeException e) {
            return true;   // cannot tell: hold, which is what the hold was asked for
        }
    }

    // ---------------------------------------------------------- the session

    private static volatile String parsedFrom = "";
    private static volatile List<GateRules.Rule> parsed = List.of();

    /** The rules of every session variable, read again only when one has changed. */
    private static List<GateRules.Rule> rules(Map<String, String> vars) {
        StringBuilder all = new StringBuilder();
        for (Map.Entry<String, String> v : new java.util.TreeMap<>(vars).entrySet())
            if (v.getKey().startsWith(SESSION) && v.getValue() != null) all.append(v.getValue()).append('\n');
        String text = all.toString();
        if (text.equals(parsedFrom)) return parsed;
        List<GateRules.Rule> out = GateRules.parse(text);
        parsed = out;
        parsedFrom = text;
        return out;
    }

    private static void applySessions(HttpMessage msg, String url, boolean audit, Map<String, String> vars) {
        List<GateRules.Rule> rules = rules(vars);
        if (rules.isEmpty()) return;
        List<GateRules.Rule> here = new ArrayList<>();
        for (GateRules.Rule r : rules) { Matcher m = r.url().matcher(url); if (m.matches()) here.add(r); }
        if (here.isEmpty()) return;
        boolean cookies = false;
        for (GateRules.Rule r : here) {
            if (r.cookie()) { cookies = true; continue; }
            String now = msg.getRequestHeader().getHeader(r.name());
            String put = GateRules.headerToSend(now, r, audit);
            if (put != null) msg.getRequestHeader().setHeader(r.name(), put);
        }
        if (cookies) {
            String now = msg.getRequestHeader().getHeader("Cookie");
            String put = GateRules.cookiesToSend(now, here, audit);
            if (put != null && !put.equals(now)) msg.getRequestHeader().setHeader("Cookie", put);
        }
    }

}