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.

16.2 KB
Raw Blame
package opensuite.engine;

import opensuite.spider.Cdp;
import opensuite.spider.Cdp.JsonValue;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Looks at the pages open in the engine's own browsers, for the Live crawl
 * view. The engine drives a headless browser when it logs in and when it
 * crawls pages built by JavaScript; this takes a picture of the page that
 * browser has open, as the browser itself drew it, so what is shown is what the
 * scan is really seeing and not a second visit to the application.
 *
 * <p>The browsers are started with a debugging port on this machine only. They
 * are found as children of the engine's process, and a picture is asked of each
 * page over that port. Nothing is sent to the application.
 */
public final class CrawlWatch {

    /** The browser argument that lets a page be looked at. The port is picked by the system, on this machine only. */
    public static final String PORT_ARG = "--remote-debugging-port=0";

    /**
     * One look: the page a browser has open, with how many browsers are at work.
     * {@code cssWidth} is the page's width as the page itself measures it, which
     * is less than the picture's when the browser draws at more than one dot to
     * the point; {@code jpeg} is the picture as the browser sent it, small
     * enough to keep.
     */
    public record Frame(BufferedImage image, String url, String title, int pages, int cssWidth, byte[] jpeg) {}

    /**
     * The browsers draw two dots to the point, as a high-density screen does, so
     * the picture has detail to spare and stays sharp at whatever size the tab
     * shows it. The page is laid out exactly as before.
     */
    public static final String SCALE_ARG = "--force-device-scale-factor=2";

    /** How long the view stays with one browser before it may move to another, so it can be read. */
    static final long DWELL_MS = 2500;

    /** The size the engine's browsers open at. Their default is 800 by 600, which most pages treat as a small screen. */
    public static final String WINDOW_ARG = "--window-size=1366,768";

    private static final Pattern DATA_DIR = Pattern.compile("--user-data-dir=(\\S+)");
    private static final long EVERY_MS = 600;
    /** With nobody watching, a look is taken only this often, to have the last page to show afterwards. */
    private static final int UNWATCHED_EVERY = 5;

    private final java.util.function.Supplier<ZapEngine> engine;
    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build();
    private final Map<String, Cdp> open = new HashMap<>();          // by a page's socket address
    private final Map<String, String> lastUrl = new HashMap<>();    // by a page's id
    private final Map<String, Long> movedAt = new HashMap<>();      // by a page's id
    private final Map<String, Integer> cssWidths = new HashMap<>(); // by a page's socket address
    private String shownId;
    private long shownSince;
    private volatile boolean stopped;

    public CrawlWatch(java.util.function.Supplier<ZapEngine> engine) { this.engine = engine; }

    // ---- giving the crawl's browser the login a single-page application keeps in storage ----

    /** For each site, what its pages are given: names prefixed "local:" or "session:". */
    private static final Map<String, Map<String, String>> SEED = new java.util.concurrent.ConcurrentHashMap<>();
    private final Set<String> seeded = new HashSet<>();   // page id and site

    /** Have the crawl's browser hold these for a site's pages; an empty map takes the site off. */
    public static void seedStorage(String site, Map<String, String> items) {
        if (site == null) return;
        if (items == null || items.isEmpty()) SEED.remove(site); else SEED.put(site, new java.util.LinkedHashMap<>(items));
    }

    /** The site a page belongs to, written as the rest of the tool writes one. */
    public static String siteOf(String url) {
        try {
            URI u = URI.create(url);
            if (u.getScheme() == null || u.getHost() == null) return null;
            boolean secure = u.getScheme().equalsIgnoreCase("https");
            int port = u.getPort() < 0 ? (secure ? 443 : 80) : u.getPort();
            return new opensuite.core.HttpService(u.getHost(), port, secure).url();
        } catch (RuntimeException e) {
            return null;
        }
    }

    /**
     * The script run in a page: put in what is missing and, if anything was,
     * load the page again so the application starts with it. What is already
     * there is left alone, so a page is reloaded once at most.
     */
    public static String seedScript(Map<String, String> items) {
        StringBuilder local = new StringBuilder("{"), session = new StringBuilder("{");
        for (Map.Entry<String, String> e : items.entrySet()) {
            boolean s = e.getKey().startsWith("session:");
            String name = e.getKey().substring(e.getKey().indexOf(':') + 1);
            StringBuilder to = s ? session : local;
            if (to.length() > 1) to.append(',');
            to.append('"').append(opensuite.spider.Cdp.jsonEscape(name)).append("\":\"").append(opensuite.spider.Cdp.jsonEscape(e.getValue())).append('"');
        }
        return "(function(l,s){var n=0;try{for(var k in l){if(localStorage.getItem(k)===null){localStorage.setItem(k,l[k]);n++;}}"
                + "for(var j in s){if(sessionStorage.getItem(j)===null){sessionStorage.setItem(j,s[j]);n++;}}}catch(e){}"
                + "if(n>0)location.reload();return n;})(" + local + "}," + session + "})";
    }

