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.

35.5 KB
Raw Blame
package opensuite.engine;

import opensuite.core.Debug;
import opensuite.core.HttpService;
import opensuite.core.ScanTask;
import opensuite.core.SuiteContext;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Keeps one scan logged in. It gives the engine the session's headers for the
 * scan's targets, watches the session while the scan runs, and takes the
 * headers away again when the scan is over.
 *
 * <p>While the scan runs it does two things on a timer. It looks at what the
 * browser has sent through the proxy since it last looked, and takes up a
 * newer cookie or token. And it sends the session checks. Only an answer that
 * is positively a logged-out one, twice running, counts as the session
 * ending: a target that is failing, or an answer like nothing seen before, is
 * tried again and nothing else. When the session has ended, a scan that logs
 * in by itself logs in again, and otherwise the scan is paused with a note
 * asking for a new login and resumed as soon as there is a working session,
 * or, when it was told not to pause, carries on and says so.
 *
 * <p>Every part of this can be switched off for a scan: the watching as a
 * whole, the pausing, the logging in again, and the check for each header.
 */
public final class SessionGuard {

    private static final int EVERY_MS = 1000, RECHECK_MS = 500, WAITING_MS = 3000;

    private final SuiteContext ctx;
    private final ZapApi api;
    private final ScanAuth auth;
    private final ScanTask task;
    private final Set<String> sites = new LinkedHashSet<>();
    private final List<HttpService> services = new ArrayList<>();
    private final String rulePrefix;

    private volatile List<ScanAuth.Header> live = new ArrayList<>();
    private final List<ScanAuth.Check> checks = new ArrayList<>();
    private final List<String> rules = new ArrayList<>();
    private volatile boolean pausedHere;
    /** The scan is held for a moment while a logged-out answer is asked for again, or while logging in again. */
    private volatile boolean holding;
    private volatile Thread watcher;
    private volatile boolean ended;
    private int lastSeen;
    private int failures, logins;
    /** When a session the scan carried on without was seen to end, or 0. */
    private long lostAt;
    private boolean saidUnknown;
    private String loginUrl;

    public SessionGuard(SuiteContext ctx, ZapApi api, ScanAuth auth, List<ZapScanner.Seed> seeds, ScanTask task) {
        this.ctx = ctx;
        this.api = api;
        this.auth = auth == null ? new ScanAuth() : auth;
        this.task = task;
        this.rulePrefix = "Open Suite scan " + task.number + " header ";
        for (ZapScanner.Seed s : seeds) if (sites.add(s.service().url())) services.add(s.service());
        // A session header for a site other than a seed (an API on its own host) brings that site in.
        for (ScanAuth.Header h : this.auth.headers) if (!h.site().isEmpty()) sites.add(h.site());
    }

    /** True when the scan was paused by the guard, not by the user. */
    public boolean waitingForLogin() { return pausedHere; }

    /** The headers the scanner is sending now. */
    public List<ScanAuth.Header> headers() { return new ArrayList<>(live); }

    /** The session checks in use. */
    public List<ScanAuth.Check> checks() { return new ArrayList<>(checks); }

    /**
     * Patterns for the addresses the scan is to leave alone, matched against
     * the whole address: the links that end a session, guessed by name for
     * each site, and the ones the user listed.
     */
    public List<String> logoutPatterns() {
        return new ArrayList<>(skipRules().keySet());
    }

    /** Why a URL was skipped, for the list the scan gives of what it left out. */
    public static final String WHY_LOGOUT = "log out link", WHY_LISTED = "out of scope for this scan",
            WHY_TRACE = "stack trace reference", WHY_LOOP = "crawl loop";

    /**
     * The same patterns, each with the reason it is there. A crawl loop is
     * not among them: its pattern is only made once the loop has been seen
     * and confirmed, by {@link #loopCheck()}.
     */
    public java.util.Map<String, String> skipRules() {
        // A map: the same site given as http and as https comes to the same pattern.
        java.util.Map<String, String> out = new java.util.LinkedHashMap<>();
        for (String typed : auth.avoid) for (String p : avoidPatterns(typed, sites)) out.putIfAbsent(p, WHY_LISTED);
        if (auth.mode != ScanAuth.Mode.NONE && auth.skipLogout)
            for (String site : sites) out.putIfAbsent(logoutGuess(site), WHY_LOGOUT);
        if (auth.skipLoops) out.putIfAbsent(SOURCE_POSITION, WHY_TRACE);
        return out;
    }

