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.

9.8 KB
Raw Blame
package opensuite.proxy;

import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;

/**
 * Holds the certificate authority to being per-installation.
 *
 * <p>An intercepting proxy that shipped one authority in its build would be
 * handing every user the same private key: anyone with a copy of the product
 * could then sign a certificate any other user's browser already trusts, and
 * read their traffic. Nothing is shipped, and this is the case that says so:
 * a fresh directory must produce a fresh key, and an existing one must be
 * reused rather than silently replaced.
 */
public final class CertificateAuthorityIsolationTest {

    private interface Body { void run() throws Exception; }

    private static void check(String name, Body body) {
        Harness.test(name, () -> {
            try { body.run(); }
            catch (AssertionError e) { throw e; }
            catch (Exception e) { throw new AssertionError(e.toString(), e); }
        });
    }

    private static String keyFingerprint(CertificateAuthority ca) throws Exception {
        byte[] spki = ca.caCertificate().getPublicKey().getEncoded();
        byte[] d = MessageDigest.getInstance("SHA-256").digest(spki);
        StringBuilder s = new StringBuilder();
        for (byte b : d) s.append(String.format("%02x", b));
        return s.toString();
    }

    private static void delete(Path dir) {
        try (var walk = Files.walk(dir)) {
            walk.sorted(java.util.Comparator.reverseOrder()).forEach(p -> {
                try { Files.deleteIfExists(p); } catch (Exception ignored) {}
            });
        } catch (Exception ignored) {}
    }

