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.

5.9 KB
Raw Blame
package opensuite.gate;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * What the gate decides, apart from the engine it sits in: whether a hold
 * names a request, and what session a request is sent with. Nothing here
 * touches the engine, so it is tested with the rest of Open Suite, against
 * the very text Open Suite writes for it.
 */
public final class GateRules {

    private GateRules() {}

    /** Whether a hold's parts name this site and its time has not passed. */
    public static boolean holds(String[] parts, String site, long now) {
        try {
            if (Long.parseLong(parts[0]) <= now) return false;
        } catch (NumberFormatException e) {
            return false;
        }
        for (int i = 1; i < parts.length; i++) if (parts[i].equalsIgnoreCase(site)) return true;
        return false;
    }

    /** The scans a hold is for: "S3" a crawl, "A5" an audit, "J" the browser crawl, "N" none at present. Sites have a colon and are not these. */
    public static List<String> scansOf(String[] parts) {
        List<String> out = new ArrayList<>();
        for (int i = 1; i < parts.length; i++) if (parts[i].matches("[SA]\\d+|J|N")) out.add(parts[i]);
        return out;
    }

    /** A crawl's requests are sent on threads the crawler names after the crawl's number. */
    public static boolean crawlThread(String thread, String id) {
        return thread != null && (thread.startsWith("ZAP-SpiderThreadPool-" + id + "-") || thread.equals("ZAP-SpiderInitThread-" + id));
    }

    /** One header or cookie of a session: where it goes, its value now and the values it had before. */
    public record Rule(boolean cookie, Pattern url, String name, String value, List<String> past) {
        public boolean known(String v) { return v.equals(value) || past.contains(v); }
    }

    /** Rules as Open Suite writes them: "c|h urlPattern name value past...", a rule to a line, each part URL-encoded. */
    public static List<Rule> parse(String text) {
        List<Rule> out = new ArrayList<>();
        for (String line : text.split("\n")) {
            String[] f = line.trim().split(" ");
            if (f.length < 4) continue;
            try {
                List<String> past = new ArrayList<>();
                for (int i = 4; i < f.length; i++) past.add(dec(f[i]));
                out.add(new Rule(f[0].equals("c"), Pattern.compile(dec(f[1])), dec(f[2]), dec(f[3]), past));
            } catch (RuntimeException e) {
                // a rule that cannot be read is left out; the others stand
            }
        }
        return out;
    }

    private static String dec(String s) { return URLDecoder.decode(s, StandardCharsets.UTF_8); }

    /** The value to send for a session header, or null to leave the request's own: a check has changed it. */
    public static String headerToSend(String now, Rule r, boolean audit) {
        if (audit && now != null && !r.known(now)) return null;
        return r.value();
    }

    /**
     * The Cookie header to send. A crawler's request carries the session's
     * cookies and no others, as it did under the header rules. An auditor's
     * request keeps its own cookies, takes the session's value for each
     * session cookie it carries unchanged or lacks, and keeps the value of
     * one a check has changed.
     */
    public static String cookiesToSend(String now, List<Rule> rules, boolean audit) {
        Map<String, String> jar = new LinkedHashMap<>();
        if (audit && now != null) {
            for (String part : now.split(";")) {
                String p = part.trim();
                if (p.isEmpty()) continue;
                int eq = p.indexOf('=');
                if (eq < 0) jar.put(p, null); else jar.put(p.substring(0, eq).trim(), p.substring(eq + 1).trim());
            }
        }
        for (Rule r : rules) {
            if (!r.cookie()) continue;
            String has = jar.get(r.name());
            if (audit && has != null && !r.known(has)) continue;   // the check's own value goes through
            jar.put(r.name(), r.value());
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> c : jar.entrySet()) {
            if (sb.length() > 0) sb.append("; ");
            sb.append(c.getKey());
            if (c.getValue() != null) sb.append('=').append(c.getValue());
        }
        return sb.toString();
    }

    // ------------------------------------------------------ alerts since

    /**
     * The alerts newer than one already had: their numbers in rising order,
     * the last number looked at, and the highest number there is. Where the
     * caller wants only one site's alerts the others are passed over, and
     * count as looked at. No more than {@code most} are named at once: the
     * caller asks again from {@code last}.
     */
    public record Newer(List<Integer> ids, int last, int top) {
        public String idList() {
            StringBuilder b = new StringBuilder();
            for (int id : ids) { if (b.length() > 0) b.append(','); b.append(id); }
            return b.toString();
        }
    }

    public static Newer newer(java.util.Collection<Integer> all, int after, int most, java.util.function.IntPredicate wanted) {
        List<Integer> sorted = new ArrayList<>();
        int top = -1;
        for (Integer id : all) {
            if (id == null) continue;
            if (id > top) top = id;
            if (id > after) sorted.add(id);
        }
        java.util.Collections.sort(sorted);
        List<Integer> ids = new ArrayList<>();
        int last = after;
        for (int id : sorted) {
            if (most > 0 && ids.size() >= most) break;
            if (wanted == null || wanted.test(id)) ids.add(id);
            last = id;
        }
        return new Newer(ids, last, top);
    }
}