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.

21.0 KB
Raw Blame
package opensuite.proxy;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Launches a Chromium-based browser preconfigured for the proxy.
 *
 * The browser runs in its own isolated profile, routes all traffic through the
 * proxy, and trusts the Open Suite CA through the SPKI-list flag, so there is no
 * certificate to install and no manual proxy setup. Only certificates under the
 * Open Suite CA are trusted, so this is safe.
 */
public final class EmbeddedBrowser {
    private EmbeddedBrowser() {}

    /** Candidate browser binaries, in order of preference. */
    private static final String[] CANDIDATES = {
        "/usr/bin/chromium",
        "/usr/bin/chromium-browser",
        "/usr/bin/google-chrome",
        "/usr/bin/google-chrome-stable",
        "/usr/bin/brave-browser",
        "/snap/bin/chromium",
        "/Applications/Chromium.app/Contents/MacOS/Chromium",
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
        "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"
    };

    /** Where a Chromium-family browser is installed on this system, most preferred first. */
    private static java.util.List<String> systemBrowsers() {
        if (!opensuite.core.Os.WINDOWS) return java.util.List.of(CANDIDATES);
        java.util.List<String> out = new ArrayList<>();
        for (String var : new String[]{"ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"}) {
            String base = System.getenv(var);
            if (base == null || base.isBlank()) continue;
            out.add(base + "\\Chromium\\Application\\chrome.exe");
            out.add(base + "\\Google\\Chrome\\Application\\chrome.exe");
            out.add(base + "\\BraveSoftware\\Brave-Browser\\Application\\brave.exe");
        }
        return out;
    }

    private static Process running;

    /**
     * Whether a program file is there to be run. Windows has no execute bit, and
     * what Java asks instead is refused on some network and shared folders though
     * the program starts from them, so there the file being present is the test.
     */
    static boolean runnable(File f) {
        return opensuite.core.Os.WINDOWS ? f.isFile() : f.canExecute();
    }

    /** The Chromium bundled in the product's browser/ folder, or null. */
    private static File bundledBrowser() {
        for (File root : productDirs()) {
            File[] cands = {
                new File(root, "browser/chrome-linux/chrome"),      // plain Chromium snapshot
                new File(root, "browser/chrome-linux64/chrome"),    // Chrome for Testing layout
                new File(root, "browser/chrome-mac/Chromium.app/Contents/MacOS/Chromium"),   // macOS snapshot
                new File(root, "browser/chrome-win/chrome.exe"),     // Windows snapshot
                new File(root, "browser/chrome"),
            };
            for (File f : cands) if (runnable(f)) return f;
        }
        return null;
    }

    /** Likely locations of the product directory (where dist/ and browser/ live). */
    private static java.util.List<File> productDirs() {
        java.util.List<File> dirs = new ArrayList<>();
        // Next to the running jar: <product>/dist/opensuite.jar -> <product>.
        try {
            // Through Path, not new File(URI): started from a network or shared folder
            // the location names a server (file://server/share/...), which File refuses
            // outright, and the browser beside the jar was then not found.
            File jar = java.nio.file.Path.of(EmbeddedBrowser.class.getProtectionDomain()
                    .getCodeSource().getLocation().toURI()).toFile();
            if (jar.isFile()) {
                File d = jar.getParentFile();                 // dist/ or build/
                if (d != null) dirs.add(d.getParentFile());   // product root
                dirs.add(d);
            } else if (jar.isDirectory()) {
                dirs.add(jar);                                 // running from build/
                if (jar.getParentFile() != null) dirs.add(jar.getParentFile());
            }
        } catch (Exception ignored) {}
        File home = new File(System.getProperty("user.home"));
        tidyOldInstall(home);
        dirs.add(fetchedRoot(home));
        dirs.add(new File(home, OLD_ROOT));   // a copy fetched by an earlier version that could not be moved
        dirs.add(new File(System.getProperty("user.dir")));
        return dirs;
    }

    /** Where earlier versions fetched the browser to: a folder in plain sight in the home folder. */
    static final String OLD_ROOT = "opensuite";

    /** The folder a fetched browser's {@code browser/} lives in: inside the application's own hidden folder. */
    static File fetchedRoot(File home) {
        return new File(new File(home, ".opensuite"), "bundled");
    }

    private static boolean tidied;

