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.

7.3 KB
Raw Blame
package opensuite.engine;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Tells a crawl loop from a real part of an application, by asking.
 *
 * <p>A crawl loop is what a crawler makes when an application answers any
 * URL with a page and the links on that page are then followed from inside
 * themselves: /assets/public/assets/public/assets/public and on without end.
 * Its mark is a folder name that comes up three times in one path. But a real
 * application can be laid out so too (/users/5/users/7/users/9), and a rule
 * that went by the shape of the URL alone would skip those pages unseen.
 *
 * <p>So the shape only raises the question. The first URL found with a name
 * three times in its path is requested, and so is the same URL with the
 * repeats taken out. Where both come back as the same page, the repeats add
 * nothing: URLs that repeat that name are a loop, and are excluded from then
 * on. Where they differ, the application means something by them and they
 * are kept. A URL that cannot be fetched decides nothing, and nothing is
 * excluded on its account.
 */
public final class LoopCheck {

    /** One answer: its status code and body. */
    public record Page(int status, String body) {}

    /** What was settled about one repeated folder name on one site. */
    public record Finding(String site, String name, boolean loop, String sample, String shorter, String pattern) {}

    /** A path with one folder name in it three times; the name must hold a letter, so numbers that happen to match are not taken for it. */
    private static final Pattern SHAPE = Pattern.compile(
            "(?i)https?://[^/?#]+(?:/[^/?#]+)*?/((?=[^/?#]*[a-z])[^/?#]+)(?:/[^/?#]+)*?/\\1(?:/[^/?#]+)*?/\\1(?:[/?#].*)?");

    private static final int TRIES = 3;

    private final Function<String, Page> fetch;
    private final Map<String, Boolean> settled = new LinkedHashMap<>();   // site, a line break, the name: loop or not
    private final Map<String, Integer> tried = new HashMap<>();
    private final Map<String, Pattern> loops = new LinkedHashMap<>();
    private final Set<String> looked = new HashSet<>();

    /** @param fetch requests a URL as the scan would, with its session, and gives the answer, or null when there was none */
    public LoopCheck(Function<String, Page> fetch) { this.fetch = fetch; }

    /** The folder name that comes up three times in this URL's path, in lower case, or null. */
    public static String repeatedName(String url) {
        Matcher m = SHAPE.matcher(url == null ? "" : url);
        return m.matches() ? m.group(1).toLowerCase(Locale.ROOT) : null;
    }

    /**
     * The URL with the repeats taken out: its path up to the first time the
     * name comes up, then what follows the last time. /x/a/b/a/c/a/d becomes
     * /x/a/d. The query string is kept.
     */
    public static String shorter(String url, String name) {
        int scheme = url.indexOf("://");
        int pathAt = url.indexOf('/', scheme < 0 ? 0 : scheme + 3);
        if (pathAt < 0) return url;
        int end = url.length();
        for (char stop : new char[]{'?', '#'}) { int i = url.indexOf(stop, pathAt); if (i >= 0 && i < end) end = i; }
        String[] parts = url.substring(pathAt + 1, end).split("/", -1);
        int first = -1, last = -1;
        for (int i = 0; i < parts.length; i++)
            if (parts[i].equalsIgnoreCase(name)) { if (first < 0) first = i; last = i; }
        if (first < 0 || first == last) return url;
        StringBuilder path = new StringBuilder();
        for (int i = 0; i <= first; i++) path.append('/').append(parts[i]);
        for (int i = last + 1; i < parts.length; i++) path.append('/').append(parts[i]);
        return url.substring(0, pathAt) + path + url.substring(end);
    }

    /** The pattern for every URL of the site that has the name three times in its path. */
    public static String patternFor(String site, String name) {
        String n = Pattern.quote(name);
        return "(?i)" + SessionGuard.regex(site) + "(?:/[^/?#]+)*?/" + n + "(?:/[^/?#]+)*?/" + n + "(?:/[^/?#]+)*?/" + n + "(?:[/?#].*)?";
    }

    /**
     * Whether two answers are the same page. The status must match, and the
     * bodies must either be equal or share nearly all their lines: a page that
     * prints the requested URL, the time or a token differs in a line or two
     * and is still the same page.
     */
    public static boolean samePage(Page a, Page b) {
        if (a == null || b == null || a.status() != b.status()) return false;
        String x = a.body() == null ? "" : a.body(), y = b.body() == null ? "" : b.body();
        if (x.equals(y)) return true;
        Set<String> lx = lines(x), ly = lines(y);
        if (lx.isEmpty() || ly.isEmpty()) return false;
        int both = 0;
        for (String l : lx) if (ly.contains(l)) both++;
        int either = lx.size() + ly.size() - both;
        // A short body has too few lines for a share of them to mean anything: it must be equal.
        return either >= 8 && both * 100 >= either * 90;
    }

    private static Set<String> lines(String body) {
        Set<String> out = new HashSet<>();
        for (String l : body.split("[\\r\\n]+|(?<=>)")) { String t = l.strip(); if (!t.isEmpty()) out.add(t); }
        return out;
    }

    /** Whether this URL belongs to a loop already found. */
    public boolean isLoop(String url) {
        if (url == null) return false;
        for (Pattern p : loops.values()) if (p.matcher(url).matches()) return true;
        return false;
    }

    /** The patterns of the loops found so far. */
    public List<String> patterns() {
        List<String> out = new ArrayList<>();
        for (Pattern p : loops.values()) out.add(p.pattern());
        return out;
    }

    /**
     * Look at the URLs a crawl has found on a site and settle any repeated
     * name not yet settled. Each URL is looked at once. Returns what was
     * settled this time: the caller excludes a loop's pattern and says so.
     */
    public synchronized List<Finding> examine(String site, Collection<String> urls) {
        List<Finding> out = new ArrayList<>();
        for (String url : urls) {
            if (url == null || !looked.add(url)) continue;
            String name = repeatedName(url);
            if (name == null) continue;
            String key = site + "\n" + name;
            if (settled.containsKey(key)) continue;
            int n = tried.merge(key, 1, Integer::sum);
            if (n > TRIES) continue;   // no answer was had: nothing is excluded without one
            String shorter = shorter(url, name);
            Page long_ = fetch.apply(url);
            Page short_ = long_ == null || shorter.equals(url) ? null : fetch.apply(shorter);
            if (long_ == null || short_ == null) { looked.remove(url); continue; }
            boolean loop = samePage(long_, short_);
            settled.put(key, loop);
            String pattern = patternFor(site, name);
            if (loop) loops.put(key, Pattern.compile(pattern));
            out.add(new Finding(site, name, loop, url, shorter, pattern));
        }
        return out;
    }
}