    /** Give each page of a seeded site its storage, once. */
    private synchronized void seed() {
        if (SEED.isEmpty()) return;
        for (int port : ports()) {
            List<Page> pages;
            try {
                HttpRequest rq = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/json/list"))
                        .timeout(Duration.ofSeconds(1)).build();
                pages = pagesIn(http.send(rq, HttpResponse.BodyHandlers.ofString()).body());
            } catch (Exception e) { continue; }
            for (Page p : pages) {
                String site = siteOf(p.url());
                Map<String, String> items = site == null ? null : SEED.get(site);
                if (items == null || !seeded.add(p.id() + "\n" + site)) continue;
                Cdp cdp = null;
                try {
                    cdp = Cdp.connect(p.socket());
                    cdp.send("Runtime.evaluate", "{\"expression\":\"" + opensuite.spider.Cdp.jsonEscape(seedScript(items)) + "\"}");
                } catch (RuntimeException e) {
                    seeded.remove(p.id() + "\n" + site);   // the page was not ready: tried again on the next look
                } finally {
                    if (cdp != null) quiet(cdp);
                }
            }
        }
    }

    /** Have the engine start its browsers so that their pages can be looked at. */
    public static void arm(ZapApi api) {
        try { api.setBrowserArgument(PORT_ARG, true); } catch (Exception ignore) { /* the view stays empty */ }
        // A window the size of an ordinary desktop one, so a page is laid out and shown as it usually looks.
        try { api.setBrowserArgument(WINDOW_ARG, true); } catch (Exception ignore) { /* the browser keeps its small default */ }
        try { api.setBrowserArgument(SCALE_ARG, true); } catch (Exception ignore) { /* the picture is then only as fine as the page */ }
    }

    /**
     * Keep looking while a scan is running, and hand each look to the sink: a
     * frame, or null when no browser has a page open. While the view is being
     * watched a look is taken every tick; otherwise only now and then, so the
     * last page is there to show when the view is opened later.
     */
    public void start(BooleanSupplier running, BooleanSupplier watched, Consumer<Frame> sink) {
        Thread t = new Thread(() -> {
            boolean showing = false;
            int tick = 0;
            while (!stopped) {
                try {
                    if (running.getAsBoolean()) {
                        seed();
                        if (watched.getAsBoolean() || tick % UNWATCHED_EVERY == 0) {
                            Frame f = look();
                            if (f != null || showing) sink.accept(f);
                            showing = f != null;
                        }
                    } else if (showing || !open.isEmpty()) {
                        closeAll();
                        if (showing) sink.accept(null);
                        showing = false;
                    }
                    tick++;
                    Thread.sleep(EVERY_MS);
                } catch (InterruptedException e) {
                    return;
                } catch (RuntimeException e) {
                    opensuite.core.Debug.log("crawl watch: " + e);
                }
            }
        }, "crawl-watch");
        t.setDaemon(true);
        t.start();
    }

    /**
     * Which page to show. The one that moved last is where the crawl is, but a
     * view that jumped to it at once would flick between browsers too fast to
     * read; so the page being shown is kept for a while, as long as it is
     * still open.
     */
    static String choose(String shown, long shownSince, long now, Map<String, Long> movedAt) {
        String newest = null;
        long at = Long.MIN_VALUE;
        for (Map.Entry<String, Long> e : movedAt.entrySet())
            if (e.getValue() > at || (e.getValue() == at && e.getKey().equals(shown))) { at = e.getValue(); newest = e.getKey(); }
        if (shown != null && movedAt.containsKey(shown) && now - shownSince < DWELL_MS) return shown;
        return newest;
    }

    public void stop() { stopped = true; closeAll(); }

    /** The debugging ports of the engine's browsers that are running now. */
    List<Integer> ports() {
        List<Integer> out = new ArrayList<>();
        ZapEngine e = engine.get();
        if (e == null) return out;
        for (ProcessHandle h : e.descendants()) {
            Integer port = portOf(commandLine(h));
            if (port != null) out.add(port);
        }
        return out;
    }

    /**
     * A process's command line. A browser rewrites its own once it is running,
     * and what Java reports is then cut down to the program's path, so on Linux
     * it is read from the system as it stands.
     */
    static String commandLine(ProcessHandle h) {
        try {
            byte[] raw = Files.readAllBytes(Path.of("/proc", Long.toString(h.pid()), "cmdline"));
            if (raw.length > 0) return new String(raw, java.nio.charset.StandardCharsets.UTF_8).replace('\0', ' ');
        } catch (Exception ignore) { /* not Linux, or the process has gone */ }
        return h.info().commandLine().orElse("");
    }