    /**
     * Earlier versions fetched the browser to {@code ~/opensuite/browser}, a
     * folder left loose in the home folder. It is moved once into the
     * application's own folder, and the old folder removed if nothing else is
     * in it. Anything that cannot be moved is left where it is, and still found.
     */
    static synchronized void tidyOldInstall(File home) {
        if (tidied && home.equals(new File(System.getProperty("user.home")))) return;
        tidied = true;
        try {
            File old = new File(home, OLD_ROOT), from = new File(old, "browser"), to = new File(fetchedRoot(home), "browser");
            if (!from.isDirectory() || to.exists()) return;
            // Only a folder that is the fetched browser and nothing else: a chrome or a driver in it.
            if (!new File(from, "chromedriver").exists() && !new File(from, "chrome-linux").isDirectory()
                    && !new File(from, "chrome-linux64").isDirectory()) return;
            java.nio.file.Files.createDirectories(to.getParentFile().toPath());
            java.nio.file.Files.move(from.toPath(), to.toPath());
            String[] left = old.list();
            if (left != null && left.length == 0) old.delete();
        } catch (Exception ignored) { /* left in place: it is still looked for there */ }
    }

    /**
     * The chromedriver matching the bundled or system Chromium, for ZAP's AJAX
     * spider. Prefers the one shipped in {@code browser/}, then the system path.
     * Returns null if none is found (the AJAX crawl is then skipped).
     */
    public static String findDriver() {
        for (File root : productDirs()) {
            File[] cands = {
                new File(root, "browser/chromedriver"),
                new File(root, "browser/chromedriver.exe"),
                new File(root, "browser/chrome-linux/chromedriver"),
                new File(root, "browser/chrome-linux64/chromedriver"),
            };
            for (File f : cands) if (runnable(f)) return f.getAbsolutePath();
        }
        for (String c : new String[]{
                "/usr/bin/chromedriver", "/usr/local/bin/chromedriver", "/opt/homebrew/bin/chromedriver",
                "/snap/bin/chromium.chromedriver"}) {
            if (new File(c).canExecute()) return c;
        }
        try {
            Process p = new ProcessBuilder("which", "chromedriver").start();
            if (p.waitFor() == 0) {
                String out = new String(p.getInputStream().readAllBytes()).trim();
                if (!out.isEmpty() && new File(out).canExecute()) return out;
            }
        } catch (Exception ignored) {}
        return null;
    }

    /** Said by {@link #launch} when there is no browser at all; the caller then offers to fetch one. */
    public static final String NO_BROWSER = "No browser is installed yet.";

    /**
     * Where the browser is fetched to: {@code browser/} in the product folder
     * when that can be written, else {@code ~/.opensuite/bundled/browser} (a
     * packaged copy is read-only). Both are places {@link #findBinary} looks.
     */
    public static File installDir() {
        File home = new File(System.getProperty("user.home"));
        File old = new File(home, OLD_ROOT);
        for (File root : productDirs()) {
            if (root == null || !root.isDirectory() || root.equals(old)) continue;
            if (!new File(root, "dist").isDirectory() && !new File(root, "browser").isDirectory()) continue;
            // Never into a macOS app bundle: anything added there breaks its signature.
            if (root.canWrite() && !root.getPath().contains(".app/")) return new File(root, "browser");
        }
        return new File(fetchedRoot(home), "browser");
    }

    /** True if a Chromium-family browser can be found. */
    public static boolean available() { return findBinary() != null; }

    /** A scan's browser crawl needs both the browser and the driver that steers it. */
    public static boolean readyForScans() { return findBinary() != null && findDriver() != null; }

    private static volatile Boolean sandboxWorks;

    /**
     * Whether the browser can start with its sandbox on this system, found by
     * starting it once without a window. Some Linux systems refuse the feature
     * the sandbox relies on, and the browser then ends as it starts.
     */
    public static boolean sandboxWorks() {
        Boolean known = sandboxWorks;
        if (known != null) return known;
        // Only Linux systems are known to refuse it; elsewhere the question is not asked.
        if (opensuite.core.Os.WINDOWS) return sandboxWorks = true;
        boolean works = true;
        String binary = findBinary();
        if (binary != null) {
            try {
                Process pr = new ProcessBuilder(binary, "--headless=new", "--disable-gpu",
                        "--dump-dom", "about:blank").redirectErrorStream(true).start();
                pr.getOutputStream().close();
                StringBuilder said = new StringBuilder();
                Thread reader = new Thread(() -> {
                    try (java.io.InputStream in = pr.getInputStream()) {
                        byte[] buf = new byte[4096];
                        for (int n; (n = in.read(buf)) > 0 && said.length() < 20000; ) {
                            synchronized (said) { said.append(new String(buf, 0, n, java.nio.charset.StandardCharsets.ISO_8859_1)); }
                        }
                    } catch (java.io.IOException ignore) { }
                }, "browser-sandbox-probe");
                reader.setDaemon(true);
                reader.start();
                if (!pr.waitFor(15, java.util.concurrent.TimeUnit.SECONDS)) pr.destroyForcibly();
                reader.join(2000);
                String text;
                synchronized (said) { text = said.toString(); }
                works = !refusesSandbox(text);
            } catch (Exception e) {
                works = true;   // could not tell; let the real start speak for itself
            }
        }
        sandboxWorks = works;
        return works;
    }