    /** The check that confirms a crawl loop before anything is skipped for one, or null when the scan was told not to look. */
    public LoopCheck loopCheck() {
        return auth.skipLoops ? new LoopCheck(this::fetch) : null;
    }

    /** Request a URL as the scanner would, with the scan's headers and session. Null when there was no answer. */
    LoopCheck.Page fetch(String url) {
        try {
            HttpService svc = HttpService.parse(url);
            if (svc == null) return null;
            String rest = url.substring(url.indexOf("://") + 3);
            int slash = rest.indexOf('/');
            String target = slash < 0 ? "/" : rest.substring(slash);
            int hash = target.indexOf('#');
            if (hash >= 0) target = target.substring(0, hash);
            String host = slash < 0 ? rest : rest.substring(0, slash);
            opensuite.core.HttpMessage req = new opensuite.core.HttpMessage(opensuite.core.Bytes.bytes(
                    "GET " + target + " HTTP/1.1\r\nHost: " + host + "\r\nAccept: */*\r\nConnection: close\r\n\r\n"));
            for (ScanAuth.Header h : sent(live))
                if (h.site().isEmpty() || h.site().equals(svc.url())) req.setHeader(h.name(), h.value());
            opensuite.core.HttpClient.Options opt = new opensuite.core.HttpClient.Options();
            opt.followRedirects = false;
            opensuite.core.HttpClient.Result r = new opensuite.core.HttpClient().send(svc, req, opt);
            if (!r.ok() || r.response == null) return null;
            // A target that is failing settles nothing.
            int status = r.response.statusCode();
            if (status >= 500 || status == 429 || status == 408) return null;
            return new LoopCheck.Page(status, r.response.bodyText());
        } catch (RuntimeException e) {
            return null;
        }
    }

    /**
     * An address whose path goes over the same ground again: one folder name
     * three times or more, as in /a/b/a/b/a/b or /a/x/a/y/a. No real site is
     * laid out so; it is what a crawl makes when a page answers every address
     * and its links are then followed from inside themselves, without end.
     * The name must have a letter in it, so numbers that happen to match
     * (/grid/1/1/1) are not taken for it.
     */
    public static final String LOOP =
            "(?i)https?://[^/?#]+(?:/[^/?#]+)*?/((?=[^/?#]*[a-z])[^/?#]+)(?:/[^/?#]+)*?/\\1(?:/[^/?#]+)*?/\\1(?:[/?#].*)?";

    /**
     * An address that ends in a place in a source file, as in
     * /srv/app/routes/files.js:68:18. That is a line of an error report the
     * application printed, which the crawler took for a link; asking for it
     * finds nothing, and where the application answers every address with
     * its front page, each one becomes a new place to crawl from.
     */
    public static final String SOURCE_POSITION = "(?i)https?://[^/?#]+/[^?#]*\\.[a-z][a-z0-9]{0,5}:\\d+(?::\\d+)?\\)?";

    /**
     * Tell the engine's two crawlers whether to pass over links and buttons
     * that log out. The patterns above stop a log out address being requested;
     * this also stops the browser crawl clicking a log out button that sends
     * no request of its own, as a single-page application's does.
     */
    public void applyLogoutAvoidance() {
        boolean on = auth.mode != ScanAuth.Mode.NONE && auth.skipLogout;
        try {
            api.setLogoutAvoidance(on);
            if (on) task.log("Logout rule on: links and buttons that log out are not requested (URLs containing log out, sign out, "
                    + "log off or sign off). To include them, clear Skip logout links and buttons under Application login, Options.");
        } catch (Exception ignored) { /* an engine without the option: the address patterns still hold */ }
    }

    private final List<String> tokensAdded = new ArrayList<>();

