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.

27.4 KB
Raw Blame
package opensuite.engine;

import opensuite.core.HttpClient;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.LogEntry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * How a scan stays logged in. The scanner's requests are given the headers of a
 * working session (its cookies, its token) and nothing else in the suite is:
 * browsing, Repeater and the other tools send what they always sent.
 *
 * <p>The headers come from one of two places. In {@link Mode#BROWSER} they are
 * the ones the user's own browsing through the proxy carried, picked out of
 * the proxy history, so any login a person can do in a browser works. In
 * {@link Mode#CREDENTIALS} the suite logs in itself with a username and a
 * password and uses what the application hands back, which lets a scan log in
 * again unattended. Either way a session check tells the scan when the
 * session has ended: a request, and text the user marked in its response that
 * is there only while logged in. The session is valid while the response
 * contains that text. Nothing else about a response is judged: not its status
 * code and not its size, which differ from one application to the next.
 */
public final class ScanAuth {

    public enum Mode { NONE, BROWSER, CREDENTIALS }

    /**
     * One header the scanner sends. {@code site} is the service it belongs to,
     * as {@link HttpService#url()} gives it, or empty for every target.
     */
    public record Header(String site, String name, String value) {
        public String key() { return site + "\n" + name.toLowerCase(Locale.ROOT); }
    }

    /**
     * A request that answers one way when logged in and another when not. It
     * remembers both answers, so a later answer can be told to be one, the
     * other, or neither.
     */
    /**
     * The names of form fields that carry a fresh token on every request, for
     * the scanner to refresh before each test. The engine knows the usual
     * names already; these are any others this application uses.
     */
    public List<String> formTokens = new ArrayList<>();

    /** The token names the engine knows without being told. A field whose name contains one of them is covered. */
    static final List<String> USUAL_TOKENS = List.of("anticsrf", "csrftoken", "__requestverificationtoken", "csrfmiddlewaretoken",
            "authenticity_token", "owasp_csrftoken", "anoncsrf", "csrf_token", "_csrf", "_csrfsecret", "__csrf_magic", "csrf", "_token");

    private static final java.util.regex.Pattern HIDDEN_INPUT = java.util.regex.Pattern.compile(
            "(?is)<input\\b[^>]*\\btype\\s*=\\s*[\"']?hidden\\b[^>]*>");
    private static final java.util.regex.Pattern NAME_ATTR = java.util.regex.Pattern.compile(
            "(?is)\\bname\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))");

    /**
     * The hidden fields of forms seen at these sites whose names the engine
     * would not take for a token by itself: what to offer when asked which
     * fields might be tokens. Nothing is guessed about what a field is for.
     */
    public static List<String> hiddenFields(List<LogEntry> history, Set<String> sites, int limit) {
        List<String> out = new ArrayList<>();
        for (int i = history.size() - 1, looked = 0; i >= 0 && looked < 5000 && out.size() < limit; i--, looked++) {
            LogEntry e = history.get(i);
            try {
                if (e.service() == null || !sites.contains(e.service().url()) || e.response() == null) continue;
                String body = e.response().bodyText();
                if (body == null || body.indexOf("<input") < 0 && body.indexOf("<INPUT") < 0) continue;
                java.util.regex.Matcher m = HIDDEN_INPUT.matcher(body);
                while (m.find() && out.size() < limit) {
                    java.util.regex.Matcher n = NAME_ATTR.matcher(m.group());
                    if (!n.find()) continue;
                    String name = n.group(1) != null ? n.group(1) : n.group(2) != null ? n.group(2) : n.group(3);
                    if (name == null || name.isBlank() || out.contains(name)) continue;
                    String low = name.toLowerCase(java.util.Locale.ROOT);
                    boolean usual = false;
                    for (String u : USUAL_TOKENS) if (low.contains(u)) { usual = true; break; }
                    if (!usual) out.add(name);
                }
            } catch (RuntimeException ignored) { }
        }
        return out;
    }

    /**
     * A session check: a request, and the text its response contains only
     * while the session is valid. The text is marked by the user in a real
     * response of this application and proven before use: see {@link #measure}.
     */
    public static final class Check {
        public HttpService service;
        public HttpMessage request;
        /** The text a logged-in response contains. A check without it is not used. */
        public String text = "";
        /** What proving it on the application showed, in words, and whether that makes it fit to use. */
        public String measured = "";
        public boolean usable;
        /** The text was found without the session too: it would say "logged in" for ever, so the check is never used. */
        public boolean misleading;
        /** The session headers it was found to depend on, as {@link Header#key()} gives them. */
        public final Set<String> needs = new java.util.LinkedHashSet<>();

        public Check() {}
        public Check(HttpService service, HttpMessage request) {
            this.service = service; this.request = request;
        }

        public String label() {
            if (service == null || request == null) return "";
            return request.method() + " " + service.url() + request.requestTarget()
                    + (text.isEmpty() ? "" : " containing " + quoted(text));
        }
    }

    /**
     * What an answer to a check says. {@code IN}: the marked text is there.
     * {@code OUT}: it is not. {@code UNKNOWN}: the target gave no answer or an
     * error of its own, which says nothing about the session. Only
     * {@code OUT} is a reason to act.
     */
    public enum State { IN, OUT, UNKNOWN }

    /** What a check found. */
    public record Verdict(State state, int status, String detail) {
        public boolean loggedIn() { return state == State.IN; }
    }

    public Mode mode = Mode.NONE;
    /**
     * What the browser the session was made in holds in its storage for each
     * site, names prefixed "local:" or "session:". A single-page application
     * keeps its login there and not in a cookie, so the scan's own browser is
     * given the same before it crawls.
     */
    public final Map<String, Map<String, String>> storage = new LinkedHashMap<>();
    /** The session's headers: ticked in the wizard, or returned by a login. */
    public final List<Header> headers = new ArrayList<>();
    /** Headers typed in by hand, sent as well whatever the mode. */
    public final List<Header> extra = new ArrayList<>();
    /** Take up a newer session when the browser gets one while the scan runs. */
    public boolean follow = true;
    /** The session checks the user set. With none, the session is not monitored: nothing is worked out in their place. */
    public final List<Check> checks = new ArrayList<>();
    /** Leave links that log out alone. */
    public boolean skipLogout = true;
    /** The browser's session was asked for, but there was none to use: the scan runs logged out and must say so. */
    public boolean sessionMissing;
    /** Leave alone addresses that repeat themselves, which is a crawl going round in a loop. Holds whether or not the scan logs in. */
    public boolean skipLoops = true;
    /** Addresses the scan leaves alone as well, one pattern each; * stands for anything. */
    public final List<String> avoid = new ArrayList<>();
    /** Cookies the user unticked, as site, a line break, and the cookie's name: never sent, even when the browser sends them later. */
    public final Set<String> dropCookies = new java.util.LinkedHashSet<>();
    /** Watch the session while the scan runs. Off, the session is never checked and the scan never pauses for it. */
    public boolean monitor = true;
    /** Pause the scan when the session ends; off, the scan carries on and only says so. */
    public boolean pauseOnLoss = true;
    public String username = "", password = "";
    /** The page to log in at, or empty to find it when the scan starts. */
    public String loginUrl = "";
    /** Log in again by itself when the session ends. */
    public boolean relogin = true;

    /** True when the scan sends nothing of its own: no session and no extra headers. */
    public boolean isEmpty() {
        return mode == Mode.NONE && extra.isEmpty();
    }

    /** A line for the task's event log. */
    public String describe() {
        String extras = extra.isEmpty() ? "" : " and " + extra.size() + " extra header(s)";
        return switch (mode) {
            case BROWSER -> "the browser's session (" + names(headers) + ")" + extras;
            case CREDENTIALS -> "a login as " + username + extras;
            case NONE -> extra.isEmpty() ? "no login" : extra.size() + " extra header(s)";
        };
    }

    private static String names(List<Header> hs) {
        java.util.Set<String> n = new java.util.LinkedHashSet<>();
        for (Header h : hs) n.add(h.name());
        return n.isEmpty() ? "no headers" : String.join(", ", n);
    }

    public ScanAuth copy() {
        ScanAuth a = new ScanAuth();
        a.mode = mode; a.headers.addAll(headers); a.extra.addAll(extra); a.follow = follow;
        a.checks.addAll(checks); a.skipLogout = skipLogout; a.skipLoops = skipLoops; a.sessionMissing = sessionMissing; a.username = username; a.password = password;
        a.avoid.addAll(avoid); a.dropCookies.addAll(dropCookies); a.monitor = monitor; a.pauseOnLoss = pauseOnLoss;
        a.loginUrl = loginUrl; a.relogin = relogin;
        for (Map.Entry<String, Map<String, String>> e : storage.entrySet()) a.storage.put(e.getKey(), new LinkedHashMap<>(e.getValue()));
        return a;
    }

    // ------------------------------------------------- picking out a session

    /**
     * Header names the user has said carry this application's session. An
     * application of its own making may name such a header anything at all,
     * so the names below cannot be the whole list. Held in lower case.
     */
    public static final Set<String> MARKED = java.util.concurrent.ConcurrentHashMap.newKeySet();

    /** Whether a request header is one that carries a session or a credential. */
    public static boolean isAuthHeader(String name) {
        String n = name.toLowerCase(Locale.ROOT);
        if (n.equals("cookie") || n.equals("authorization") || MARKED.contains(n)) return true;
        if (n.startsWith("proxy-") || n.startsWith("sec-") || n.startsWith("accept") || n.startsWith("content-")) return false;
        if (n.equals("www-authenticate") || n.equals("origin") || n.equals("referer")) return false;
        return n.contains("token") || n.contains("api-key") || n.contains("apikey") || n.contains("api_key")
                || n.contains("auth") || n.contains("session") || n.contains("csrf") || n.contains("xsrf");
    }

    /** How far back in the proxy history a session is looked for. */
    private static final int LOOK_BACK = 3000;

    /**
     * The session the browser is using with each of the sites: the newest
     * value of every session header its requests through the proxy carried.
     * Cookies are merged across requests, the newest value of each winning, so
     * a cookie the browser sends only to some paths is not lost.
     *
     * @param history the message store's entries, oldest first
     * @param sites   the services to look at, as {@link HttpService#url()} gives them
     * @param after   only entries numbered above this are read (0 for all)
     */
    public static List<Header> capture(List<LogEntry> history, Collection<String> sites, int after) {
        Map<String, Header> found = new LinkedHashMap<>();
        Map<String, Map<String, String>> cookies = new LinkedHashMap<>();
        int looked = 0;
        for (int i = history.size() - 1; i >= 0 && looked < LOOK_BACK; i--) {
            LogEntry e = history.get(i);
            if (e.number() <= after) break;
            if (!"proxy".equals(e.tool()) || e.service() == null) continue;
            String site = e.service().url();
            if (!sites.contains(site)) continue;
            looked++;
            HttpMessage req;
            try { req = e.request(); } catch (RuntimeException ex) { continue; }
            if (req == null) continue;
            absorb(site, req, found, cookies);
        }
        return gathered(found, cookies);
    }

    /**
     * The User-Agent of the browser the session was made in: that of the
     * newest request the proxy saw to one of the sites. An application that
     * ties a session to the browser it began in ends it when the header
     * changes, so a scan that borrows the session sends the same one.
     */
    public static String userAgent(List<LogEntry> history, Collection<String> sites) {
        int looked = 0;
        for (int i = history.size() - 1; i >= 0 && looked < LOOK_BACK; i--) {
            LogEntry e = history.get(i);
            if (!"proxy".equals(e.tool()) || e.service() == null || !sites.contains(e.service().url())) continue;
            looked++;
            try {
                HttpMessage req = e.request();
                String ua = req == null ? null : req.header("User-Agent");
                if (ua != null && !ua.isBlank()) return ua.trim();
            } catch (RuntimeException ignored) { }
        }
        return null;
    }

    /** The same, from the requests a browser made while the engine logged in with it, oldest first. */
    static List<Header> captureFrom(List<EngineLogin.Seen> seen) {
        Map<String, Header> found = new LinkedHashMap<>();
        Map<String, Map<String, String>> cookies = new LinkedHashMap<>();
        for (int i = seen.size() - 1; i >= 0; i--) absorb(seen.get(i).service().url(), seen.get(i).request(), found, cookies);
        return gathered(found, cookies);
    }

    /** Take a request's session headers in; called newest request first, so what is already there is newer. */
    private static void absorb(String site, HttpMessage req, Map<String, Header> found, Map<String, Map<String, String>> cookies) {
        for (String line : req.headerLines()) {
            int c = line.indexOf(':');
            if (c <= 0) continue;
            String name = line.substring(0, c).trim(), value = line.substring(c + 1).trim();
            if (value.isEmpty() || !isAuthHeader(name)) continue;
            if (name.equalsIgnoreCase("cookie")) {
                Map<String, String> jar = cookies.computeIfAbsent(site, k -> new LinkedHashMap<>());
                for (Map.Entry<String, String> ck : parseCookies(value).entrySet()) jar.putIfAbsent(ck.getKey(), ck.getValue());
            } else {
                Header h = new Header(site, name, value);
                found.putIfAbsent(h.key(), h);
            }
        }
    }

    private static List<Header> gathered(Map<String, Header> found, Map<String, Map<String, String>> cookies) {
        List<Header> out = new ArrayList<>();
        for (Map.Entry<String, Map<String, String>> s : cookies.entrySet())
            if (!s.getValue().isEmpty()) out.add(new Header(s.getKey(), "Cookie", cookieHeader(s.getValue())));
        out.addAll(found.values());
        return out;
    }

    /**
     * The headers of {@code current} brought up to date with {@code newer}: a
     * header the browser has since sent with another value takes that value,
     * and cookies are merged name by name. Headers the user did not choose
     * are not added. Returns null when nothing changed.
     */
    public static List<Header> merged(List<Header> current, List<Header> newer) {
        return merged(current, newer, Set.of());
    }

    /** The same, leaving out the cookies in {@code dropped} (site, a line break, the cookie's name). */
    public static List<Header> merged(List<Header> current, List<Header> newer, Set<String> dropped) {
        Map<String, Header> byKey = new LinkedHashMap<>();
        for (Header h : newer) byKey.put(h.key(), h);
        List<Header> out = new ArrayList<>();
        boolean changed = false;
        for (Header h : current) {
            Header n = byKey.get(h.key());
            if (n == null) { out.add(h); continue; }
            String value = n.value();
            if (h.name().equalsIgnoreCase("cookie")) {
                Map<String, String> jar = parseCookies(h.value());
                for (Map.Entry<String, String> ck : parseCookies(n.value()).entrySet())
                    if (!dropped.contains(h.site() + "\n" + ck.getKey())) jar.put(ck.getKey(), ck.getValue());
                value = cookieHeader(jar);
            }
            if (!value.equals(h.value())) changed = true;
            out.add(new Header(h.site(), h.name(), value));
        }
        return changed ? out : null;
    }

    public static Map<String, String> parseCookies(String header) {
        Map<String, String> out = new LinkedHashMap<>();
        for (String part : header.split(";")) {
            String p = part.trim();
            if (p.isEmpty()) continue;
            int eq = p.indexOf('=');
            if (eq < 0) out.put(p, ""); else out.put(p.substring(0, eq).trim(), p.substring(eq + 1).trim());
        }
        return out;
    }

    public static String cookieHeader(Map<String, String> jar) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> c : jar.entrySet()) {
            if (sb.length() > 0) sb.append("; ");
            sb.append(c.getKey()).append('=').append(c.getValue());
        }
        return sb.toString();
    }

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

    /**
     * Requests from the browser's history to offer for a session check: the
     * pages and API calls it fetched, newest first, each address once. Only
     * GET requests are offered, since a check is sent again and again and
     * must change nothing. Which of them shows a login is for the user to say,
     * by marking text in its response.
     */
    public static List<Check> candidates(List<LogEntry> history, Collection<String> sites, int limit) {
        List<Check> out = new ArrayList<>();
        Set<String> seen = new java.util.HashSet<>();
        int looked = 0;
        for (int i = history.size() - 1; i >= 0 && looked < LOOK_BACK && out.size() < limit; i--) {
            LogEntry e = history.get(i);
            if (!"proxy".equals(e.tool()) || e.service() == null || !sites.contains(e.service().url())) continue;
            looked++;
            try {
                if (e.status() < 200 || e.status() > 299 || !"GET".equals(e.method())) continue;
                String ext = e.fileExtension();
                if (ext != null && ext.matches("(?i)js|css|png|jpe?g|gif|svg|ico|woff2?|ttf|map|webp|mp4")) continue;
                HttpMessage req = e.request();
                if (req == null || !seen.add(e.service().url() + req.requestTarget())) continue;
                out.add(new Check(e.service(), req.copy()));
            } catch (RuntimeException ignored) { /* an entry that cannot be read is no candidate */ }
        }
        return out;
    }

    /** The same, from the requests a browser made while the engine logged in with it, newest first. */
    static List<Check> candidatesFrom(List<EngineLogin.Seen> seen, int limit) {
        List<Check> out = new ArrayList<>();
        Set<String> had = new java.util.HashSet<>();
        for (int i = seen.size() - 1; i >= 0 && out.size() < limit; i--) {
            EngineLogin.Seen s = seen.get(i);
            HttpMessage req = s.request();
            if (s.status() < 200 || s.status() > 299 || !"GET".equals(req.method())) continue;
            if (req.path().matches("(?i).*\\.(js|css|png|jpe?g|gif|svg|ico|woff2?|ttf|map|webp|mp4)")) continue;
            if (!had.add(s.service().url() + req.requestTarget())) continue;
            out.add(new Check(s.service(), req.copy()));
        }
        return out;
    }

    /** The check's request as the scanner would send it: with the session's headers put on. */
    static HttpMessage dressed(Check c, List<Header> headers, boolean withSession) {
        HttpMessage req = c.request.copy();
        String site = c.service.url();
        // The request came from the browser with its own session on it; take that off first.
        for (String line : new ArrayList<>(req.headerLines())) {
            int i = line.indexOf(':');
            if (i > 0 && isAuthHeader(line.substring(0, i).trim())) req.removeHeader(line.substring(0, i).trim());
        }
        req.removeHeader("If-None-Match");
        req.removeHeader("If-Modified-Since");
        if (withSession)
            for (Header h : headers)
                if (h.site().isEmpty() || h.site().equals(site)) req.setHeader(h.name(), h.value());
        return req;
    }

    /**
     * A response as text: its head and its unpacked body, with line ends as
     * plain line feeds. This one form is what the user is shown to mark text
     * in and what is searched for that text afterwards, so what was marked is
     * what is looked for.
     */
    public static String shown(HttpMessage response) {
        if (response == null) return "";
        return (response.headerText() + response.bodyText()).replace("\r\n", "\n");
    }

    /**
     * One sending of a check: the request as it was sent, the status and the
     * response as {@link #shown} gives it, or why there was none.
     */
    public record Answer(String sent, int status, String shown, String error) {
        public boolean ok() { return error == null; }
    }

    /** Send the check's request, with the session's headers or with none. Redirects are not followed: the answer is the application's own. */
    public static Answer ask(Check c, List<Header> headers, boolean withSession) {
        HttpClient.Options opt = new HttpClient.Options();
        opt.followRedirects = false;
        opt.updateContentLength = true;
        HttpMessage out = dressed(c, headers, withSession);
        HttpClient.Result r = new HttpClient().send(c.service, out, opt);
        if (!r.ok()) return new Answer(shown(out), 0, "", String.valueOf(r.error));
        return new Answer(shown(out), r.response.statusCode(), shown(r.response), null);
    }

    /** Send the check with the given headers and say whether the answer is a logged-in one. */
    public static Verdict run(Check c, List<Header> headers) {
        Answer a = ask(c, headers, true);
        if (!a.ok()) return new Verdict(State.UNKNOWN, 0, "returned no response: " + a.error());
        return judge(c, a.status(), a.shown());
    }

    /**
     * What an answer says about the session, by the one rule there is: the
     * session is valid while the response contains the marked text. Without
     * the text it is logged out, unless the target is failing (an error of
     * its own, too many requests, a time-out), which says nothing either way.
     */
    static Verdict judge(Check c, int status, String shown) {
        String why = "returned " + status;
        if (c.text.isEmpty()) return new Verdict(State.UNKNOWN, status, "has no logged-in text set");
        if (shown != null && shown.contains(c.text)) return new Verdict(State.IN, status, why + " containing " + quoted(c.text));
        if (status >= 500 || status == 429 || status == 408)
            return new Verdict(State.UNKNOWN, status, why + ", which indicates a target-side failure");
        return new Verdict(State.OUT, status, why + " without " + quoted(c.text));
    }

    /** Text in quotation marks for a message, cut short when long and kept to one line. */
    public static String quoted(String text) {
        String t = text == null ? "" : text.replace("\n", " ").strip();
        return "\"" + (t.length() > 60 ? t.substring(0, 57) + "..." : t) + "\"";
    }

    /** How many times a check is sent with the session when it is proven. */
    public static final int TIMES = 3;

    /** What proving a check showed: whether it can be used, why, and the last answers either way for the user to look at. */
    public record Proof(boolean ok, boolean misleading, String said, Answer with, Answer without) {}

    /**
     * Prove a check on the application before it is relied on. Its request is
     * sent {@value #TIMES} times with the session and the text must be in
     * every answer: text that comes and goes (a time, a token) would report a
     * lost session that is not lost. It is then sent once without the session
     * and the text must be absent: text that is there either way would never
     * report a loss at all.
     */
    public static Proof prove(Check c, List<Header> headers) {
        if (c.text.isEmpty()) return new Proof(false, false, "No logged-in text is set.", null, null);
        String t = quoted(c.text);
        Answer with = null;
        for (int i = 1; i <= TIMES; i++) {
            with = ask(c, headers, true);
            if (!with.ok()) return new Proof(false, false, "No response with the session (" + with.error() + ").", with, null);
            if (!with.shown().contains(c.text))
                return new Proof(false, false, "Not verified: " + t + " is not in the response with the session (request " + i + " of " + TIMES
                        + " returned " + with.status() + ").", with, null);
        }
        Answer without = ask(c, headers, false);
        if (!without.ok())
            return new Proof(false, false, "Not verified: no response without the session (" + without.error() + ").", with, without);
        if (without.shown().contains(c.text))
            return new Proof(false, true, "Not usable: " + t + " is also in the response without the session, so it cannot detect a logout.",
                    with, without);
        return new Proof(true, false, "Verified: " + t + " is in " + TIMES + " of " + TIMES + " responses with the session and absent without it.",
                with, without);
    }

    /**
     * Prove a check and record the result on it, then find which of the
     * session's headers it depends on by sending it with each one left out
     * in turn: the ones without which the text is gone.
     */
    public static Proof measure(Check c, List<Header> session, List<Header> extra) {
        List<Header> all = new ArrayList<>(extra);
        all.addAll(session);
        Proof p = prove(c, all);
        c.usable = p.ok();
        c.misleading = p.misleading();
        c.measured = p.said();
        c.needs.clear();
        if (!c.usable) return p;
        List<Header> own = new ArrayList<>();
        for (Header h : session) if (h.site().isEmpty() || h.site().equals(c.service.url())) own.add(h);
        if (own.size() == 1) { c.needs.add(own.get(0).key()); return p; }
        for (Header h : own) {
            List<Header> rest = new ArrayList<>(all);
            rest.remove(h);
            if (run(c, rest).state() == State.OUT) c.needs.add(h.key());
        }
        return p;
    }

    /** The session headers that none of the checks depends on: their ending would not be noticed. */
    public static List<Header> unwatched(List<Check> checks, List<Header> session) {
        Set<String> covered = new java.util.HashSet<>();
        for (Check c : checks) if (c.usable) covered.addAll(c.needs);
        List<Header> out = new ArrayList<>();
        for (Header h : session) if (!covered.contains(h.key())) out.add(h);
        return out;
    }

}