    /** Whether what a browser wrote as it ended says its sandbox was refused. */
    static boolean refusesSandbox(String said) {
        return said != null && (said.contains("No usable sandbox") || said.contains("setuid sandbox")
                || said.contains("namespace sandbox"));
    }

    public static String findBinary() {
        // Prefer the Chromium bundled with the product, so it works even when the
        // machine has no browser installed.
        File bundled = bundledBrowser();
        if (bundled != null) return bundled.getAbsolutePath();
        for (String c : systemBrowsers()) {
            if (runnable(new File(c))) return c;
        }
        if (opensuite.core.Os.WINDOWS) return null;   // no "which" there, and the places above are where it would be
        // Last resort: rely on PATH.
        for (String name : new String[]{"chromium", "chromium-browser", "google-chrome"}) {
            try {
                Process p = new ProcessBuilder("which", name).start();
                if (p.waitFor() == 0) {
                    String out = new String(p.getInputStream().readAllBytes()).trim();
                    if (!out.isEmpty() && new File(out).canExecute()) return out;
                }
            } catch (Exception ignored) {}
        }
        return null;
    }

    /**
     * Launch (or focus) the browser pointed at the proxy.
     *
     * @return null on success, or a human-readable error.
     */
    public static synchronized String launch(ProxyServer server, String startUrl) {
        return launch(server, startUrl, true);
    }

    /**
     * Launch the browser, optionally with its own security enforcement relaxed
     * so that requests it would otherwise refuse to send still reach the proxy.
     * See {@link BrowserFlags} for exactly what that changes.
     */
    public static synchronized String launch(ProxyServer server, String startUrl,
                                             boolean relaxSecurity) {
        String binary = findBinary();
        if (binary == null) {
            return NO_BROWSER;
        }

        int port = runningPort(server);
        if (port < 0) {
            return "No proxy listener is running. Enable one on the proxy options tab first.";
        }

        String spki;
        try {
            spki = server.ca().spkiFingerprint();
        } catch (Exception e) {
            return "Could not read the CA fingerprint: " + e.getMessage();
        }

        // Settings > Tools > Browser: where the profile lives, or a throwaway one when data is not stored.
        opensuite.core.Settings settings = server.settings();
        final boolean keep = BrowserFlags.storesData(settings);
        Path profile;
        try {
            profile = keep ? BrowserFlags.dataFolder(settings) : java.nio.file.Files.createTempDirectory("opensuite-browser");
        } catch (java.io.IOException e) {
            return "Could not create a temporary browser profile: " + e.getMessage();
        }
        profile.toFile().mkdirs();
        clearCache(profile);
        final Path used = profile;

        List<String> cmd = new ArrayList<>();
        cmd.add(binary);
        cmd.add("--user-data-dir=" + profile);
        cmd.add("--proxy-server=http://127.0.0.1:" + port);
        // Do not send local addresses direct; everything goes through the proxy
        // except the loopback literal the browser needs for internal pages.
        cmd.add("--proxy-bypass-list=<-loopback>");
        cmd.add("--ignore-certificate-errors-spki-list=" + spki);
        // Suppresses Chromium's yellow "unsupported command-line flag" banner
        // that the SPKI flag otherwise triggers.
        cmd.add("--test-type");
        cmd.add("--no-first-run");
        cmd.add("--no-default-browser-check");
        cmd.add("--disable-background-networking");
        cmd.add("--disable-sync");
        cmd.add("--disable-component-update");
        // Force all traffic over TCP through the proxy. Without this, Chromium
        // switches to QUIC/HTTP3 (UDP) for sites advertising Alt-Svc h3 (e.g.
        // google, example.com) and bypasses the proxy entirely, so nothing is
        // captured or intercepted.
        cmd.add("--disable-quic");
        // A pentest browser should show all traffic, so don't let the cache hide
        // requests. Minimise the disk cache and clear any stale entries below.
        cmd.add("--disk-cache-size=1");
        cmd.addAll(BrowserFlags.forTesting(relaxSecurity));
        cmd.addAll(BrowserFlags.fromSettings(settings));
        if (opensuite.core.Os.MAC) {
            // Its own profile asks for no Keychain access, so no password prompt appears on first start.
            cmd.add("--use-mock-keychain");
        } else if (!opensuite.core.Os.WINDOWS) {
            // Its own window class, which the desktop maps to Open Suite's own icon
            // through the entry installed below, so the testing browser is never
            // mistaken for the user's everyday one in the taskbar.
            cmd.add("--class=" + BrowserDesktopEntry.WM_CLASS);
            // Run as an X11 client even on a Wayland desktop (through XWayland):
            // the browser's native Wayland path pushes its vendor icon straight to
            // the compositor and does not reliably carry the class, so there would
            // be nothing for the desktop entry or the icon property to attach to.
            cmd.add("--ozone-platform=x11");
            BrowserDesktopEntry.install();
        }
        cmd.add("--new-window");
        cmd.add(startUrl == null || startUrl.isBlank() ? "http://opensuite/" : startUrl);

        try {
            // What the browser says as it starts is kept, so that one which
            // gives up at once can be explained rather than vanish unremarked.
            final java.io.File said = java.io.File.createTempFile("opensuite-browser", ".log");
            said.deleteOnExit();
            final long began = System.currentTimeMillis();
            // With its private channel where that can be set up, so new tabs show the start page too.
            Process viaChannel = NewTabPage.start(cmd, said, "http://opensuite/");
            final Process started = viaChannel != null ? viaChannel : new ProcessBuilder(cmd)
                    .redirectOutput(ProcessBuilder.Redirect.DISCARD)
                    .redirectError(said)
                    .start();
            running = started;
            if (!opensuite.core.Os.MAC && !opensuite.core.Os.WINDOWS) BrowserWindowIcon.watch(running);
            started.onExit().thenRun(() -> {
                String why = null;
                if (System.currentTimeMillis() - began < EARLY_EXIT_MS) {
                    String text = "";
                    try { text = new String(java.nio.file.Files.readAllBytes(said.toPath()), java.nio.charset.StandardCharsets.UTF_8); }
                    catch (java.io.IOException ignored) { }
                    why = startFailure(started.exitValue(), text);
                }
                said.delete();
                // A profile that is not stored goes when the browser does.
                if (!keep) deleteTree(used.toFile());
                if (why != null) onStartFailure.accept(why);
            });
            return null;
        } catch (Exception e) {
            return "Failed to launch the browser: " + e.getMessage();
        }
    }