    /**
     * Give the engine the names of this application's own form tokens, so it
     * fetches a fresh one before each test of such a form. Taken away again
     * when the scan ends; a name the engine already had is left as it was.
     */
    public void applyFormTokens() {
        if (auth.formTokens.isEmpty()) return;
        List<String> has;
        try { has = api.formTokenNames(); } catch (Exception e) { has = List.of(); }
        for (String name : auth.formTokens) {
            if (name == null || name.isBlank() || has.contains(name.strip())) continue;
            try { api.addFormToken(name.strip()); tokensAdded.add(name.strip()); } catch (Exception ignored) { }
        }
        if (!tokensAdded.isEmpty()) task.log("Form tokens refreshed before each test: " + String.join(", ", tokensAdded)
                + ". Forms that contain them are tested one request at a time, which is slower");
    }

    /**
     * Say in the task's log which pages this scan leaves alone, and warn when
     * a logged-in scan has nothing to stop it ending its own session: no page
     * was put out of scope and no log out link is known for the target.
     */
    public void logLeftAlone() {
        if (auth.sessionMissing) {
            // Said as a failure, so it stands out in the log: the scan was meant to be logged in and is not.
            task.log("The scan could not use the browser's session: no session for this target was observed in proxy traffic. "
                    + "The scan runs unauthenticated. For an authenticated scan, log in to the application in the Open Suite browser and start the scan again.");
            task.setSession("Not logged in: no browser session was found for this target");
        }
        for (String page : auth.avoid) task.log("Out of scope for this scan: " + page);
        if (!auth.avoid.isEmpty()) task.log("These pages are excluded over HTTP and HTTPS, on any port of their host");
        if (auth.skipLoops) task.log("Crawl loop detection is enabled. A URL that repeats a folder name three times (/a/b/a/b/a/b) is requested "
                + "once and compared with the same URL without the repeats: identical responses confirm a loop, and further URLs of that "
                + "form are skipped. Stack trace references (/app/file.js:68:18) are skipped.");
        if (auth.mode == ScanAuth.Mode.NONE || !auth.avoid.isEmpty()) return;
        boolean known = false;
        if (auth.skipLogout) {
            List<java.util.regex.Pattern> guesses = new ArrayList<>();
            for (String site : sites) guesses.add(java.util.regex.Pattern.compile(logoutGuess(site)));
            List<opensuite.core.LogEntry> all = ctx.store().all();
            for (int i = all.size() - 1, looked = 0; i >= 0 && looked < 5000 && !known; i--, looked++) {
                opensuite.core.LogEntry e = all.get(i);
                try {
                    if (e.service() == null || !sites.contains(e.service().url())) continue;
                    String url = e.service().url() + e.request().path();
                    for (java.util.regex.Pattern g : guesses) if (g.matcher(url).matches()) known = true;
                } catch (RuntimeException ignored) { }
            }
        }
        if (!known) task.log("No pages are out of scope for this scan and no logout link has been observed at the target. "
                + "A request to a page that ends the session will log the scan out: exclude such pages under Application login.");
    }

    /** The pattern that guesses a site's log-out links by their names. */
    public static String logoutGuess(String site) {
        return eitherScheme(site) + "/[^?#]*(log[-_]?out|sign[-_]?out|log[-_]?off|sign[-_]?off)[^?#]*(\\?.*)?";
    }

    /**
     * A typed address as patterns: a whole address stands for itself, a path
     * (starting with /) for that path on every site, and * for anything. A
     * query string after the address is covered too.
     */
    public static List<String> avoidPatterns(String typed, java.util.Collection<String> sites) {
        java.util.Set<String> out = new java.util.LinkedHashSet<>();
        String t = typed == null ? "" : typed.trim();
        if (t.isEmpty()) return new ArrayList<>();
        String tail = t.contains("?") ? "" : "(\\?.*)?";
        if (t.matches("(?i)https?://.*")) out.add(eitherScheme(t) + tail);
        else for (String site : sites) out.add(eitherScheme(site) + (t.startsWith("/") ? "" : "/.*") + starred(t) + tail);
        return new ArrayList<>(out);
    }

    /** Text as a pattern for itself, with * standing for anything. */
    private static String starred(String text) {
        StringBuilder re = new StringBuilder();
        String[] parts = text.split("\\*", -1);
        for (int i = 0; i < parts.length; i++) {
            if (i > 0) re.append(".*");
            re.append(regex(parts[i]));
        }
        return re.toString();
    }