    /** The port a browser started with this command line is listening on, or null if it is not one of ours to watch. */
    static Integer portOf(String commandLine) {
        if (!commandLine.contains(PORT_ARG) || commandLine.contains("--type=")) return null;
        Matcher m = DATA_DIR.matcher(commandLine);
        if (!m.find()) return null;
        try {
            // The browser writes the port it was given on the first line of this file.
            List<String> lines = Files.readAllLines(Path.of(m.group(1), "DevToolsActivePort"));
            return lines.isEmpty() ? null : Integer.valueOf(lines.get(0).trim());
        } catch (Exception e) {
            return null;   // not written yet, or the browser has gone
        }
    }

    /** One page a browser has open. */
    record Page(String id, String url, String title, String socket) {}

    /** The application pages among a browser's list of what it has open. */
    static List<Page> pagesIn(String json) {
        List<Page> out = new ArrayList<>();
        JsonValue root;
        try { root = JsonValue.parse(json); } catch (RuntimeException e) { return out; }
        if (!root.isArray()) return out;
        for (JsonValue t : root.asArray()) {
            String url = ZapApi.str(t, "url");
            if (!"page".equals(ZapApi.str(t, "type")) || url == null || !url.startsWith("http")) continue;
            String socket = ZapApi.str(t, "webSocketDebuggerUrl");
            if (socket == null || socket.isEmpty()) continue;
            out.add(new Page(ZapApi.str(t, "id"), url, ZapApi.str(t, "title"), socket));
        }
        return out;
    }

    /** Look once. Null when no browser has an application page open. */
    public synchronized Frame look() {
        List<Page> pages = new ArrayList<>();
        for (int port : ports()) {
            try {
                HttpRequest rq = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/json/list"))
                        .timeout(Duration.ofSeconds(1)).build();
                pages.addAll(pagesIn(http.send(rq, HttpResponse.BodyHandlers.ofString()).body()));
            } catch (Exception ignore) { /* that browser has just closed */ }
        }
        // Let go of pages that have closed.
        Set<String> live = new HashSet<>();
        for (Page p : pages) live.add(p.socket());
        for (String s : new ArrayList<>(open.keySet())) if (!live.contains(s)) { quiet(open.remove(s)); cssWidths.remove(s); }
        Set<String> ids = new HashSet<>();
        for (Page p : pages) ids.add(p.id());
        lastUrl.keySet().retainAll(ids);
        movedAt.keySet().retainAll(ids);
        if (pages.isEmpty()) { shownId = null; return null; }

        // Note which pages have moved, and settle on the one to show.
        long now = System.currentTimeMillis();
        Map<String, Long> moved = new HashMap<>();
        Map<String, Page> byId = new HashMap<>();
        for (Page p : pages) {
            if (!p.url().equals(lastUrl.put(p.id(), p.url()))) movedAt.put(p.id(), now);
            moved.put(p.id(), movedAt.getOrDefault(p.id(), 0L));
            byId.put(p.id(), p);
        }
        String id = choose(shownId, shownSince, now, moved);
        if (!java.util.Objects.equals(id, shownId)) { shownId = id; shownSince = now; }
        Page pick = byId.get(id);
        if (pick == null) return null;
        try {
            Cdp cdp = open.get(pick.socket());
            if (cdp == null) { cdp = Cdp.connect(pick.socket()); open.put(pick.socket(), cdp); }
            String data = cdp.send("Page.captureScreenshot", "{\"format\":\"jpeg\",\"quality\":82}").get("data").asString();
            byte[] jpeg = java.util.Base64.getDecoder().decode(data);
            BufferedImage img = javax.imageio.ImageIO.read(new ByteArrayInputStream(jpeg));
            if (img == null) return null;
            Integer css = cssWidths.get(pick.socket());
            if (css == null) {
                css = img.getWidth();
                try {
                    // The page's own width, asked of the browser and not of the page's scripts.
                    JsonValue v = cdp.send("Page.getLayoutMetrics", "{}").get("cssLayoutViewport");
                    int w = v == null ? 0 : v.get("clientWidth").asInt();
                    if (w > 0) css = w;
                } catch (RuntimeException ignore) { /* taken as one dot to the point */ }
                cssWidths.put(pick.socket(), css);
            }
            return new Frame(img, pick.url(), pick.title() == null ? "" : pick.title(), pages.size(), css, jpeg);
        } catch (RuntimeException | java.io.IOException e) {
            quiet(open.remove(pick.socket()));
            cssWidths.remove(pick.socket());
            return null;
        }
    }

    private synchronized void closeAll() {
        for (Cdp c : open.values()) quiet(c);
        open.clear();
        lastUrl.clear();
        movedAt.clear();
        cssWidths.clear();
        shownId = null;
    }

    private static void quiet(Cdp c) {
        if (c == null) return;
        try { c.close(); } catch (RuntimeException ignore) { }
    }
}