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.

11.1 KB
Raw Blame
package opensuite.proxy;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.function.BooleanSupplier;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Fetches Open Suite's own browser the first time it is wanted, so a machine with
 * no browser installed needs nothing done by hand. The same pinned Chromium
 * snapshot and checksums as fetch-browser.sh (tools/versions): the download is
 * verified before anything is unpacked, and only a complete, verified tree is
 * moved into place.
 */
public final class BrowserInstaller {

    /** Pinned in step with tools/versions; a test holds the two together. */
    static final String REVISION = "1739897";
    static final String CHROME_SHA256 = "1e91cc79f03fdc3ee88ec41d83916363486f54196cf7d5dffedad4b6574537fa";
    static final String DRIVER_SHA256 = "322d5da8574828f52e6f975ed20a5cb5d8835dcc4667207585f95a8e22525e5c";
    /** The Apple Silicon build: its own revision, since snapshots are not made for every revision on every platform. */
    static final String MAC_REVISION = "1739876";
    static final String MAC_CHROME_SHA256 = "7e3ba9bc8065d2f4616727fcacc47c6e48dea6f682cb9e6f62a655e826811880";
    static final String MAC_DRIVER_SHA256 = "bb7594fe4904987d5216d3ffb184d18085d5815e1c7df8eb498b1fadb9778d7e";
    /** The 64-bit Windows build, likewise the nearest revision that was built for it. */
    static final String WIN_REVISION = "1739871";
    static final String WIN_CHROME_SHA256 = "1f64ba54679753406996d4f67de232fe9eb0f9ded142a172ed66791cdb37895e";
    static final String WIN_DRIVER_SHA256 = "640c74be989045ffc147b029831890cc8c5078376d04be5243dbf4e72f897444";
    private static final String SNAPSHOTS = "https://commondatastorage.googleapis.com/chromium-browser-snapshots/";

    /** One platform's snapshot: where it is, what it is called, and its checksums. */
    record Build(String platform, String revision, String name, String chromeSha, String driverName, String driverSha, String binary) {}

    static final Build LINUX = new Build("Linux_x64", REVISION, "chrome-linux", CHROME_SHA256, "chromedriver_linux64", DRIVER_SHA256, "chrome");
    static final Build MAC = new Build("Mac_Arm", MAC_REVISION, "chrome-mac", MAC_CHROME_SHA256, "chromedriver_mac64", MAC_DRIVER_SHA256,
            "Chromium.app/Contents/MacOS/Chromium");

    static final Build WINDOWS = new Build("Win_x64", WIN_REVISION, "chrome-win", WIN_CHROME_SHA256, "chromedriver_win32", WIN_DRIVER_SHA256,
            "chrome.exe");

    /** The build for this machine, or null where there is none. */
    static Build build() {
        String os = System.getProperty("os.name", "").toLowerCase(java.util.Locale.ROOT);
        String arch = System.getProperty("os.arch", "").toLowerCase(java.util.Locale.ROOT);
        if (os.contains("linux") && (arch.equals("amd64") || arch.equals("x86_64"))) return LINUX;
        if (os.startsWith("mac") && arch.equals("aarch64")) return MAC;
        if (os.startsWith("windows") && (arch.equals("amd64") || arch.equals("x86_64"))) return WINDOWS;
        return null;
    }

    /** Where the pinned build runs, for messages. */
    public static final String PLATFORMS = "64-bit Linux, 64-bit Windows and Apple Silicon Macs";

    private BrowserInstaller() {}

    /** Told how far the work has got: what is being done, bytes so far and bytes in all (-1 when not known). */
    public interface Progress { void at(String step, long done, long total); }

    /** True where a pinned build runs: 64-bit Intel or AMD Linux, or an Apple Silicon Mac. */
    public static boolean supported() { return build() != null; }

    /** Download, verify and unpack the browser and its driver into {@code browserDir}. */
    public static void install(File browserDir, Progress progress, BooleanSupplier cancelled) throws IOException {
        Build b = build();
        if (b == null) throw new IOException("The bundled browser supports " + PLATFORMS + " only.");
        Files.createDirectories(browserDir.toPath());
        Path tmp = Files.createTempDirectory(browserDir.toPath(), ".fetch");
        try {
            String base = SNAPSHOTS + b.platform() + "/" + b.revision() + "/";
            Path chromeZip = tmp.resolve("chrome.zip"), driverZip = tmp.resolve("driver.zip");
            download(base + b.name() + ".zip", chromeZip, "Downloading browser", progress, cancelled);
            verify(chromeZip, b.chromeSha());
            download(base + b.driverName() + ".zip", driverZip, "Downloading driver", progress, cancelled);
            verify(driverZip, b.driverSha());
            progress.at("Unpacking", -1, -1);
            Path out = tmp.resolve("out");
            unzip(chromeZip, out, cancelled);
            unzip(driverZip, out, cancelled);
            Path chrome = out.resolve(b.name());
            if (!Files.isRegularFile(chrome.resolve(b.binary()))) throw new IOException("The download did not contain the browser.");
            Files.writeString(chrome.resolve("REVISION"), b.revision() + "\n");
            // The Windows snapshot carries a test program a third of its size that nothing here runs.
            Files.deleteIfExists(chrome.resolve("interactive_ui_tests.exe"));
            Path dest = browserDir.toPath().resolve(b.name());
            deleteTree(dest);
            Files.move(chrome, dest, StandardCopyOption.ATOMIC_MOVE);
            String driverFile = b == WINDOWS ? "chromedriver.exe" : "chromedriver";
            Path driver = out.resolve(b.driverName()).resolve(driverFile);
            if (Files.isRegularFile(driver)) Files.move(driver, browserDir.toPath().resolve(driverFile), StandardCopyOption.REPLACE_EXISTING);
        } finally {
            deleteTree(tmp);
        }
    }