    private static final java.util.regex.Pattern ADDRESS = java.util.regex.Pattern.compile("(?i)https?://([^/?#]*)(.*)");

    /**
     * A site or a whole address as a pattern for that page on its host however
     * it is reached: over http or https, on any port, in capitals or not. An
     * application often answers on both schemes, on ports that cannot be told
     * one from the other (8080 and 8443, say), and a page that ends the session
     * does so whichever way it is asked for. Leaving one page too many alone
     * costs a scan little; asking for the wrong one costs it its session.
     */
    static String eitherScheme(String address) {
        java.util.regex.Matcher m = ADDRESS.matcher(address == null ? "" : address.trim());
        if (!m.matches()) return "(?i)" + starred(address == null ? "" : address.trim());
        String host = m.group(1);
        int colon = host.lastIndexOf(':');
        if (colon > 0 && host.substring(colon + 1).matches("\\d+")) host = host.substring(0, colon);
        // This machine has several names, and an application on it answers to them all.
        String name = host.matches("(?i)localhost|127\\.0\\.0\\.1|\\[::1\\]") ? "(localhost|127\\.0\\.0\\.1|\\[::1\\])" : starred(host);
        return "(?i)https?://" + name + "(:\\d+)?" + starred(m.group(2));
    }

    /**
     * Set the scan up: log in when the scan does that itself, hand the headers
     * to the engine, settle on the session checks, and start watching. Throws
     * when the scan was to be logged in and cannot be, because a scan that
     * only looks authenticated is worse than one that stops.
     */
    public void begin() throws Exception {
        if (auth.isEmpty()) return;
        clearStale();
        if (auth.mode == ScanAuth.Mode.CREDENTIALS) {
            loginUrl = auth.loginUrl == null ? "" : auth.loginUrl.trim();
            if (loginUrl.isEmpty()) {
                LoginFlow.Template found = LoginFlow.fromHistory(ctx.store().all(), sites, auth.username, auth.password);
                if (found == null && !services.isEmpty()) found = LoginFlow.detect(services.get(0), "/");
                if (found == null) throw new Exception("no login page was found at the target. Enter the URL of the login "
                        + "page under Application login, or use the browser's session instead");
                loginUrl = found.pageUrl();
            }
            task.log("Logging in as " + auth.username + " at " + loginUrl);
            ctx.taskChanged(task);
            EngineLogin.Result r = EngineLogin.login(api, ctx.settings(), sites, loginUrl, auth.username, auth.password);
            if (!r.ok()) throw new Exception("could not log in: " + r.detail());
            live = new ArrayList<>(r.headers());
            task.log("Login completed as " + auth.username + ": a session was received");
        } else if (auth.mode == ScanAuth.Mode.BROWSER) {
            live = new ArrayList<>(auth.headers);
            if (live.isEmpty()) throw new Exception("the browser's session was chosen but no session header is selected");
        }
        lastSeen = opensuite.core.LogEntry.peekCounter();
        if (auth.mode != ScanAuth.Mode.NONE && auth.monitor) settleChecks();
        apply();
        task.log("Scanning with " + auth.describe() + "; applied to scanner requests only");
        task.setSession("Logged in at scan start");
        if (auth.mode != ScanAuth.Mode.NONE) {
            if (!auth.monitor) {
                task.log("Session monitoring is disabled, as configured: the scan will not detect a session loss");
                task.setSession("Not monitored, as configured");
            } else if (checks.isEmpty()) {
                task.setSession("Not monitored: no session check is set");
                task.log("Session not monitored: no session check is set. The scan cannot detect a session loss and will not pause for one. "
                        + "Add a session check under Application login to monitor the session.");
            } else {
                for (ScanAuth.Check c : checks) task.log("Session check: " + c.request.method() + " " + c.service.url()
                        + c.request.requestTarget() + ". " + c.measured);
                ScanAuth.Verdict v = verdict(live);
                if (v.state() == ScanAuth.State.OUT) {
                    if (auth.mode == ScanAuth.Mode.CREDENTIALS)
                        throw new Exception("the login was not confirmed: after logging in, the session check " + failed + v.detail());
                    lost("The session is not logged in (the check " + failed + v.detail() + ")");
                } else if (v.state() == ScanAuth.State.IN && auth.mode == ScanAuth.Mode.CREDENTIALS) {
                    task.log("Login confirmed by the session check");
                }
            }
        }
        ctx.taskChanged(task);
        if (auth.mode == ScanAuth.Mode.NONE) return;   // nothing to watch: typed headers do not end
        Thread t = new Thread(this::watch, "scan-session-" + task.number);
        t.setDaemon(true);
        watcher = t;
        t.start();
    }

