|
| 1 | +package com.bencodez.simpleapi.servercomm.http; |
| 2 | + |
| 3 | +import java.io.ByteArrayInputStream; |
| 4 | +import java.io.IOException; |
| 5 | +import java.net.InetSocketAddress; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.security.KeyStore; |
| 9 | +import java.security.Security; |
| 10 | +import java.security.cert.X509Certificate; |
| 11 | +import java.time.Clock; |
| 12 | +import java.time.Duration; |
| 13 | +import java.util.Arrays; |
| 14 | +import java.util.concurrent.Executors; |
| 15 | +import java.util.concurrent.TimeUnit; |
| 16 | + |
| 17 | +import javax.net.ssl.KeyManager; |
| 18 | +import javax.net.ssl.KeyManagerFactory; |
| 19 | +import javax.net.ssl.SSLContext; |
| 20 | +import javax.net.ssl.SSLException; |
| 21 | +import javax.net.ssl.SSLServerSocket; |
| 22 | +import javax.net.ssl.SSLSocket; |
| 23 | +import javax.net.ssl.TrustManagerFactory; |
| 24 | + |
| 25 | +/** Invoked in a fresh JVM with only the shaded JAR and this fixture on its classpath. */ |
| 26 | +public final class PackagedTlsSmoke { |
| 27 | + private PackagedTlsSmoke() { } |
| 28 | + |
| 29 | + public static void main(String[] args) throws Exception { |
| 30 | + require(args.length == 2, "Expected state directory and full artifact"); |
| 31 | + Path state = Path.of(args[0]); |
| 32 | + Path full = Path.of(args[1]); |
| 33 | + requireFromJar(HttpTlsIdentity.class, full); |
| 34 | + HttpTlsIdentity identity = HttpTlsIdentity.loadOrCreate(state.resolve("trusted"), "127.0.0.1"); |
| 35 | + require(Security.getProvider("BC") != null, "BC provider was not registered"); |
| 36 | + requireFromJar(Security.getProvider("BC").getClass(), full); |
| 37 | + X509Certificate ca = identity.caCertificate(); |
| 38 | + X509Certificate server = identity.serverCertificate(); |
| 39 | + ca.verify(ca.getPublicKey()); |
| 40 | + server.verify(ca.getPublicKey()); |
| 41 | + server.checkValidity(); |
| 42 | + require(ca.getBasicConstraints() >= 0 && server.getBasicConstraints() == -1, "Incorrect CA constraints"); |
| 43 | + require(server.getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.1"), "Missing server-auth usage"); |
| 44 | + |
| 45 | + var client = identity.issueClientCertificate("backend-one"); |
| 46 | + client.certificate().verify(ca.getPublicKey()); |
| 47 | + require(identity.validClientCertificate("backend-one", client.certificate()), "Valid client rejected"); |
| 48 | + require(!identity.validClientCertificate("backend-two", client.certificate()), "Wrong backend identity accepted"); |
| 49 | + require(!identity.validClientCertificate("backend-one", server), "Server certificate accepted as a client"); |
| 50 | + SSLContext serverContext = identity.serverContext(); |
| 51 | + exchange(serverContext, clientContext(client, ca), true); |
| 52 | + exchange(serverContext, clientContext(null, ca), false); |
| 53 | + HttpTlsIdentity foreign = HttpTlsIdentity.loadOrCreate(state.resolve("foreign"), "127.0.0.1"); |
| 54 | + var foreignClient = foreign.issueClientCertificate("backend-one"); |
| 55 | + require(!identity.validClientCertificate("backend-one", foreignClient.certificate()), "Foreign CA accepted"); |
| 56 | + exchange(serverContext, clientContext(foreignClient, ca), false); |
| 57 | + |
| 58 | + HttpTlsIdentity reloaded = HttpTlsIdentity.loadOrCreate(state.resolve("trusted"), "127.0.0.1"); |
| 59 | + require(Arrays.equals(server.getEncoded(), reloaded.serverCertificate().getEncoded()), "Reload replaced the identity"); |
| 60 | + HttpTlsIdentity renewed = HttpTlsIdentity.loadOrCreate(state.resolve("trusted"), "127.0.0.1", |
| 61 | + Clock.offset(Clock.systemUTC(), Duration.ofDays(340))); |
| 62 | + renewed.serverCertificate().verify(ca.getPublicKey()); |
| 63 | + require(renewed.serverCertificate().getNotAfter().after(server.getNotAfter()), "Server renewal failed"); |
| 64 | + HttpTlsIdentity renewedCa = HttpTlsIdentity.loadOrCreate(state.resolve("trusted"), "127.0.0.1", |
| 65 | + Clock.offset(Clock.systemUTC(), Duration.ofDays(3400))); |
| 66 | + renewedCa.caCertificate().verify(ca.getPublicKey()); |
| 67 | + renewedCa.serverCertificate().verify(renewedCa.caCertificate().getPublicKey()); |
| 68 | + require(renewedCa.caCertificate().getNotAfter().after(ca.getNotAfter()), "CA renewal failed"); |
| 69 | + System.out.println("Packaged TLS smoke passed: certificate issuance, PKCS12, mutual TLS, rejection, reload and renewal"); |
| 70 | + } |
| 71 | + |
| 72 | + private static SSLContext clientContext(HttpTlsIdentity.IssuedClientCertificate client, X509Certificate ca) |
| 73 | + throws Exception { |
| 74 | + KeyManager[] keys = new KeyManager[0]; |
| 75 | + if (client != null) { |
| 76 | + byte[] encoded = client.pkcs12(); |
| 77 | + char[] password = client.password(); |
| 78 | + try { |
| 79 | + KeyStore store = KeyStore.getInstance("PKCS12"); |
| 80 | + try (var input = new ByteArrayInputStream(encoded)) { store.load(input, password); } |
| 81 | + KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 82 | + factory.init(store, password); |
| 83 | + keys = factory.getKeyManagers(); |
| 84 | + } finally { |
| 85 | + Arrays.fill(encoded, (byte) 0); |
| 86 | + Arrays.fill(password, '\0'); |
| 87 | + } |
| 88 | + } |
| 89 | + KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType()); |
| 90 | + trust.load(null, new char[0]); |
| 91 | + trust.setCertificateEntry("ca", ca); |
| 92 | + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); |
| 93 | + factory.init(trust); |
| 94 | + SSLContext context = SSLContext.getInstance("TLS"); |
| 95 | + context.init(keys, factory.getTrustManagers(), null); |
| 96 | + return context; |
| 97 | + } |
| 98 | + |
| 99 | + private static void exchange(SSLContext serverContext, SSLContext clientContext, boolean expected) throws Exception { |
| 100 | + var executor = Executors.newSingleThreadExecutor(); |
| 101 | + try (SSLServerSocket listener = (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket()) { |
| 102 | + listener.bind(new InetSocketAddress("127.0.0.1", 0)); |
| 103 | + listener.setSoTimeout(5000); |
| 104 | + listener.setNeedClientAuth(true); |
| 105 | + var accepted = executor.submit(() -> { |
| 106 | + try (SSLSocket socket = (SSLSocket) listener.accept()) { |
| 107 | + socket.setSoTimeout(5000); |
| 108 | + socket.startHandshake(); |
| 109 | + require(socket.getInputStream().read() == 41, "Missing authenticated request"); |
| 110 | + socket.getOutputStream().write(42); |
| 111 | + return true; |
| 112 | + } catch (SSLException rejected) { |
| 113 | + return false; |
| 114 | + } |
| 115 | + }); |
| 116 | + boolean clientAccepted = false; |
| 117 | + try (SSLSocket socket = (SSLSocket) clientContext.getSocketFactory().createSocket()) { |
| 118 | + socket.connect(new InetSocketAddress("127.0.0.1", listener.getLocalPort()), 5000); |
| 119 | + socket.setSoTimeout(5000); |
| 120 | + var parameters = socket.getSSLParameters(); |
| 121 | + parameters.setEndpointIdentificationAlgorithm("HTTPS"); |
| 122 | + socket.setSSLParameters(parameters); |
| 123 | + socket.startHandshake(); |
| 124 | + socket.getOutputStream().write(41); |
| 125 | + clientAccepted = socket.getInputStream().read() == 42; |
| 126 | + } catch (IOException rejected) { |
| 127 | + if (expected) throw rejected; |
| 128 | + } |
| 129 | + // A negative case must be an actual TLS rejection on the server, not a connect/timeout error. |
| 130 | + require(accepted.get(10, TimeUnit.SECONDS) == expected, "Unexpected server handshake result"); |
| 131 | + require(clientAccepted == expected, "Unexpected client handshake result"); |
| 132 | + } finally { |
| 133 | + executor.shutdownNow(); |
| 134 | + require(executor.awaitTermination(10, TimeUnit.SECONDS), "TLS fixture worker did not stop"); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + private static void requireFromJar(Class<?> type, Path full) throws Exception { |
| 139 | + Path source = Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI()); |
| 140 | + require(Files.isSameFile(source, full), "Loaded outside packaged artifact: " + type.getName()); |
| 141 | + } |
| 142 | + |
| 143 | + private static void require(boolean condition, String message) { |
| 144 | + if (!condition) throw new AssertionError(message); |
| 145 | + } |
| 146 | +} |
0 commit comments