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.

18.8 KB
Raw Blame
package opensuite.proxy;

import opensuite.core.Debug;
import opensuite.spider.Cdp;
import opensuite.spider.Cdp.JsonValue;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Shows the start page in every new tab of the built-in browser, as it is
 * shown in the first.
 *
 * The browser is started with a private control channel: two pipes that only
 * this process holds, never a network port. Over it Open Suite is told when
 * a tab opens on the browser's own new-tab page and sends that tab to the
 * start page instead. Nothing else is asked of the channel.
 *
 * Where the channel cannot be set up (no shell, no named pipes), the caller
 * starts the browser the plain way and new tabs keep the browser's own page.
 */
public final class NewTabPage {

    private NewTabPage() {}

    /** True for the addresses the browser gives its own new-tab page. */
    static boolean isNewTab(String url) {
        if (url == null) return false;
        String u = url.trim().toLowerCase(java.util.Locale.ROOT);
        return u.equals("chrome://newtab/") || u.equals("chrome://newtab")
                || u.startsWith("chrome://new-tab-page") || u.startsWith("chrome-search://local-ntp");
    }

    /** The command that starts the browser with the two pipes on the descriptors it reads its control channel from. */
    static List<String> wrapped(List<String> cmd) {
        List<String> out = new ArrayList<>();
        out.add("/bin/sh");
        out.add("-c");
        out.add("exec \"$@\" 3<\"$OPENSUITE_PIPE_IN\" 4>\"$OPENSUITE_PIPE_OUT\"");
        out.add("sh");
        out.add(cmd.get(0));
        out.add("--remote-debugging-pipe");
        out.addAll(cmd.subList(1, cmd.size()));
        return out;
    }

    /**
     * Start the browser with the channel, or return null when that cannot be
     * done here, having started nothing.
     */
    static Process start(List<String> cmd, File errors, String startPage) {
        if (opensuite.core.Os.WINDOWS) return startByPort(cmd, errors, startPage);
        if (!new File("/bin/sh").canExecute()) return null;
        Path dir = null;
        try {
            dir = Files.createTempDirectory("opensuite-browser-pipe");
            File in = dir.resolve("in").toFile(), out = dir.resolve("out").toFile();
            Process mk = new ProcessBuilder("mkfifo", "-m", "600", in.getPath(), out.getPath())
                    .redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start();
            if (mk.waitFor() != 0) { tidy(dir); return null; }
            ProcessBuilder pb = new ProcessBuilder(wrapped(cmd))
                    .redirectOutput(ProcessBuilder.Redirect.DISCARD)
                    .redirectError(errors);
            pb.environment().put("OPENSUITE_PIPE_IN", in.getPath());
            pb.environment().put("OPENSUITE_PIPE_OUT", out.getPath());
            Process started = pb.start();
            final Path used = dir;
            Thread t = new Thread(() -> serve(started, in, out, used, startPage), "opensuite-new-tab");
            t.setDaemon(true);
            t.start();
            return started;
        } catch (IOException | RuntimeException e) {
            Debug.log("new-tab channel not available: " + e);
            if (dir != null) tidy(dir);
            return null;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            if (dir != null) tidy(dir);
            return null;
        }
    }

    /**
     * Windows has no named pipes a shell could hand the browser, so there the
     * channel is the browser's own debugging socket: on this machine only, on a
     * port the browser picks and writes into its profile folder.
     */
    private static Process startByPort(List<String> cmd, File errors, String startPage) {
        String profile = null;
        for (String a : cmd) if (a.startsWith("--user-data-dir=")) profile = a.substring("--user-data-dir=".length());
        if (profile == null) return null;
        Path portFile = Path.of(profile, "DevToolsActivePort");
        try {
            Files.deleteIfExists(portFile);
            List<String> with = new ArrayList<>();
            with.add(cmd.get(0));
            with.add("--remote-debugging-port=0");
            with.addAll(cmd.subList(1, cmd.size()));
            Process started = new ProcessBuilder(with)
                    .redirectOutput(ProcessBuilder.Redirect.DISCARD)
                    .redirectError(errors)
                    .start();
            Thread t = new Thread(() -> serveByPort(started, portFile, startPage), "opensuite-new-tab");
            t.setDaemon(true);
            t.start();
            return started;
        } catch (IOException | RuntimeException e) {
            Debug.log("new-tab channel not available: " + e);
            return null;
        }
    }