    /** A browser that ends this soon after starting never came up. */
    private static final long EARLY_EXIT_MS = 8000;

    /** Told why the browser gave up as it started; by default, the user is shown it. */
    static volatile java.util.function.Consumer<String> onStartFailure = why ->
            javax.swing.SwingUtilities.invokeLater(() -> javax.swing.JOptionPane.showMessageDialog(
                    java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(),
                    why, "Open browser", javax.swing.JOptionPane.WARNING_MESSAGE));

    /**
     * Why a browser that ended straight after starting did so, from its exit
     * code and what it wrote; null when it ended without complaint (as it does
     * on handing the page to a window that is already open).
     */
    static String startFailure(int exitCode, String said) {
        if (exitCode == 0) return null;
        String text = said == null ? "" : said;
        if (refusesSandbox(text)) {
            return "Open Suite's browser could not start because the system does not permit its sandbox.\n"
                    + "Some Linux systems restrict the feature that the sandbox requires.\n\n"
                    + "To run the browser, enable \"Allow Open Suite's browser to run without a sandbox\"\n"
                    + "under Settings > Tools > Browser, or allow unprivileged user namespaces for it on this system.\n\n"
                    + "Without the sandbox, browsing hostile websites exposes the local host to greater risk.";
        }
        String first = "";
        for (String line : text.split("\n")) {
            String t = line.strip();
            if (!t.isEmpty() && !t.startsWith("#")) { first = t.length() > 300 ? t.substring(0, 300) : t; break; }
        }
        return "Open Suite's browser exited during startup (exit code " + exitCode + ")."
                + (first.isEmpty() ? "" : "\n\n" + first);
    }

    /** Remove cached responses so every navigation reaches the proxy. */
    private static void clearCache(Path profile) {
        String[] dirs = {
            "Default/Cache", "Default/Code Cache", "Default/GPUCache",
            "Default/Service Worker/CacheStorage", "Cache", "GPUCache",
        };
        for (String d : dirs) deleteTree(profile.resolve(d).toFile());
    }

    private static void deleteTree(File f) {
        if (f == null || !f.exists()) return;
        File[] kids = f.listFiles();
        if (kids != null) for (File k : kids) deleteTree(k);
        f.delete();
    }

    /** The port of the first running listener, or -1. */
    private static int runningPort(ProxyServer server) {
        for (ProxyListener l : server.listeners()) {
            if (l.running) return l.port;
        }
        return -1;
    }

    public static boolean isRunning() {
        return running != null && running.isAlive();
    }

    public static void shutdown() {
        if (running != null && running.isAlive()) running.destroy();
    }
}