diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md index 00f8b01c90..f4a657e418 100644 --- a/docs/configuration/tls.md +++ b/docs/configuration/tls.md @@ -50,6 +50,14 @@ Disabling verification (`--no-verify-ssl`, `verify=False`, `NODE_TLS_REJECT_UNAU | `FLOCI_TLS_KEY_PATH` | *(unset)* | Path to PEM private key file | | `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate a server certificate signed by Floci's local CA when no cert/key paths provided | +The HTTPS listener accepts TLS 1.3 and TLS 1.2 by default, matching +[AWS's TLS 1.2 minimum](https://aws.amazon.com/blogs/security/tls-1-2-required-for-aws-endpoints/). +TLS 1.0 and TLS 1.1 are not enabled by default. To require TLS 1.3 only, set +`QUARKUS_TLS_PROTOCOLS=TLSv1.3`. An explicit [Quarkus TLS registry protocol setting](https://quarkus.io/guides/tls-registry-reference#tls-protocol-versions) +(`quarkus.tls.protocols`) takes precedence; otherwise the listener inherits the legacy +`quarkus.http.ssl.protocols` setting, including `QUARKUS_HTTP_SSL_PROTOCOLS`. The selected +protocols are retained when the server certificate is reloaded. + With TLS enabled, the proxy that accepts HTTP and HTTPS on Floci's ports listens on `QUARKUS_HTTP_HOST` (`127.0.0.1` by default). As without TLS, any address outside loopback also needs `FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true`; see [Network Exposure](./environment-variables.md#network-exposure). ## Local CA and Server Certificate diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 933ace86b5..1f593f2ca9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -10,6 +10,10 @@ quarkus: "io.apicurio": level: WARN + tls: + # Keep AWS's TLS 1.2 minimum and preserve explicit legacy HTTP protocol restrictions. + protocols: ${quarkus.http.ssl.protocols:TLSv1.3,TLSv1.2} + http: port: ${floci.port} # Loopback by default. Any other address (0.0.0.0, a LAN IP) also needs diff --git a/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java index edfd13210d..118c88e633 100644 --- a/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java @@ -23,9 +23,8 @@ import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.List; -import java.util.Set; -import java.util.TreeSet; +import static io.github.hectorvent.floci.config.TlsTestSupport.dnsSans; import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsActionJson; import static io.restassured.RestAssured.given; @@ -87,7 +86,7 @@ class CustomDomainTlsIntegrationTest { for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) { X509Certificate served = handshake(chain, domain, true); - assertTrue(sans(served).contains(domain), domain + " not in " + sans(served)); + assertTrue(dnsSans(served).contains(domain), domain + " not in " + dnsSans(served)); assertEquals(parse(chain).get(0).getSubjectX500Principal(), served.getIssuerX500Principal(), "the served leaf is issued by the CA in the ACM chain"); } @@ -98,7 +97,7 @@ class CustomDomainTlsIntegrationTest { assertThrows(SSLHandshakeException.class, () -> handshake(chain, domain, true), "reset drops " + domain); } - assertFalse(sans(handshake(chain, API_DOMAIN, false)).contains(API_DOMAIN)); + assertFalse(dnsSans(handshake(chain, API_DOMAIN, false)).contains(API_DOMAIN)); } /** @@ -134,12 +133,4 @@ class CustomDomainTlsIntegrationTest { .generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8))) .stream().map(X509Certificate.class::cast).toList(); } - - private static Set sans(X509Certificate leaf) throws Exception { - Set sans = new TreeSet<>(); - for (List entry : leaf.getSubjectAlternativeNames()) { - sans.add(String.valueOf(entry.get(1))); - } - return sans; - } } diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java index 6565ea4014..763d11376c 100644 --- a/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java @@ -8,21 +8,18 @@ import org.junit.jupiter.api.Test; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SNIHostName; -import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManagerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; -import java.nio.file.Path; -import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.List; import java.util.Set; -import java.util.TreeSet; +import static io.github.hectorvent.floci.config.TlsTestSupport.dnsSans; +import static io.github.hectorvent.floci.config.TlsTestSupport.trustOnlyTheCa; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -51,7 +48,7 @@ class TlsEnsureHostIntegrationTest { @Test void ensureHostIsVisibleToTheNextHandshakeAndResetTakesItBack() throws Exception { X509Certificate boot = peerLeaf(); - assertFalse(sans(boot).contains(NEW_HOST), "precondition: the boot leaf does not cover " + NEW_HOST); + assertFalse(dnsSans(boot).contains(NEW_HOST), "precondition: the boot leaf does not cover " + NEW_HOST); assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost, "precondition: a client verifying the new name rejects the boot leaf"); assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is served before"); @@ -59,7 +56,7 @@ class TlsEnsureHostIntegrationTest { manager.ensureHost(NEW_HOST); X509Certificate extended = peerLeaf(); - Set sans = sans(extended); + Set sans = dnsSans(extended); assertTrue(sans.contains(NEW_HOST), sans.toString()); assertTrue(sans.contains("localhost"), "configured names are still served: " + sans); assertEquals(boot.getPublicKey(), extended.getPublicKey(), "same key pair across the reload"); @@ -68,7 +65,7 @@ class TlsEnsureHostIntegrationTest { given().when().post("/_floci/state/reset").then().statusCode(200); - Set afterReset = sans(peerLeaf()); + Set afterReset = dnsSans(peerLeaf()); assertFalse(afterReset.contains(NEW_HOST), "reset drops the learned name: " + afterReset); assertTrue(afterReset.contains("localhost"), afterReset.toString()); assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost, "reset: the new name is rejected again"); @@ -114,24 +111,4 @@ class TlsEnsureHostIntegrationTest { connection.disconnect(); } } - - private static SSLContext trustOnlyTheCa() throws Exception { - KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType()); - trust.load(null, null); - trust.setCertificateEntry("floci", - FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(trust); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(null, tmf.getTrustManagers(), null); - return ctx; - } - - private static Set sans(X509Certificate leaf) throws Exception { - Set sans = new TreeSet<>(); - for (List entry : leaf.getSubjectAlternativeNames()) { - sans.add(String.valueOf(entry.get(1))); - } - return sans; - } } diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsConfigTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsConfigTest.java new file mode 100644 index 0000000000..013915abd3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsConfigTest.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.config; + +import io.smallrye.config.EnvConfigSource; +import io.smallrye.config.PropertiesConfigSource; +import io.smallrye.config.SmallRyeConfig; +import io.smallrye.config.SmallRyeConfigBuilder; +import io.smallrye.config.source.yaml.YamlConfigSource; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TlsProtocolsConfigTest { + + @Test + void defaultsToTls13AndTls12Only() throws IOException { + assertEquals(List.of("TLSv1.3", "TLSv1.2"), protocols(Map.of(), Map.of())); + } + + @Test + void preservesTheLegacyHttpProtocolRestriction() throws IOException { + assertEquals(List.of("TLSv1.3"), + protocols(Map.of("quarkus.http.ssl.protocols", "TLSv1.3"), Map.of())); + } + + @Test + void preservesTheLegacyHttpEnvironmentRestriction() throws IOException { + assertEquals(List.of("TLSv1.3"), + protocols(Map.of(), Map.of("QUARKUS_HTTP_SSL_PROTOCOLS", "TLSv1.3"))); + } + + @Test + void preservesTheRegistryEnvironmentRestriction() throws IOException { + assertEquals(List.of("TLSv1.3"), + protocols(Map.of(), Map.of("QUARKUS_TLS_PROTOCOLS", "TLSv1.3"))); + } + + @Test + void explicitRegistryProtocolsTakePrecedenceOverTheLegacySetting() throws IOException { + assertEquals(List.of("TLSv1.3"), protocols(Map.of( + "quarkus.tls.protocols", "TLSv1.3", + "quarkus.http.ssl.protocols", "TLSv1.3,TLSv1.2"), Map.of())); + } + + @Test + void anActiveProfileCanRestrictTheRegistryProtocols() throws IOException { + assertEquals(List.of("TLSv1.3"), + protocols(Map.of("%strict.quarkus.tls.protocols", "TLSv1.3"), Map.of())); + } + + private static List protocols(Map overrides, Map environment) + throws IOException { + SmallRyeConfig config = new SmallRyeConfigBuilder() + .addDefaultInterceptors() + .withProfile("strict") + .withSources(new YamlConfigSource(Path.of("src/main/resources/application.yml").toUri().toURL())) + .withSources(new EnvConfigSource(environment, 300)) + .withSources(new PropertiesConfigSource(overrides, "test-overrides", 400)) + .build(); + return config.getOptionalValues("quarkus.tls.protocols", String.class).orElse(List.of()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsIntegrationTest.java new file mode 100644 index 0000000000..953fa5c080 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/config/TlsProtocolsIntegrationTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.config; + +import io.github.hectorvent.floci.testutil.FreePorts; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.vertx.core.Vertx; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.config.TlsTestSupport.dnsSans; +import static io.github.hectorvent.floci.config.TlsTestSupport.trustOnlyTheCa; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@QuarkusTest +@TestProfile(SelfSignedTlsProfile.class) +class TlsProtocolsIntegrationTest { + + @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0") + int httpPort; + + @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0") + int httpsPort; + + @Inject + TlsCertificateManager manager; + + private Set originalHostnames; + private Vertx vertx; + private TlsProxyServer proxy; + private int publicPort; + + @BeforeEach + void startProxy() throws Exception { + originalHostnames = manager.knownHostnames(); + publicPort = FreePorts.loopbackIpv4Port(); + vertx = Vertx.vertx(); + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class); + when(config.port()).thenReturn(publicPort); + when(config.tls()).thenReturn(tls); + when(tls.enabled()).thenReturn(true); + when(tls.awsHttpsPort()).thenReturn(0); + when(config.security()).thenReturn(mock(EmulatorConfig.SecurityConfig.class)); + proxy = new TlsProxyServer(vertx, config, "127.0.0.1", httpPort, httpsPort); + } + + @AfterEach + void restoreCertificateAndCloseProxy() throws Exception { + try { + manager.clear(); + originalHostnames.forEach(manager::ensureHost); + } finally { + if (proxy != null) { + proxy.stop(); + } + if (vertx != null) { + vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS); + } + } + } + + @ParameterizedTest(name = "{0} works through the public proxy before and after certificate reload") + @ValueSource(strings = {"TLSv1.2", "TLSv1.3"}) + void protocolWorksBeforeAndAfterCertificateReload(String protocol) throws Exception { + String newHost = "tls-" + UUID.randomUUID() + ".reload.localhost.floci.io"; + X509Certificate before = health(publicPort, "localhost", protocol); + assertFalse(dnsSans(before).contains(newHost), "the new name must require a certificate reload"); + + manager.ensureHost(newHost); + + X509Certificate after = health(publicPort, newHost, protocol); + assertTrue(dnsSans(after).contains(newHost), "the listener must serve the newly issued SAN"); + assertNotEquals(before, after, "the listener must have reloaded its certificate"); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2}) + void obsoleteProtocolsAreRejectedByTheServerBeforeAndAfterReload(int minorVersion) throws Exception { + assertProtocolVersionAlert(minorVersion); + String newHost = "legacy-" + UUID.randomUUID() + ".reload.localhost.floci.io"; + X509Certificate before = health(publicPort, "localhost", "TLSv1.3"); + + manager.ensureHost(newHost); + + X509Certificate after = health(publicPort, newHost, "TLSv1.3"); + assertTrue(dnsSans(after).contains(newHost)); + assertNotEquals(before, after); + assertProtocolVersionAlert(minorVersion); + } + + private void assertProtocolVersionAlert(int minorVersion) throws Exception { + // A raw TLS 1.0/1.1 ClientHello reaches the server instead of being rejected locally + // by the JDK client's disabled-algorithm policy. The only offered cipher is TLS_RSA_WITH_AES_128_CBC_SHA. + byte[] hello = new byte[50]; + hello[0] = 22; + hello[1] = 3; + hello[2] = (byte) minorVersion; + hello[4] = 45; + hello[5] = 1; + hello[8] = 41; + hello[9] = 3; + hello[10] = (byte) minorVersion; + hello[45] = 2; + hello[47] = 0x2f; + hello[48] = 1; + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("127.0.0.1", publicPort), 5000); + socket.setSoTimeout(5000); + socket.getOutputStream().write(hello); + byte[] alert = socket.getInputStream().readNBytes(7); + assertEquals(7, alert.length, "a complete TLS alert must come from the server"); + assertEquals(21, alert[0], "TLS alert record"); + assertEquals(2, alert[5], "fatal alert"); + assertEquals(70, alert[6], "protocol_version alert"); + } + } + + private static X509Certificate health(int port, String host, String protocol) throws Exception { + try (Socket transport = new Socket()) { + transport.connect(new InetSocketAddress("127.0.0.1", port), 5000); + try (SSLSocket socket = (SSLSocket) trustOnlyTheCa().getSocketFactory() + .createSocket(transport, host, port, true)) { + socket.setSoTimeout(5000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setProtocols(new String[]{protocol}); + parameters.setServerNames(List.of(new SNIHostName(host))); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + socket.setSSLParameters(parameters); + socket.startHandshake(); + assertEquals(protocol, socket.getSession().getProtocol(), "the pinned protocol must be negotiated"); + + // The health endpoint uses the management host, independently of TLS SNI. + socket.getOutputStream().write(("GET /_floci/health HTTP/1.1\r\nHost: localhost" + + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); + String status = new BufferedReader(new InputStreamReader( + socket.getInputStream(), StandardCharsets.US_ASCII)).readLine(); + assertNotNull(status, "the real Quarkus backend must return an HTTP response"); + assertEquals("200", status.split(" ")[1], status); + return (X509Certificate) socket.getSession().getPeerCertificates()[0]; + } + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsTestSupport.java b/src/test/java/io/github/hectorvent/floci/config/TlsTestSupport.java new file mode 100644 index 0000000000..11b5b73c5c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/config/TlsTestSupport.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.config; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +final class TlsTestSupport { + + private TlsTestSupport() {} + + static SSLContext trustOnlyTheCa() throws Exception { + KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType()); + trust.load(null, null); + trust.setCertificateEntry("floci", + FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate()); + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(trust); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, factory.getTrustManagers(), null); + return context; + } + + static Set dnsSans(X509Certificate certificate) throws Exception { + Set names = new TreeSet<>(); + for (List entry : certificate.getSubjectAlternativeNames()) { + if (Integer.valueOf(2).equals(entry.get(0))) { + names.add(String.valueOf(entry.get(1))); + } + } + return names; + } +}