    private static void download(String url, Path to, String step, Progress progress, BooleanSupplier cancelled) throws IOException {
        try {
            HttpClient http = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NORMAL)
                    .connectTimeout(java.time.Duration.ofSeconds(20)).build();
            HttpResponse<InputStream> r = http.send(HttpRequest.newBuilder(URI.create(url)).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
            if (r.statusCode() != 200) throw new IOException("The download server returned HTTP " + r.statusCode() + ".");
            long total = r.headers().firstValueAsLong("content-length").orElse(-1);
            try (InputStream in = r.body(); OutputStream out = Files.newOutputStream(to)) {
                byte[] buf = new byte[1 << 16];
                long done = 0;
                for (int n; (n = in.read(buf)) > 0; ) {
                    if (cancelled.getAsBoolean()) throw new IOException("Cancelled.");
                    out.write(buf, 0, n);
                    progress.at(step, done += n, total);
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Cancelled.");
        }
    }

    /** Refuse a file whose SHA-256 is not the pinned one. */
    static void verify(Path file, String sha256) throws IOException {
        try (InputStream in = Files.newInputStream(file)) {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] buf = new byte[1 << 16];
            for (int n; (n = in.read(buf)) > 0; ) md.update(buf, 0, n);
            String got = HexFormat.of().formatHex(md.digest());
            if (!got.equalsIgnoreCase(sha256)) throw new IOException("The download failed checksum verification and was discarded.");
        } catch (java.security.NoSuchAlgorithmException e) {
            throw new IOException(e);
        }
    }

    /**
     * Unpack an archive under {@code dir}. An entry that would land outside it
     * is refused, and a program or script is made executable, since the archive
     * format read here does not carry file modes.
     */
    static void unzip(Path zip, Path dir, BooleanSupplier cancelled) throws IOException {
        Path root = dir.toAbsolutePath().normalize();
        Files.createDirectories(root);
        // A macOS app bundle needs its symbolic links and file modes, which this
        // reader drops; the system's own unpacker keeps them, once every name is checked.
        if (opensuite.core.Os.MAC) { unzipKeepingLinks(zip, root, cancelled); return; }
        try (ZipInputStream in = new ZipInputStream(Files.newInputStream(zip))) {
            for (ZipEntry e; (e = in.getNextEntry()) != null; ) {
                if (cancelled.getAsBoolean()) throw new IOException("Cancelled.");
                Path to = root.resolve(e.getName()).normalize();
                if (!to.startsWith(root)) throw new IOException("The archive contains a path outside the extraction directory: " + e.getName());
                if (e.isDirectory()) { Files.createDirectories(to); continue; }
                Files.createDirectories(to.getParent());
                Files.copy(in, to, StandardCopyOption.REPLACE_EXISTING);
                if (runnable(to)) to.toFile().setExecutable(true, false);
            }
        }
    }

    private static void unzipKeepingLinks(Path zip, Path root, BooleanSupplier cancelled) throws IOException {
        try (java.util.zip.ZipFile z = new java.util.zip.ZipFile(zip.toFile())) {
            for (ZipEntry e : java.util.Collections.list(z.entries()))
                if (!root.resolve(e.getName()).normalize().startsWith(root))
                    throw new IOException("The archive contains a path outside the extraction directory: " + e.getName());
        }
        if (cancelled.getAsBoolean()) throw new IOException("Cancelled.");
        try {
            Process p = new ProcessBuilder("/usr/bin/ditto", "-x", "-k", zip.toString(), root.toString())
                    .redirectErrorStream(true).start();
            String said = new String(p.getInputStream().readAllBytes()).trim();
            if (p.waitFor() != 0) throw new IOException("Could not unpack the download: " + said);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Cancelled.");
        }
    }

    /** A native program (ELF) or a script with an interpreter line. */
    static boolean runnable(Path file) throws IOException {
        byte[] head = new byte[4];
        int n;
        try (InputStream in = Files.newInputStream(file)) { n = in.readNBytes(head, 0, 4); }
        return (n == 4 && head[0] == 0x7F && head[1] == 'E' && head[2] == 'L' && head[3] == 'F') || (n >= 2 && head[0] == '#' && head[1] == '!');
    }

    private static void deleteTree(Path p) throws IOException {
        if (!Files.exists(p, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return;
        try (java.util.stream.Stream<Path> walk = Files.walk(p)) {
            for (Path x : (Iterable<Path>) walk.sorted(java.util.Comparator.reverseOrder())::iterator) Files.deleteIfExists(x);
        }
    }
}