Light, fluffy, and always free - The AWS Local Emulator alternative
fix(acm): stop hex-shaped names becoming bogus IP address SANs (#3335)
Hector Ventura7a7531a6b9ea
diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.javaindex eb4bfc3500..e87d9482c8 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java@@ -69,11 +69,13 @@ public class CertificateGenerator {private static final int PBE_ITERATIONS = 4096;/**- * Pattern matching IPv4 addresses (e.g. 192.168.1.100) and IPv6 addresses- * (bracketed like [::1] or raw like ::1, fe80::1).+ * A dotted quad with every octet in range. Deliberately strict: a loose pattern lets a+ * value like {@code 1234} reach {@link InetAddress#getByName}, which happily decodes it as+ * {@code 0.0.4.210} and bakes a nonsense address into the certificate.*/- private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile(- "^\\[?([0-9a-fA-F:]+)]?$|^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$"+ private static final Pattern IPV4_PATTERN = Pattern.compile(+ "^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)"+ + "(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}$");public record GeneratedCertificate(@@ -342,15 +344,16 @@ public class CertificateGenerator {private static GeneralName toGeneralName(String san) {if (isIpAddress(san)) {try {- // Strip brackets from IPv6 if present (e.g. [::1] → ::1)- String raw = san.startsWith("[") && san.endsWith("]")- ? san.substring(1, san.length() - 1)- : san;+ String raw = stripBrackets(san);byte[] addr = InetAddress.getByName(raw).getAddress();return new GeneralName(GeneralName.iPAddress,new org.bouncycastle.asn1.DEROctetString(addr));} catch (Exception e) {- // Fallback to DNS name if IP parsing fails+ // Only a malformed IPv6 literal reaches this: IPv4 is range-checked before it+ // gets here, and a value only arrives with a colon and a literal-shaped first+ // character, which the JDK rejects outright rather than resolving. Emitting it as a DNS+ // name keeps the name covered; dropping it would silently stop the server+ // serving that host, which fails a handshake with nothing to point at.LOG.debugv("Could not parse '{0}' as IP address, treating as DNS name", san);return new GeneralName(GeneralName.dNSName, san);}@@ -359,14 +362,56 @@ public class CertificateGenerator {}/**- * Checks whether a SAN value looks like an IP address (IPv4 or IPv6).- * Wildcard entries (e.g. *.localhost) are never IP addresses.+ * Whether a SAN value has the shape of an IP address literal. Wildcard entries are never+ * IP addresses.+ *+ * <p>This has to match the set {@link InetAddress#getByName} parses as a literal rather than+ * resolving, because anything outside that set is sent to the name service, and certificate+ * generation must not make network calls. That set is narrower than "contains a colon":+ * {@code getAllByName} only attempts a literal parse when the <em>first</em> character is an+ * ASCII hex digit or a colon, and otherwise resolves. So {@code z:1} holds a colon and is+ * still looked up.+ *+ * <p>Both halves of the colon test are load-bearing. Inside the JDK's literal branch a failed+ * IPv6 parse only throws when the value contains a colon; without one it falls through to a+ * lookup. So the value must both contain a colon and begin like a literal for the parse to be+ * guaranteed to fail closed.*/static boolean isIpAddress(String value) {if (value == null || value.isBlank() || value.startsWith("*")) {return false;}- return IP_ADDRESS_PATTERN.matcher(value).matches();+ String raw = stripBrackets(value);+ return IPV4_PATTERN.matcher(raw).matches()+ || (raw.indexOf(':') >= 0 && startsLikeAnIpLiteral(raw.charAt(0)));+ }++ /**+ * The JDK's own leading-character test for "try to parse this as a literal", spelled out+ * rather than delegated.+ *+ * <p>Deliberately not {@code Character.digit(c, 16)}. {@code IPAddressUtil.digit} resolves to+ * an ASCII-only parser unless {@code jdk.net.allowAmbiguousIPAddressLiterals} is set, and its+ * own comment gives the accepted set as {@code [0-9,A-F,a-f]}. {@code Character.digit} is+ * wider: it answers 1 for the Arabic-Indic digit one, so a value like {@code \u0661:1} would+ * pass this check, be handed to the resolver, and be looked up after the JDK declined to read+ * it as a literal.+ *+ * <p>Being stricter than the JDK is safe in both directions. If that property ever is set,+ * this check simply routes the value to the dNSName fallback instead of the resolver.+ */+ private static boolean startsLikeAnIpLiteral(char first) {+ return first == ':'+ || (first >= '0' && first <= '9')+ || (first >= 'a' && first <= 'f')+ || (first >= 'A' && first <= 'F');+ }++ /** Unwraps the brackets an IPv6 literal may carry, e.g. {@code [::1]} to {@code ::1}. */+ private static String stripBrackets(String value) {+ return value.length() > 1 && value.startsWith("[") && value.endsWith("]")+ ? value.substring(1, value.length() - 1)+ : value;}/**diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.javaindex 2b1df09451..15cd1c9c60 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java@@ -147,6 +147,66 @@ class CertificateGeneratorSanTypeTest {"Should have 3 iPAddress SANs (127.0.0.1, 0.0.0.0, 10.0.0.5). Found SANs: " + sans);}+ // ==================== hex-shaped names are not addresses ====================++ /**+ * A hex-only label used to match the old IP pattern and be handed to+ * {@code InetAddress.getByName}, which decodes {@code 1234} as {@code 0.0.4.210}. The+ * certificate then carried an address nobody asked for, and the name it was given was not+ * covered at all.+ */+ @ParameterizedTest+ @ValueSource(strings = {"1234", "0", "beef", "cafe", "abcd"})+ void hexShapedLabelsAreDnsNamesNotAddresses(String name) throws Exception {+ var cert = generator.generateSelfSignedCertificate(+ "localhost", List.of("localhost", name), KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ assertTrue(sans.stream().anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName+ && san.get(1).toString().equals(name)),+ name + " must be covered as a dNSName. Found: " + sans);+ assertFalse(sans.stream().anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress+ && !san.get(1).toString().equals("127.0.0.1")),+ name + " must not become an iPAddress SAN. Found: " + sans);+ }++ /** An octet above 255 is not an address; the old dotted-quad pattern accepted it. */+ @ParameterizedTest+ @ValueSource(strings = {"256.1.1.1", "999.999.999.999", "1.2.3.4.5", "01.02.03.256"})+ void outOfRangeDottedQuadsAreDnsNames(String name) {+ assertFalse(CertificateGenerator.isIpAddress(name),+ name + " is not a valid IPv4 address");+ }++ /** A malformed IPv6 literal still reaches the DNS-name fallback rather than being dropped. */+ @Test+ void aMalformedIpv6LiteralIsStillCoveredAsADnsName() throws Exception {+ var cert = generator.generateSelfSignedCertificate(+ "localhost", List.of("localhost", "fffff::1"), KeyAlgorithm.RSA_2048);++ X509Certificate x509 = generator.parseCertificate(cert.certificatePem());+ Collection<List<?>> sans = x509.getSubjectAlternativeNames();++ assertTrue(sans.stream().anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName+ && san.get(1).toString().equals("fffff::1")),+ "a name we cannot parse must still be covered, not silently dropped. Found: " + sans);+ }++ /**+ * The property that keeps certificate generation off the network: only values already known+ * to be literals are handed to the resolver. A colon-free label must never be treated as an+ * address, however hex-shaped, because resolving it would be a blocking DNS call whose result+ * would replace the name the caller asked to cover.+ */+ @ParameterizedTest+ @ValueSource(strings = {"1234", "beef", "deadbeef", "localhost", "floci"})+ void colonFreeLabelsAreNeverTreatedAsAddresses(String name) {+ assertFalse(CertificateGenerator.isIpAddress(name),+ name + " has no colon and is not a dotted quad, so it must not be resolved");+ }+// ==================== isIpAddress utility tests ====================@ParameterizedTest@@ -173,4 +233,43 @@ class CertificateGeneratorSanTypeTest {assertFalse(CertificateGenerator.isIpAddress(""));assertFalse(CertificateGenerator.isIpAddress(" "));}++ /**+ * A colon somewhere is not enough to make a value a literal, and treating it as one puts the+ * resolver back in the certificate path.+ *+ * <p>{@code InetAddress.getAllByName} only attempts a literal parse when the first character+ * is an ASCII hex digit or a colon; everything else it resolves. Measured on JDK 25,+ * {@code getByName("z:1")} takes tens of milliseconds and fails with the resolver's+ * "nodename nor servname provided", while {@code getByName("fffff::1")} fails in under a+ * millisecond with "invalid IPv6 address literal". Only the second never left the JVM.+ */+ @ParameterizedTest+ @ValueSource(strings = {"z:1", "host:8080", "xyz::1", "-:1", "_:1", "g::1"})+ void isIpAddress_colonButNotLiteralShaped_staysADnsName(String value) {+ assertFalse(CertificateGenerator.isIpAddress(value),+ value + " starts with a character the JDK will not read as a literal, so calling it "+ + "an IP address would send it to the name service");+ }++ /**+ * The shape a {@code Character.digit(c, 16)} implementation would let through.+ *+ * <p>{@code IPAddressUtil.digit} is ASCII-only by default and its own comment gives the set as+ * [0-9,A-F,a-f], but {@code Character.digit} answers 1 for the Arabic-Indic digit one. Writing+ * the leading-character test the convenient way would classify this as a literal, hand it to+ * the resolver, and have the JDK decline to parse it and look it up instead.+ */+ @Test+ void isIpAddress_nonAsciiDigitLeadingColonValue_staysADnsName() {+ assertFalse(CertificateGenerator.isIpAddress("\u0661:1"),+ "a non-ASCII digit is not one of [0-9,A-F,a-f], so the JDK would resolve this");+ }++ /** Literal-shaped leading characters still count, including uppercase hex and a bare colon. */+ @ParameterizedTest+ @ValueSource(strings = {"::1", "FE80::1", "fe80::1", "0::1", "9:1", "A::1", "f::1"})+ void isIpAddress_literalShapedLeadingCharacter_isStillAnIpAddress(String value) {+ assertTrue(CertificateGenerator.isIpAddress(value), value + " should be detected as IP");+ }}