mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(acm): stop hex-shaped names becoming bogus IP address SANs (#3335)
* fix(acm): stop hex-shaped names becoming bogus IP address SANs
The SAN type check matched any string of hex digits and colons, which is far
looser than an address. Two things followed, both silent.
A label like 1234 or 0 matched, and InetAddress.getByName decoded it rather than
failing: 1234 became 0.0.4.210. The certificate carried an address nobody asked
for, and the name the caller wanted covered was not in the certificate at all.
Worse, a colon-free label was handed to the resolver, so certificate generation
performed a blocking name-service lookup. If the name happened to resolve, the
resolved address was written as an iPAddress SAN in place of the literal name.
Detection is now a range-checked dotted quad, plus a colon test for IPv6
literals. A colon cannot appear in a hostname, so a colon-bearing value is parsed
as a literal or rejected outright, never looked up. Only values already known to
be literals reach the resolver, which is what keeps generation off the network.
The DNS-name fallback stays. With detection this tight only a malformed IPv6
literal can reach it, and covering the name is the safer failure: dropping it
would stop the server serving that host with nothing to point at, whereas an
unmatched dNSName entry is simply ignored by clients.
Tests cover what was silently wrong: hex-shaped labels stay DNS names, an octet
above 255 is not an address, a malformed IPv6 literal is still covered, and no
colon-free label is ever treated as an address.
* fix(acm): stop a colon-bearing hostname reaching the resolver
The SAN type check treated any value containing a colon as an IPv6 literal, on
the reasoning that a hostname cannot contain one. The JDK does not agree, and
the value was still handed to InetAddress.getByName.
getAllByName only attempts a literal parse when the FIRST character is an ASCII
hex digit or a colon; everything else it resolves. So z:1 has a colon, is not
literal-shaped, and is looked up. Measured on JDK 25: getByName("z:1") takes
tens of milliseconds and fails with the resolver's "nodename nor servname
provided", while getByName("fffff::1") fails in under a millisecond with
"invalid IPv6 address literal". Only the second never left the JVM.
That is the same bug this branch set out to fix, reopened for a narrower shape,
and the method's own javadoc asserted the opposite. Detection now matches the
JDK's dispatch: a colon AND a literal-shaped first character.
Both halves 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. Neither condition alone fails closed.
The leading-character test is spelled out rather than delegated to
Character.digit(c, 16). IPAddressUtil.digit resolves to an ASCII-only parser
unless jdk.net.allowAmbiguousIPAddressLiterals is set, and its own comment gives
the set as [0-9,A-F,a-f], but Character.digit answers 1 for the Arabic-Indic
digit one. The convenient spelling would classify U+0661 followed by a colon as
a literal, hand it to the resolver, and have the JDK decline to parse it and
look it up. Being stricter than the JDK is safe in both directions: if that
property is ever set, this only routes the value to the dNSName fallback.
Tests cover both shapes and were mutation-checked: restoring the colon-anywhere
rule fails the z:1 cases, and switching to Character.digit fails the non-ASCII
digit case.
Reported by pgermosen in review, including the observation that the malformed
IPv6 literal the existing tests cover is genuinely safe.
This commit is contained in:
1 parent
b87ee5bd4a
commit
7a7531a6b9
2 files changed
+156
-12
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+99
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user