    /**
     * Settle the session checks: each one the user set is proven again on the
     * application with the session the scan now has. One whose text is also
     * there without the session is not used, since it could never report a
     * loss. One whose text is missing now is kept: the session is not logged
     * in, which is the very thing it is there to say. Nothing is worked out
     * in place of a check the user did not set.
     */
    private void settleChecks() {
        for (ScanAuth.Check given : auth.checks) {
            if (given.text.isEmpty()) {
                task.log("Session check not used: " + given.request.method() + " " + given.service.url() + given.request.requestTarget()
                        + ". No logged-in text is set for it.");
                continue;
            }
            ScanAuth.Check c = new ScanAuth.Check(given.service, given.request);
            c.text = given.text;
            ScanAuth.measure(c, live, auth.extra);
            if (c.misleading) {
                task.log("Session check not used: " + c.request.method() + " " + c.service.url() + c.request.requestTarget() + ". " + c.measured);
                continue;
            }
            checks.add(c);
        }
        if (!checks.isEmpty())
            for (ScanAuth.Header h : ScanAuth.unwatched(checks, live))
                task.log("Not monitored: " + h.name() + (h.site().isEmpty() ? "" : " on " + h.site())
                        + ". No session check depends on it, so its expiry alone will not be detected");
    }

    /** All the checks together: out when any is, in when all are, and unknown otherwise. */
    /** The check that last found the session ended, as "GET http://host/path ", or empty. */
    private String failed = "";

    private ScanAuth.Verdict verdict(List<ScanAuth.Header> session) {
        ScanAuth.Verdict unknown = null, in = null;
        for (ScanAuth.Check c : checks) {
            ScanAuth.Verdict v = ScanAuth.run(c, sent(session));
            if (v.state() == ScanAuth.State.OUT) {
                // Which request said so: with several hosts, that names the one to log in to again.
                String target = c.request == null ? "" : c.request.method() + " "
                        + (c.service == null ? "" : c.service.url()) + c.request.path();
                failed = target.isBlank() ? "" : target + " ";
                return v;
            }
            if (v.state() == ScanAuth.State.UNKNOWN) unknown = v; else in = v;
        }
        return unknown != null ? unknown : in;
    }

    /** Everything the scanner sends: the typed headers, then the session's. */
    private List<ScanAuth.Header> sent(List<ScanAuth.Header> session) {
        List<ScanAuth.Header> all = new ArrayList<>(auth.extra);
        all.addAll(session);
        return all;
    }

    /** Take the headers off the engine and stop watching. */
    public void end() {
        ended = true;
        ScanGate.release(api, task.number);
        for (String name : tokensAdded) { try { api.removeFormToken(name); } catch (Exception ignored) { } }
        tokensAdded.clear();
        if (pausedHere || holding) task.setNote("");
        Thread t = watcher;
        if (t != null) t.interrupt();
        synchronized (rules) {
            for (String r : rules) { try { api.removeScanHeader(r); } catch (Exception ignored) { } }
            rules.clear();
        }
        try { api.clearGlobalVar(sessionVar()); } catch (Exception ignored) { }
        try { api.setSpiderAcceptCookies(true); } catch (Exception ignored) { }
    }

    /** Rules left behind by a scan of this number in an engine that outlived it. */
    private void clearStale() throws Exception {
        List<String> known;
        try {
            known = api.scanHeaderRules();
        } catch (Exception e) {
            throw new Exception("the scan engine did not return its header rules (" + e.getMessage() + ")");
        }
        for (String r : known) if (r != null && r.startsWith(rulePrefix)) api.removeScanHeader(r);
        try { api.clearGlobalVar(sessionVar()); } catch (Exception ignored) { /* none was left */ }
    }

