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.

10.9 KB
Raw Blame
package opensuite.core;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * What an audit has done, address by address: which of the scan's rules the
 * engine has started on each address it is auditing.
 *
 * <p>The engine takes one rule across every address, then the next, and says
 * each time it starts a rule on an address. Those starts are kept here, with
 * the engine's own list of the scan's rules and how each stands. From the two
 * an address can be given a true figure, "12 of 47": 47 rules apply to it and
 * the engine has started 12 of them on it.
 *
 * <p>What counts. A rule the engine runs once for a whole site is not a rule
 * for an address and is left out. So is a rule the engine skipped. A rule is
 * counted from the moment the engine starts it on the address: the engine
 * gives no word when one rule ends on one address. Where the first starts of
 * a rule were not heard, that rule is counted for an address only once the
 * engine reports the whole rule complete.
 */
public final class RuleProgress {

    /** One of a scan's rules on one site, as the engine reports it. State is C, R or P: complete, running, pending. */
    public record Rule(String site, int id, String name, boolean perSite, char state, boolean skipped, boolean missed) {}

    /** Rules started on an address out of those that apply to it. */
    public record Count(int run, int total) implements Comparable<Count> {
        public boolean done() { return total > 0 && run >= total; }
        @Override public int compareTo(Count o) {
            int c = Long.compare((long) run * Math.max(1, o.total), (long) o.run * Math.max(1, total));
            return c != 0 ? c : Integer.compare(total, o.total);
        }
        /** How far the address is through the checks that apply to it, 0 to 100. */
        public int percent() { return total <= 0 ? 0 : (int) Math.min(100, (long) run * 100 / total); }
        @Override public String toString() { return run + " of " + total; }
    }

    private final List<String> addresses = new ArrayList<>();
    private final Map<String, BitSet> started = new HashMap<>();
    private final List<String> names = new ArrayList<>();
    private final Map<String, Integer> nameAt = new HashMap<>();
    private final Map<String, List<Rule>> bySite = new LinkedHashMap<>();
    private int version;
    private int[] totals;          // {addresses, addresses with every rule run}, for the version below
    private int totalsVersion = -1;

    /** The site of an address, written one way: scheme, host and port, the port always given. */
    public static String site(String address) {
        if (address == null) return "";
        int s = address.indexOf("://");
        if (s < 0) return address.toLowerCase(java.util.Locale.ROOT);
        String scheme = address.substring(0, s).toLowerCase(java.util.Locale.ROOT);
        int end = address.indexOf('/', s + 3);
        String host = (end < 0 ? address.substring(s + 3) : address.substring(s + 3, end)).toLowerCase(java.util.Locale.ROOT);
        int at = host.lastIndexOf('@');
        if (at >= 0) host = host.substring(at + 1);
        boolean hasPort = host.lastIndexOf(':') > host.lastIndexOf(']');
        return scheme + "://" + host + (hasPort ? "" : scheme.equals("https") ? ":443" : ":80");
    }

    /** An address written one way: its site without a usual port, and its path without query or fragment. */
    public static String key(String url) {
        if (url == null) return "";
        int cut = url.length(), q = url.indexOf('?'), h = url.indexOf('#');
        if (q >= 0) cut = q;
        if (h >= 0 && h < cut) cut = h;
        String u = url.substring(0, cut);
        int s = u.indexOf("://");
        if (s < 0) return u;
        int end = u.indexOf('/', s + 3);
        String site = site(u), path = end < 0 ? "/" : u.substring(end);
        if (site.startsWith("http://") && site.endsWith(":80")) site = site.substring(0, site.length() - 3);
        else if (site.startsWith("https://") && site.endsWith(":443")) site = site.substring(0, site.length() - 4);
        return site + path;
    }

    /** The engine has started this rule on this address. */
    public synchronized void started(String rule, String address) {
        if (rule == null || address == null) return;
        String key = key(address);
        BitSet on = started.get(key);
        if (on == null) { on = new BitSet(); started.put(key, on); addresses.add(key); version++; }
        Integer n = nameAt.get(rule);
        if (n == null) { n = names.size(); names.add(rule); nameAt.put(rule, n); }
        if (!on.get(n)) { on.set(n); version++; }
    }

    /** The scan's rules as the engine has them now. The rules of each site named replace what was held for it. */
    public synchronized void rules(List<Rule> all) {
        Map<String, List<Rule>> fresh = new LinkedHashMap<>();
        for (Rule r : all) fresh.computeIfAbsent(site(r.site()), k -> new ArrayList<>()).add(r);
        for (Map.Entry<String, List<Rule>> e : fresh.entrySet()) {
            if (e.getValue().equals(bySite.get(e.getKey()))) continue;
            bySite.put(e.getKey(), e.getValue());
            version++;
        }
    }

    /** Whether anything is held: an audit that reported its rule starts. */
    public synchronized boolean known() { return !addresses.isEmpty(); }