    private static void serveByPort(Process browser, Path portFile, String startPage) {
        Live mine = new Live();
        java.net.http.WebSocket ws = null;
        try {
            // The browser writes its port, then the path of its own socket, once it is listening.
            List<String> lines = List.of();
            for (int i = 0; i < 150 && browser.isAlive(); i++) {
                try { lines = Files.readAllLines(portFile); } catch (IOException notYet) { lines = List.of(); }
                if (lines.size() >= 2 && !lines.get(1).isBlank()) break;
                Thread.sleep(200);
            }
            if (lines.size() < 2) { Debug.log("new-tab channel: the browser gave no debugging port"); return; }
            java.util.concurrent.LinkedBlockingQueue<String> got = new java.util.concurrent.LinkedBlockingQueue<>();
            final String END = new String("end");
            java.net.http.WebSocket socket = java.net.http.HttpClient.newHttpClient().newWebSocketBuilder()
                    .buildAsync(java.net.URI.create("ws://127.0.0.1:" + lines.get(0).trim() + lines.get(1).trim()),
                            new java.net.http.WebSocket.Listener() {
                                private final StringBuilder part = new StringBuilder();
                                @Override public java.util.concurrent.CompletionStage<?> onText(java.net.http.WebSocket w, CharSequence data, boolean last) {
                                    part.append(data);
                                    if (last) { got.add(part.toString()); part.setLength(0); }
                                    w.request(1);
                                    return null;
                                }
                                @Override public java.util.concurrent.CompletionStage<?> onClose(java.net.http.WebSocket w, int code, String reason) { got.add(END); return null; }
                                @Override public void onError(java.net.http.WebSocket w, Throwable error) { got.add(END); }
                            })
                    .get(10, java.util.concurrent.TimeUnit.SECONDS);
            ws = socket;
            // The same messages as over the pipes: each one ends with a zero byte on the way out.
            OutputStream to = new OutputStream() {
                private final ByteArrayOutputStream buf = new ByteArrayOutputStream();
                @Override public synchronized void write(int b) throws IOException {
                    if (b != 0) { buf.write(b); return; }
                    String msg = buf.toString(StandardCharsets.UTF_8);
                    buf.reset();
                    try { socket.sendText(msg, true).get(5, java.util.concurrent.TimeUnit.SECONDS); }
                    catch (Exception e) { throw new IOException(e); }
                }
            };
            mine.to = to;
            live = mine;
            browser.onExit().thenRun(() -> got.add(END));
            // The Windows browser now and then leaves the page it was started with unloaded:
            // the address is in the bar and nothing was asked for. A page still without a
            // title a few seconds in is sent to its address once, which loads it.
            Thread nudge = new Thread(() -> {
                try { Thread.sleep(3000); } catch (InterruptedException e) { return; }
                for (Map.Entry<String, String> e : mine.pages.entrySet()) {
                    String url = e.getValue();
                    if (!url.startsWith("http") || !"".equals(mine.titles.get(e.getKey()))) continue;
                    int n = mine.ids.incrementAndGet();
                    mine.goTo.put(e.getKey(), url);
                    mine.attaching.put(n, e.getKey());
                    try {
                        write(to, "{\"id\":" + n + ",\"method\":\"Target.attachToTarget\",\"params\":{\"targetId\":\""
                                + Cdp.jsonEscape(e.getKey()) + "\",\"flatten\":true}}");
                    } catch (IOException gone) { return; }
                }
            }, "opensuite-first-page");
            nudge.setDaemon(true);
            nudge.start();
            pump(mine, to, () -> { try { String m = got.take(); return m == END ? null : m; } catch (InterruptedException e) { return null; } }, startPage);
        } catch (Exception e) {
            Debug.log("new-tab channel not available: " + e);
        } finally {
            if (live == mine) live = null;
            if (ws != null) ws.abort();
        }
    }

    /** Where the browser's messages come from, one at a time; null once it has closed. */
    private interface Source { String next() throws IOException; }

