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.

12.3 KB
Raw Blame
package opensuite.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/** A scan task shown on the dashboard: a crawl/audit, live passive audit, or active scan. */
public class ScanTask {
    public enum Type { LIVE_PASSIVE, LIVE_ACTIVE, AUDIT }
    public enum State { RUNNING, PAUSED, FINISHED }

    private static final AtomicInteger SEQ = new AtomicInteger(0);

    public final int number;
    private volatile Type type;
    private volatile String title;
    private volatile String configuration;
    private volatile String scope = "";
    private volatile State state = State.RUNNING;

    private final AtomicInteger high = new AtomicInteger();
    private final AtomicInteger medium = new AtomicInteger();
    private final AtomicInteger low = new AtomicInteger();
    private final AtomicInteger info = new AtomicInteger();

    private volatile int requests;
    private volatile int itemsTotal;
    private volatile int itemsDone;
    private volatile int discoveredLocations;  // URLs the crawl found (real, from ZAP spider)
    private volatile int auditItemsTotal;      // active-scan rules enabled (real, from ZAP)
    private volatile long startedAt = System.currentTimeMillis();
    private volatile byte[] lastShot;   // latest rendered-page screenshot (crawl tasks)
    private final List<String> log = new CopyOnWriteArrayList<>();
    private final List<Long> logAt = new CopyOnWriteArrayList<>();   // when each line was logged, in step with log

    public ScanTask(Type type, String title, String configuration) {
        this.number = SEQ.incrementAndGet();
        this.type = type;
        this.title = title;
        this.configuration = configuration;
    }

    private ScanTask(int number, Type type, String title, String configuration) {
        this.number = number;
        this.type = type;
        this.title = title;
        this.configuration = configuration;
    }

    public static void resetCounter() { SEQ.set(0); }

    /** Continue numbering after {@code v}, so a restored project's tasks keep their numbers. */
    public static void setCounter(int v) { SEQ.accumulateAndGet(v, Math::max); }

    /**
     * Everything about a task worth keeping in a project file. A task is live
     * state driven by a scan loop, so the file holds this plain copy instead;
     * a task restored from it is always finished, since nothing is driving it.
     */
    public record Snapshot(int number, Type type, String title, String configuration, String scope,
                           int high, int medium, int low, int info,
                           int requests, int itemsTotal, int itemsDone,
                           int discoveredLocations, int auditItemsTotal,
                           long startedAt, byte[] lastShot, List<String> log, long[] logAt, String rules, String sites)
            implements java.io.Serializable {}

    public Snapshot snapshot() {
        return new Snapshot(number, type, title, configuration, scope,
                high.get(), medium.get(), low.get(), info.get(),
                requests, itemsTotal, itemsDone, discoveredLocations, auditItemsTotal,
                startedAt, lastShot, logLines(), logTimes(), rules.save(), sites.save());
    }

    private synchronized long[] logTimes() {
        long[] at = new long[logAt.size()];
        for (int i = 0; i < at.length; i++) at[i] = logAt.get(i);
        return at;
    }

    public static ScanTask fromSnapshot(Snapshot s) {
        ScanTask t = new ScanTask(s.number(), s.type(), s.title(), s.configuration());
        t.scope = s.scope() == null ? "" : s.scope();
        t.state = State.FINISHED;
        t.setCounts(s.high(), s.medium(), s.low(), s.info());
        t.requests = s.requests();
        t.itemsTotal = s.itemsTotal();
        t.itemsDone = s.itemsDone();
        t.discoveredLocations = s.discoveredLocations();
        t.auditItemsTotal = s.auditItemsTotal();
        t.startedAt = s.startedAt();
        t.lastShot = s.lastShot();
        if (s.log() != null) {
            // A project saved before lines carried their own times has none: those lines take the task's start.
            long[] at = s.logAt();
            boolean timed = at != null && at.length == s.log().size();
            for (int i = 0; i < s.log().size(); i++) {
                t.log.add(s.log().get(i));
                t.logAt.add(timed ? at[i] : s.startedAt());
            }
        }
        t.sites.load(s.sites());   // absent from a project saved before a scan kept its sites
        t.rules.load(s.rules());   // absent from a project saved before audits kept this
        setCounter(s.number());
        return t;
    }

    public Type type()            { return type; }
    /** A crawl that goes on to audit what it found becomes an audit, as the one task. */
    public void setType(Type t)   { this.type = t; }
    public String title()         { return title; }
    public void setTitle(String t){ this.title = t; }
    public String configuration() { return configuration; }
    public String scope()         { return scope; }
    public void setScope(String s){ this.scope = s == null ? "" : s; }
    public State state()          { return state; }
    public void setState(State s) { this.state = s; }

    // A cancelled task is one the user deleted or stopped: the scan loop driving
    // it checks this, stops the engine's scan, and exits so nothing keeps running
    // (and consuming memory) in the background after the task is gone.
    private volatile boolean cancelled;
    private volatile String note = "";
    /** Why a paused task is paused when it was not the user who paused it, or empty. */
    public String note()          { return note; }
    public void setNote(String n) { this.note = n == null ? "" : n; }
    private volatile String caution = "", cautionDetail = "";
    /** A part of the scan that did not run, in a few words for the task's card, or empty. */
    public String caution()       { return caution; }
    /** The same in full: what did not run and why. */
    public String cautionDetail() { return cautionDetail; }
    public void setCaution(String shortly, String inFull) {
        this.caution = shortly == null ? "" : shortly;
        this.cautionDetail = inFull == null ? "" : inFull;
    }
    public boolean cancelled()    { return cancelled; }
    public void cancel()          { this.cancelled = true; }