    /** The variable Open Suite's add-on reads this scan's session from. */
    private String sessionVar() { return "opensuite.sess." + task.number; }

    /** The values each session header and cookie has had in this scan, the latest last: by site, name and, for a cookie, its name. */
    private final java.util.Map<String, java.util.LinkedHashSet<String>> valuesSeen = new java.util.LinkedHashMap<>();

    /**
     * The session as the add-on reads it: a rule to a line, "c" for a cookie
     * or "h" for a header, the pattern of the addresses it goes to, its name,
     * its value now, then the values it had earlier in the scan. The earlier
     * values let the add-on tell a request recorded under an older session,
     * which is brought up to date, from one whose value a check has changed,
     * which is sent as the check wrote it.
     */
    static String sessionRules(java.util.Collection<ScanAuth.Header> session, java.util.Map<String, java.util.LinkedHashSet<String>> seen) {
        StringBuilder out = new StringBuilder();
        for (ScanAuth.Header h : session) {
            String url = regex(h.site()) + "(/.*)?";
            if (h.name().equalsIgnoreCase("cookie")) {
                for (java.util.Map.Entry<String, String> c : ScanAuth.parseCookies(h.value()).entrySet())
                    rule(out, "c", url, c.getKey(), c.getValue(), seen.computeIfAbsent(h.key() + "\n" + c.getKey(), k -> new java.util.LinkedHashSet<>()));
            } else {
                rule(out, "h", url, h.name(), h.value(), seen.computeIfAbsent(h.key(), k -> new java.util.LinkedHashSet<>()));
            }
        }
        return out.toString();
    }

    private static void rule(StringBuilder out, String kind, String url, String name, String value, java.util.LinkedHashSet<String> seen) {
        seen.remove(value);
        out.append(kind).append(' ').append(enc(url)).append(' ').append(enc(name)).append(' ').append(enc(value));
        // The latest earlier values, as many as a long scan with a short-lived session is likely to need.
        List<String> earlier = new ArrayList<>(seen);
        for (int i = Math.max(0, earlier.size() - 40); i < earlier.size(); i++) out.append(' ').append(enc(earlier.get(i)));
        out.append('\n');
        seen.add(value);
    }

    private static String enc(String s) { return java.net.URLEncoder.encode(s, java.nio.charset.StandardCharsets.UTF_8); }

    /** Give the engine the current headers, replacing the ones it had for this scan. */
    private void apply() throws Exception {
        synchronized (rules) {
            for (String r : rules) { try { api.removeScanHeader(r); } catch (Exception ignored) { } }
            rules.clear();
            boolean cookie = false;
            int n = 0;
            // The add-on puts the session on a request itself, and leaves a header or cookie alone when a
            // check has changed it. An engine without it has the session forced on by header rules, as before.
            boolean byGate = api.gateVersion() >= 2;
            java.util.Map<String, ScanAuth.Header> session = new java.util.LinkedHashMap<>();
            for (ScanAuth.Header h : live)
                for (String site : h.site().isEmpty() ? sites : Set.of(h.site()))
                    session.put(site + "\n" + h.name().toLowerCase(java.util.Locale.ROOT), new ScanAuth.Header(site, h.name(), h.value()));
            if (byGate) {
                api.setGlobalVar(sessionVar(), sessionRules(session.values(), valuesSeen));
                for (ScanAuth.Header h : session.values()) if (h.name().equalsIgnoreCase("cookie")) cookie = true;
            }
            List<ScanAuth.Header> all = new ArrayList<>(auth.extra);
            if (!byGate) all.addAll(live);   // the session's value wins over a typed header of the same name
            java.util.Map<String, ScanAuth.Header> bySiteAndName = new java.util.LinkedHashMap<>();
            for (ScanAuth.Header h : all) {
                for (String site : h.site().isEmpty() ? sites : Set.of(h.site()))
                    bySiteAndName.put(site + "\n" + h.name().toLowerCase(java.util.Locale.ROOT), new ScanAuth.Header(site, h.name(), h.value()));
            }
            // The header rules run after the add-on: a typed header the session also carries is left to the session.
            if (byGate) bySiteAndName.keySet().removeAll(session.keySet());
            for (ScanAuth.Header h : bySiteAndName.values()) {
                String name = rulePrefix + (++n);
                api.addScanHeader(name, regex(h.site()) + "(/.*)?", h.name(), h.value());
                rules.add(name);
                if (h.name().equalsIgnoreCase("cookie")) cookie = true;
            }
            Set<String> carried = new java.util.HashSet<>();
            for (ScanAuth.Header h : live) carried.add(h.name().toLowerCase(java.util.Locale.ROOT));
            task.setSessionHeaders(carried);
            // The crawler would otherwise put the cookies it is sent over the session's.
            if (cookie) api.setSpiderAcceptCookies(false);
        }
    }