    /** Ask to be told of every page, then send each new tab to the start page until the browser closes. */
    private static void pump(Live mine, OutputStream to, Source from, String startPage) throws IOException {
        AtomicInteger ids = mine.ids;
        Map<Integer, String> attaching = mine.attaching;
        java.util.Set<String> sent = ConcurrentHashMap.newKeySet();
        write(to, "{\"id\":" + ids.incrementAndGet() + ",\"method\":\"Target.setDiscoverTargets\",\"params\":{\"discover\":true}}");
        for (String msg; (msg = from.next()) != null; ) {
            try { handle(msg, to, ids, attaching, sent, startPage); }
            catch (RuntimeException e) { Debug.log("new-tab channel: " + e); }
        }
    }

    private static void tidy(Path dir) {
        try { Files.deleteIfExists(dir.resolve("in")); Files.deleteIfExists(dir.resolve("out")); Files.deleteIfExists(dir); }
        catch (IOException ignored) { }
    }

    /** The channel to the browser that is open now, for the one other thing asked of it: reading a site's storage. */
    private static final class Live {
        OutputStream to;
        final AtomicInteger ids = new AtomicInteger();
        final Map<String, String> pages = new ConcurrentHashMap<>();                       // page id -> address
        final Map<Integer, java.util.concurrent.CompletableFuture<JsonValue>> asked = new ConcurrentHashMap<>();
        final Map<String, String> titles = new ConcurrentHashMap<>();                      // page id -> title
        final Map<Integer, String> attaching = new ConcurrentHashMap<>();                  // request -> page being attached to
        final Map<String, String> goTo = new ConcurrentHashMap<>();                        // page id -> where to send it, if not the start page
    }
    private static volatile Live live;

    /**
     * What the built-in browser holds in its storage for a site, where a
     * single-page application keeps its login: names prefixed "local:" or
     * "session:". Empty when the browser is not open, has no page of that site
     * open, or does not answer. Only read; nothing in the browser is changed.
     */
    public static Map<String, String> storageOf(String site) {
        Map<String, String> out = new java.util.LinkedHashMap<>();
        Live l = live;
        if (l == null || site == null) return out;
        String page = null;
        for (Map.Entry<String, String> e : l.pages.entrySet())
            if (e.getValue().equals(site) || e.getValue().startsWith(site + "/")) { page = e.getKey(); break; }
        if (page == null) return out;
        try {
            JsonValue attached = ask(l, null, "Target.attachToTarget", "{\"targetId\":\"" + Cdp.jsonEscape(page) + "\",\"flatten\":true}");
            String session = attached == null ? null : text(attached.get("sessionId"));
            if (session == null) return out;
            try {
                JsonValue got = ask(l, session, "Runtime.evaluate", "{\"returnByValue\":true,\"expression\":\""
                        + Cdp.jsonEscape("JSON.stringify({l:Object.assign({},localStorage),s:Object.assign({},sessionStorage)})") + "\"}");
                JsonValue result = got == null ? null : got.get("result");
                String json = result == null ? null : text(result.get("value"));
                if (json != null) readStorage(json, out);
            } finally {
                write(l.to, "{\"id\":" + l.ids.incrementAndGet() + ",\"method\":\"Target.detachFromTarget\",\"params\":{\"sessionId\":\""
                        + Cdp.jsonEscape(session) + "\"}}");
            }
        } catch (Exception e) {
            Debug.log("reading browser storage: " + e);
        }
        return out;
    }

    /** Read the browser's answer into names prefixed by which storage they came from. */
    public static void readStorage(String json, Map<String, String> out) {
        JsonValue v = JsonValue.parse(json);
        if (v == null || !v.isObject()) return;
        for (String[] part : new String[][]{{"l", "local:"}, {"s", "session:"}}) {
            JsonValue o = v.get(part[0]);
            if (o == null || !o.isObject()) continue;
            for (String k : o.keys()) {
                String val = text(o.get(k));
                if (val != null) out.put(part[1] + k, val);
            }
        }
    }