    public int high()   { return high.get(); }
    public int medium() { return medium.get(); }
    public int low()    { return low.get(); }
    public int info()   { return info.get(); }

    /** Set the issue counts directly, for a task that reflects a shared set. */
    public void setCounts(int h, int m, int l, int i) {
        high.set(h); medium.set(m); low.set(l); info.set(i);
    }

    public void countIssue(Issue.Severity sev) {
        switch (sev) {
            case HIGH -> high.incrementAndGet();
            case MEDIUM -> medium.incrementAndGet();
            case LOW -> low.incrementAndGet();
            case INFORMATION -> info.incrementAndGet();
        }
    }

    public int requests()          { return requests; }
    public void addRequests(int n) { requests += n; }
    public int itemsTotal()        { return itemsTotal; }
    public void setItemsTotal(int n){ itemsTotal = n; }
    public int itemsDone()         { return itemsDone; }
    public void setItemsDone(int n){ itemsDone = n; }
    public int discoveredLocations()        { return discoveredLocations; }
    public void setDiscoveredLocations(int n){ discoveredLocations = n; }
    public int auditItemsTotal()            { return auditItemsTotal; }
    public void setAuditItemsTotal(int n)   { auditItemsTotal = n; }
    public long startedAt()        { return startedAt; }
    public byte[] lastShot()           { return lastShot; }
    public void setLastShot(byte[] b)  { lastShot = b; }

    public double progress() {
        if (type == Type.LIVE_PASSIVE || type == Type.LIVE_ACTIVE) return -1;  // continuous
        return itemsTotal <= 0 ? 0 : Math.min(1.0, (double) itemsDone / itemsTotal);
    }

    public synchronized void log(String line) {
        log.add(line);
        logAt.add(System.currentTimeMillis());
        if (log.size() > 500) { log.remove(0); logAt.remove(0); }
    }
    public List<String> logLines() { return new ArrayList<>(log); }

    /** One line of the task's log with the time it was logged. */
    public record Event(long at, String line) {}

    public synchronized List<Event> events() {
        List<Event> out = new ArrayList<>(log.size());
        for (int i = 0; i < log.size(); i++) out.add(new Event(i < logAt.size() ? logAt.get(i) : startedAt, log.get(i)));
        return out;
    }

    private volatile String session = "";

    /** What is known of the scan's login just now, in a few words; empty for a scan that does not log in. */
    public String session() { return session; }
    public void setSession(String s) { session = s == null ? "" : s; }

    private volatile java.util.Set<String> sessionHeaders = java.util.Set.of();

    /** The names, in small letters, of the headers that carry this scan's session; none for a scan that does not log in. */
    public java.util.Set<String> sessionHeaders() { return sessionHeaders; }
    public void setSessionHeaders(java.util.Set<String> names) { sessionHeaders = names == null ? java.util.Set.of() : java.util.Set.copyOf(names); }

    private volatile java.util.List<java.util.regex.Pattern> reach = java.util.List.of();
    private final java.util.List<java.util.regex.Pattern> barred = new java.util.concurrent.CopyOnWriteArrayList<>();

    /**
     * The limits this scan was given, as the patterns handed to the engine:
     * the addresses it may request, and those among them it must not.
     */
    public void setReach(java.util.Collection<String> include, java.util.Collection<String> exclude) {
        java.util.List<java.util.regex.Pattern> in = new java.util.ArrayList<>();
        for (String re : include) try { in.add(java.util.regex.Pattern.compile(re)); } catch (RuntimeException ignored) { }
        reach = java.util.List.copyOf(in);
        barred.clear();
        for (String re : exclude) bar(re);
    }

    /** One more pattern the scan must not request, added while it runs. */
    public void bar(String regex) {
        try { barred.add(java.util.regex.Pattern.compile(regex)); } catch (RuntimeException ignored) { }
    }

    /**
     * Whether this scan refuses to request an address: it is outside the
     * addresses the scan may request, or one it was told to leave alone. The
     * same patterns the engine holds are asked, the same way: against the
     * address without its fragment, with and without its query. False for
     * anything that is not an http address, and while the limits are not yet
     * known.
     */
    public boolean refuses(String url) {
        java.util.List<java.util.regex.Pattern> in = reach;
        if (url == null || in.isEmpty() || !url.regionMatches(true, 0, "http", 0, 4)) return false;
        int hash = url.indexOf('#');
        String whole = hash < 0 ? url : url.substring(0, hash);
        int q = whole.indexOf('?');
        String bare = q < 0 ? whole : whole.substring(0, q);
        boolean allowed = false;
        for (java.util.regex.Pattern p : in) if (p.matcher(bare).matches() || p.matcher(whole).matches()) { allowed = true; break; }
        if (!allowed) return true;
        for (java.util.regex.Pattern p : barred) if (p.matcher(bare).matches() || p.matcher(whole).matches()) return true;
        return false;
    }

    private volatile String waiting = "";

    /** Why a running scan is sending nothing just now, in a few words; empty when it is not held up. */
    private final SiteProgress sites = new SiteProgress();
    /** The sites this scan covers and how far each has got; empty for a task that is not a scan of sites. */
    public SiteProgress sites() { return sites; }
    private final RuleProgress rules = new RuleProgress();

    /** Which rules the audit has started on which addresses; empty for a task that is not an audit. */
    public RuleProgress rules() { return rules; }

    public String waiting() { return waiting; }
    public void setWaiting(String w) { waiting = w == null ? "" : w; }

    public String stateLabel() {
        return switch (state) { case RUNNING -> "Running"; case PAUSED -> "Paused"; case FINISHED -> "Finished"; };
    }
}