    private void watch() {
        while (!ended && !task.cancelled() && task.state() != ScanTask.State.FINISHED) {
            try {
                // A scan paused by hand is sending nothing, so its session is looked at less often.
                boolean idle = pausedHere || (task.state() == ScanTask.State.PAUSED && !holding);
                Thread.sleep(idle ? WAITING_MS : failures > 0 || holding ? RECHECK_MS : EVERY_MS);
            } catch (InterruptedException e) {
                return;
            }
            if (ended || task.cancelled() || task.state() == ScanTask.State.FINISHED) return;
            try {
                step();
            } catch (Exception e) {
                Debug.log("scan session watch failed: " + e);
            }
        }
    }

    /** One look at the browser and one round of session checks. */
    void step() throws Exception {
        if (auth.mode == ScanAuth.Mode.BROWSER && auth.follow) {
            int upTo = opensuite.core.LogEntry.peekCounter();
            if (upTo > lastSeen) {
                List<ScanAuth.Header> newer = ScanAuth.capture(ctx.store().all(), sites, lastSeen);
                lastSeen = upTo;
                List<ScanAuth.Header> merged = ScanAuth.merged(live, newer, auth.dropCookies);
                if (merged != null) {
                    // While waiting for a login, only a session that works is taken up.
                    if (checks.isEmpty() || !pausedHere || verdict(merged).loggedIn()) {
                        live = merged;
                        apply();
                        if (!pausedHere) task.log("Updated session detected in the browser; the scanner now uses it");
                    }
                }
            }
        }
        if (checks.isEmpty()) return;
        // Resumed by hand while waiting: the user has taken over, so start counting afresh.
        if (pausedHere && task.state() == ScanTask.State.RUNNING) { pausedHere = false; failures = 0; task.setNote(""); }
        if (holding && task.state() == ScanTask.State.RUNNING) holding = false;   // resumed by hand
        ScanAuth.Verdict v = verdict(live);
        if (v.state() == ScanAuth.State.IN) {
            task.setSession("Logged in, checked at " + clock());
            release();
            failures = 0;
            logins = 0;
            saidUnknown = false;
            if (pausedHere && task.state() == ScanTask.State.PAUSED) {
                pausedHere = false;
                task.setNote("");
                task.setState(ScanTask.State.RUNNING);
                task.log("Session restored: scan resumed");
                ctx.alert("scanner", "Scan " + task.number + " has a valid session again and has resumed");
                ctx.taskChanged(task);
            } else if (pausedHere) {
                pausedHere = false;
            }
            if (lostAt != 0) {
                task.log("Session restored. Requests sent by the scanner in the previous "
                        + Math.max(1, (System.currentTimeMillis() - lostAt) / 1000) + " seconds were unauthenticated");
                lostAt = 0;
                ctx.taskChanged(task);
            }
            return;
        }
        if (v.state() == ScanAuth.State.UNKNOWN) {
            // Not a lost session: say so once and keep trying.
            release();
            failures = 0;
            if (!saidUnknown && !pausedHere) {
                saidUnknown = true;
                task.log("The session check " + v.detail() + ". This is not treated as a session loss; checking again");
            }
            return;
        }
        if (pausedHere || lostAt != 0) return;        // already known to be lost
        if (task.state() == ScanTask.State.PAUSED && !holding) return;   // paused by the user: say nothing
        if (++failures < 2) {
            // One bad answer may be a slip: ask again straight away, and send nothing meanwhile.
            hold();
            return;
        }
        failures = 0;
        if (auth.mode == ScanAuth.Mode.CREDENTIALS && auth.relogin && logins < 3) {
            logins++;
            task.log("The session has ended (the check " + failed + v.detail() + "): logging in again");
            task.setSession("Ended at " + clock() + ", logging in again");
            ctx.taskChanged(task);
            EngineLogin.Result r = EngineLogin.login(api, ctx.settings(), sites, loginUrl, auth.username, auth.password);
            if (r.ok()) {
                live = new ArrayList<>(r.headers());
                apply();
                // A login counts only when the marked text is back; a failing target leaves it open for the next look.
                ScanAuth.Verdict now = verdict(live);
                if (now.state() != ScanAuth.State.OUT) {
                    task.log(now.state() == ScanAuth.State.IN ? "Logged in again as " + auth.username + ": confirmed by the session check"
                            : "Logged in again as " + auth.username + "; the session check " + now.detail());
                    release();
                    ctx.taskChanged(task);
                    return;
                }
                task.log("Logging in again was not confirmed: the check " + failed + now.detail());
            } else {
                task.log("Logging in again failed: " + r.detail());
            }
            if (logins < 3) return;
        }
        lost("The session has ended (the check " + failed + v.detail() + ")");
    }