    private static JsonValue ask(Live l, String session, String method, String params) throws Exception {
        int n = l.ids.incrementAndGet();
        java.util.concurrent.CompletableFuture<JsonValue> f = new java.util.concurrent.CompletableFuture<>();
        l.asked.put(n, f);
        try {
            write(l.to, "{\"id\":" + n + (session == null ? "" : ",\"sessionId\":\"" + Cdp.jsonEscape(session) + "\"")
                    + ",\"method\":\"" + method + "\",\"params\":" + params + "}");
            return f.get(3, java.util.concurrent.TimeUnit.SECONDS);
        } finally {
            l.asked.remove(n);
        }
    }

    private static void serve(Process browser, File in, File out, Path dir, String startPage) {
        Live mine = new Live();
        // The shell opens the pipes in this order, each open waiting for its other end.
        try (OutputStream to = new FileOutputStream(in); InputStream from = new FileInputStream(out)) {
            tidy(dir);   // both ends are open: the names are no longer needed
            mine.to = to;
            live = mine;
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            pump(mine, to, () -> {
                for (int b; (b = from.read()) >= 0; ) {
                    if (b != 0) { buf.write(b); continue; }
                    String msg = buf.toString(StandardCharsets.UTF_8);
                    buf.reset();
                    return msg;
                }
                return null;
            }, startPage);
        } catch (IOException e) {
            // The browser closed: the channel goes with it.
        } finally {
            if (live == mine) live = null;
            tidy(dir);
        }
    }

    private static void handle(String msg, OutputStream to, AtomicInteger ids, Map<Integer, String> attaching,
                               java.util.Set<String> sent, String startPage) throws IOException {
        JsonValue m = JsonValue.parse(msg);
        if (m == null || !m.isObject()) return;
        JsonValue method = m.get("method");
        if (method != null && method.isString()) {
            String name = method.asString();
            JsonValue params = m.get("params");
            Live l = live;
            if (name.equals("Target.targetDestroyed")) {
                String gone = params == null ? null : text(params.get("targetId"));
                if (l != null && gone != null) { l.pages.remove(gone); l.titles.remove(gone); }
                return;
            }
            if (!name.equals("Target.targetCreated") && !name.equals("Target.targetInfoChanged")) return;
            JsonValue info = params == null ? null : params.get("targetInfo");
            if (info == null) return;
            String type = text(info.get("type")), url = text(info.get("url")), id = text(info.get("targetId"));
            if (id == null || !"page".equals(type)) return;
            if (l != null && url != null) l.pages.put(id, url);
            if (l != null) { String title = text(info.get("title")); l.titles.put(id, title == null ? "" : title); }
            if (!isNewTab(url)) { sent.remove(id); return; }    // the tab has moved on: a later new-tab page in it counts again
            if (!sent.add(id)) return;
            int n = ids.incrementAndGet();
            attaching.put(n, id);
            write(to, "{\"id\":" + n + ",\"method\":\"Target.attachToTarget\",\"params\":{\"targetId\":\""
                    + Cdp.jsonEscape(id) + "\",\"flatten\":true}}");
            return;
        }
        JsonValue idv = m.get("id");
        if (idv == null || !idv.isNumber()) return;
        Live waiting = live;
        java.util.concurrent.CompletableFuture<JsonValue> f = waiting == null ? null : waiting.asked.get(idv.asInt());
        if (f != null) { f.complete(m.get("result")); return; }
        String target = attaching.remove(idv.asInt());
        if (target == null) return;
        JsonValue result = m.get("result");
        String session = result == null ? null : text(result.get("sessionId"));
        if (session == null) return;
        String where = waiting == null ? null : waiting.goTo.remove(target);
        write(to, "{\"id\":" + ids.incrementAndGet() + ",\"sessionId\":\"" + Cdp.jsonEscape(session)
                + "\",\"method\":\"Page.navigate\",\"params\":{\"url\":\"" + Cdp.jsonEscape(where != null ? where : startPage) + "\"}}");
        write(to, "{\"id\":" + ids.incrementAndGet() + ",\"method\":\"Target.detachFromTarget\",\"params\":{\"sessionId\":\""
                + Cdp.jsonEscape(session) + "\"}}");
    }

    private static String text(JsonValue v) { return v != null && v.isString() ? v.asString() : null; }

    private static synchronized void write(OutputStream to, String json) throws IOException {
        to.write(json.getBytes(StandardCharsets.UTF_8));
        to.write(0);
        to.flush();
    }
}