    /** Changes each time anything here changes, so a view knows when to draw again. */
    public synchronized int version() { return version; }

    /** The addresses the engine has started a rule on, in the order it first did, from the given one on. */
    public synchronized List<String> addresses(int from) {
        return from >= addresses.size() ? List.of() : new ArrayList<>(addresses.subList(Math.max(0, from), addresses.size()));
    }

    private boolean counts(Rule r) { return !r.perSite() && !r.skipped(); }

    private boolean ran(Rule r, BitSet on) {
        Integer n = nameAt.get(r.name());
        return (n != null && on != null && on.get(n)) || (r.missed() && r.state() == 'C');
    }

    /** The figure for an address, or null where the rules of its site are not known. */
    public synchronized Count count(String address) {
        String key = key(address);
        List<Rule> rules = bySite.get(site(key));
        if (rules == null) return null;
        BitSet on = started.get(key);
        int run = 0, total = 0;
        for (Rule r : rules) {
            if (!counts(r)) continue;
            total++;
            if (ran(r, on)) run++;
        }
        return new Count(run, total);
    }

    /** The names of the rules that apply to an address and have not been started on it, in the engine's order. */
    public synchronized List<String> waiting(String address) {
        String key = key(address);
        List<Rule> rules = bySite.get(site(key));
        List<String> out = new ArrayList<>();
        if (rules == null) return out;
        BitSet on = started.get(key);
        for (Rule r : rules) if (counts(r) && !ran(r, on)) out.add(r.name());
        return out;
    }

    /** The names of the rules the engine skipped on the site of an address: they are in no address's figure. */
    public synchronized List<String> skipped(String address) {
        List<Rule> rules = bySite.get(site(key(address)));
        List<String> out = new ArrayList<>();
        if (rules != null) for (Rule r : rules) if (r.skipped() && !r.perSite()) out.add(r.name());
        return out;
    }

    /** How many addresses there are, and on how many of them every rule has been started. */
    public synchronized int[] totals() {
        if (totalsVersion != version) {
            int done = 0;
            for (String a : addresses) { Count c = count(a); if (c != null && c.done()) done++; }
            totals = new int[] {addresses.size(), done};
            totalsVersion = version;
        }
        return totals.clone();
    }

    // ------------------------------------------------------ kept in a project

    /** Everything here as text, for a project file; empty when nothing is held. */
    public synchronized String save() {
        if (addresses.isEmpty()) return "";
        StringBuilder out = new StringBuilder();
        for (List<Rule> rules : bySite.values())
            for (Rule r : rules)
                out.append("R\t").append(r.site()).append('\t').append(r.id()).append('\t').append(r.perSite() ? 'H' : 'A').append('\t')
                   .append(r.state()).append('\t').append(r.skipped() ? '1' : '0').append('\t').append(r.missed() ? '1' : '0')
                   .append('\t').append(r.name()).append('\n');
        for (String n : names) out.append("N\t").append(n).append('\n');
        for (String a : addresses) {
            out.append("A\t").append(a).append('\t');
            BitSet on = started.get(a);
            boolean first = true;
            for (int i = on.nextSetBit(0); i >= 0; i = on.nextSetBit(i + 1)) {
                if (!first) out.append(',');
                out.append(i);
                first = false;
            }
            out.append('\n');
        }
        return out.toString();
    }

    /** One rule from a line of {@link #save} without its leading letter, as the engine's add-on also writes them; null if it is not one. */
    public static Rule rule(String line) {
        String[] f = line.split("\t", 7);
        if (f.length < 7 || f[3].isEmpty()) return null;
        try {
            return new Rule(f[0], Integer.parseInt(f[1].trim()), f[6], f[2].equals("H"), f[3].charAt(0), f[4].equals("1"), f[5].equals("1"));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /** Take in what {@link #save} wrote. Lines that cannot be read are left out. */
    public synchronized void load(String saved) {
        if (saved == null || saved.isEmpty()) return;
        List<Rule> rules = new ArrayList<>();
        List<String> theirNames = new ArrayList<>();
        for (String line : saved.split("\n")) {
            if (line.startsWith("R\t")) {
                Rule r = rule(line.substring(2));
                if (r != null) rules.add(r);
            } else if (line.startsWith("N\t")) {
                theirNames.add(line.substring(2));
            } else if (line.startsWith("A\t")) {
                String[] f = line.split("\t", 3);
                if (f.length < 2) continue;
                boolean any = false;
                if (f.length == 3) for (String n : f[2].split(",")) {
                    try {
                        int i = Integer.parseInt(n.trim());
                        if (i >= 0 && i < theirNames.size()) { started(theirNames.get(i), f[1]); any = true; }
                    } catch (NumberFormatException e) {
                        // left out
                    }
                }
                if (!any) { String key = key(f[1]); if (!started.containsKey(key)) { started.put(key, new BitSet()); addresses.add(key); version++; } }
            }
        }
        rules(rules);
    }
}