    /**
     * Stop the scanner sending while the session is in doubt, so that what
     * would go out logged out is not sent at all. Not done for a scan that
     * was told never to pause.
     */
    private void hold() {
        if (holding || !auth.pauseOnLoss || task.state() != ScanTask.State.RUNNING) return;
        holding = true;
        // The engine's own pause lets tests under way go on sending; the gate stops them at once.
        ScanGate.hold(api, task.number, sites);
        task.setNote("Checking the session");
        task.setState(ScanTask.State.PAUSED);
        ctx.taskChanged(task);
    }

    private void release() {
        if (!holding) return;
        holding = false;
        task.setNote("");
        ScanGate.release(api, task.number);
        if (task.state() == ScanTask.State.PAUSED) task.setState(ScanTask.State.RUNNING);
        ctx.taskChanged(task);
    }

    private static String clock() {
        return java.time.LocalTime.now().format(java.time.format.DateTimeFormatter.ofPattern("HH:mm:ss"));
    }

    /** The session is gone and the scan cannot get another by itself. */
    private void lost(String why) {
        task.setSession("Ended at " + clock() + (auth.pauseOnLoss ? ", waiting for a new login" : ", the scan continues unauthenticated"));
        holding = false;   // the hold becomes the wait, or is let go just below
        if (!auth.pauseOnLoss) {
            ScanGate.release(api, task.number);
            lostAt = System.currentTimeMillis();
            String what = why + ". The scan continues, as configured, and its requests are now unauthenticated"
                    + (auth.mode == ScanAuth.Mode.BROWSER && auth.follow ? "; log in again in the browser and the scan will use the new session." : ".");
            task.log(what);
            ctx.alert("scanner", "Scan " + task.number + ": " + what);
            ctx.taskChanged(task);
            return;
        }
        pausedHere = true;
        task.setNote("Waiting for login");
        task.setState(ScanTask.State.PAUSED);
        String what = auth.mode == ScanAuth.Mode.CREDENTIALS
                ? why + (auth.relogin ? " and the repeated login was unsuccessful" : "") + ". Paused: resume the scan once the login works."
                : why + ". Paused: log in again in the browser and the scan resumes automatically.";
        task.log(what);
        ctx.alert("scanner", "Scan " + task.number + ": " + what);
        ctx.taskChanged(task);
    }

    /** A literal as a regular expression. */
    static String regex(String literal) {
        StringBuilder sb = new StringBuilder();
        for (char c : literal.toCharArray()) {
            if (!Character.isLetterOrDigit(c) && c != '/' && c != ':' && c != '-' && c != '_') sb.append('\\');
            sb.append(c);
        }
        return sb.toString();
    }
}