Skip to content

Commit 15e42c5

Browse files
committed
Optimize hostname checking for IPv6 addresses
1 parent 19c27c6 commit 15e42c5

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

tls/src/main/java/org/bouncycastle/jsse/provider/HostnameUtil.java

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,16 @@ static void checkHostname(String hostname, X509Certificate certificate, boolean
3030
throw new CertificateException("No hostname specified for HTTPS endpoint ID check");
3131
}
3232

33-
if (IPAddress.isValid(hostname))
33+
boolean hostnameIsIPv4 = IPAddress.isValidIPv4(hostname);
34+
boolean hostnameIsIPv6 = !hostnameIsIPv4 && IPAddress.isValidIPv6(hostname);
35+
36+
if (hostnameIsIPv4 || hostnameIsIPv6)
3437
{
3538
Collection<List<?>> subjectAltNames = certificate.getSubjectAlternativeNames();
3639
if (null != subjectAltNames)
3740
{
41+
InetAddress hostnameInetAddress = null;
42+
3843
for (List<?> subjectAltName : subjectAltNames)
3944
{
4045
if (!isAltNameType(subjectAltName, GeneralName.iPAddress))
@@ -53,20 +58,24 @@ static void checkHostname(String hostname, X509Certificate certificate, boolean
5358
return;
5459
}
5560

56-
try
61+
// In case of IPv6 addresses, convert to InetAddress to handle abbreviated forms correctly
62+
if (hostnameIsIPv6 && IPAddress.isValidIPv6(ipAddress))
5763
{
58-
if (InetAddress.getByName(hostname).equals(InetAddress.getByName(ipAddress)))
64+
try
5965
{
60-
return;
66+
if (hostnameInetAddress == null)
67+
{
68+
hostnameInetAddress = InetAddress.getByName(hostname);
69+
}
70+
if (hostnameInetAddress.equals(InetAddress.getByName(ipAddress)))
71+
{
72+
return;
73+
}
74+
}
75+
catch (UnknownHostException e)
76+
{
77+
// Ignore
6178
}
62-
}
63-
catch (UnknownHostException e)
64-
{
65-
// Ignore
66-
}
67-
catch (SecurityException e)
68-
{
69-
// Ignore
7079
}
7180
}
7281
}

0 commit comments

Comments
 (0)