    public void run() {
        Harness.suite("certificate authority is per installation");

        check("two installations never share a private key", () -> {
            Path a = Files.createTempDirectory("ca-a");
            Path b = Files.createTempDirectory("ca-b");
            try {
                String fa = keyFingerprint(new CertificateAuthority(a));
                String fb = keyFingerprint(new CertificateAuthority(b));
                Expect.isFalse(fa.equals(fb),
                        "two fresh installations were given the same CA key");
            } finally { delete(a); delete(b); }
        });

        check("an existing authority is reused, not replaced", () -> {
            Path dir = Files.createTempDirectory("ca-reuse");
            try {
                String first = keyFingerprint(new CertificateAuthority(dir));
                String second = keyFingerprint(new CertificateAuthority(dir));
                Expect.equal(second, first,
                        "reopening replaced the authority, breaking every client that trusted it");
            } finally { delete(dir); }
        });

        check("the key is readable only by its owner", () -> {
            Path dir = Files.createTempDirectory("ca-perms");
            try {
                CertificateAuthority ca = new CertificateAuthority(dir);
                if (Files.getFileAttributeView(ca.storePath(), java.nio.file.attribute.PosixFileAttributeView.class) != null) {
                    var perms = Files.getPosixFilePermissions(ca.storePath());
                    Expect.isFalse(perms.contains(java.nio.file.attribute.PosixFilePermission.GROUP_READ),
                            "the CA key is readable by the group");
                    Expect.isFalse(perms.contains(java.nio.file.attribute.PosixFilePermission.OTHERS_READ),
                            "the CA key is readable by everyone");
                } else {
                    // Windows: the access list names the owner and nobody else.
                    var acl = Files.getFileAttributeView(ca.storePath(), java.nio.file.attribute.AclFileAttributeView.class).getAcl();
                    Expect.equal(acl.size(), 1, "one entry in the access list");
                    Expect.isTrue(acl.get(0).principal().equals(Files.getOwner(ca.storePath())), "and it is the owner");
                }
            } finally { delete(dir); }
        });

        check("a store made before the product was renamed still opens, and keeps its authority", () -> {
            Path dir = Files.createTempDirectory("ca-renamed");
            try {
                CertificateAuthority made = new CertificateAuthority(dir);
                String before = keyFingerprint(made);
                // Lock the same key and certificate the way the old name did.
                char[] now = "opensuite".toCharArray(), old = "opentrap".toCharArray();
                java.security.KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
                try (var in = Files.newInputStream(made.storePath())) { ks.load(in, now); }
                java.security.KeyStore relocked = java.security.KeyStore.getInstance("PKCS12");
                relocked.load(null, old);
                relocked.setKeyEntry("ca", ks.getKey("ca", now), old, ks.getCertificateChain("ca"));
                try (var out = Files.newOutputStream(made.storePath())) { relocked.store(out, old); }

                Expect.equal(keyFingerprint(new CertificateAuthority(dir)), before, "the old store opens with the same authority");
                java.security.KeyStore after = java.security.KeyStore.getInstance("PKCS12");
                try (var in = Files.newInputStream(made.storePath())) { after.load(in, now); }
                Expect.isTrue(after.getKey("ca", now) != null, "and is locked the new way from then on");
            } finally { delete(dir); }
        });

        check("a store that cannot be read is set aside and the proxy still gets an authority", () -> {
            Path dir = Files.createTempDirectory("ca-broken");
            try {
                CertificateAuthority first = new CertificateAuthority(dir);
                // What the old import did: a plain certificate copied over the store.
                Files.write(dir.resolve("ca.p12"), first.caCertificateDer());
                CertificateAuthority second = new CertificateAuthority(dir);
                Expect.isTrue(second.setAside() != null && Files.exists(second.setAside()), "the unreadable file is kept under another name");
                Expect.isFalse(keyFingerprint(first).equals(keyFingerprint(second)), "a new authority was made");
                CertificateAuthority third = new CertificateAuthority(dir);
                Expect.isTrue(third.setAside() == null, "the next start reads the new store");
                Expect.equal(keyFingerprint(third), keyFingerprint(second), "and keeps that authority");
            } finally { delete(dir); }
        });

        check("a certificate and key exported from one installation are imported into another", () -> {
            Path a = Files.createTempDirectory("ca-from"), b = Files.createTempDirectory("ca-to");
            try {
                CertificateAuthority from = new CertificateAuthority(a), to = new CertificateAuthority(b);
                Path cert = a.resolve("c.der"), key = a.resolve("k.der"), store = a.resolve("s.p12");
                Files.write(cert, from.caCertificateDer());
                Files.write(key, from.caKeyDer());
                to.adopt(CertificateAuthority.readFiles(cert, key));
                Expect.equal(keyFingerprint(to), keyFingerprint(from), "DER certificate and key");
                Expect.equal(keyFingerprint(new CertificateAuthority(b)), keyFingerprint(from), "kept at the next start");

                Files.write(store, from.storeBytes("secret".toCharArray()));
                Path c = Files.createTempDirectory("ca-to2");
                try {
                    CertificateAuthority other = new CertificateAuthority(c);
                    other.adopt(CertificateAuthority.readStore(store, "secret".toCharArray()));
                    Expect.equal(keyFingerprint(other), keyFingerprint(from), "PKCS#12 keystore");
                    Expect.isTrue(other.contextFor("example.com") != null, "and it signs for a host");
                } finally { delete(c); }
            } finally { delete(a); delete(b); }
        });

        check("a wrong file is refused and the authority in use stays", () -> {
            Path a = Files.createTempDirectory("ca-x"), b = Files.createTempDirectory("ca-y");
            try {
                CertificateAuthority mine = new CertificateAuthority(a), theirs = new CertificateAuthority(b);
                String before = keyFingerprint(mine);
                Path cert = a.resolve("c.der"), key = a.resolve("k.der"), store = a.resolve("s.p12");
                Files.write(cert, theirs.caCertificateDer());
                Files.write(key, mine.caKeyDer());
                Files.write(store, theirs.storeBytes("secret".toCharArray()));
                String[] said = new String[4];
                try { CertificateAuthority.readStore(cert, "x".toCharArray()); } catch (Exception e) { said[0] = e.getMessage(); }
                try { CertificateAuthority.readFiles(cert, key); } catch (Exception e) { said[1] = e.getMessage(); }
                try { CertificateAuthority.readStore(store, "wrong".toCharArray()); } catch (Exception e) { said[2] = e.getMessage(); }
                try { CertificateAuthority.readFiles(key, cert); } catch (Exception e) { said[3] = e.getMessage(); }
                Expect.equal(said[0], "The file is not a PKCS#12 keystore.", "a certificate given as a keystore");
                Expect.equal(said[1], "The private key does not belong to the certificate.", "a key of another certificate");
                Expect.equal(said[2], "The password is wrong.", "a wrong password");
                Expect.equal(said[3], "The certificate file is not an X.509 certificate.", "the two files the wrong way round");
                Expect.equal(keyFingerprint(new CertificateAuthority(a)), before, "the store on disk is untouched");
            } finally { delete(a); delete(b); }
        });

    }
}