From e214417aaad876e8358736cdb02892e904b5a937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Slobodan=20Adamovi=C4=87?= Date: Thu, 8 Sep 2022 08:48:06 +0200 Subject: [PATCH] Make hostname resolution for loopback address more robust. (#89788) Implemented a fall-back to `localhost` when FQDN for loopback address (`127.0.0.1`) cannot be resolved. This can happen if test platform's DNS resolution is not properly configured. Closes #89324 --- .../kerberos/KerberosAuthenticationIT.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/x-pack/qa/kerberos-tests/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosAuthenticationIT.java b/x-pack/qa/kerberos-tests/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosAuthenticationIT.java index 072fe7a35eee6..0ecf121bf7a32 100644 --- a/x-pack/qa/kerberos-tests/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosAuthenticationIT.java +++ b/x-pack/qa/kerberos-tests/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosAuthenticationIT.java @@ -165,8 +165,22 @@ public void testGetOauth2TokenInExchangeForKerberosTickets() throws PrivilegedAc @SuppressForbidden(reason = "SPNEGO relies on hostnames and we need to ensure host isn't a IP address") protected HttpHost buildHttpHost(String host, int port) { try { - InetAddress inetAddress = InetAddress.getByName(host); - return super.buildHttpHost(inetAddress.getCanonicalHostName(), port); + final InetAddress address = InetAddress.getByName(host); + final String hostname = address.getCanonicalHostName(); + // InetAddress#getCanonicalHostName depends on the system configuration (e.g. /etc/hosts) to return the FQDN. + // In case InetAddress cannot resolve the FQDN it will return the textual representation of the IP address. + if (hostname.equals(address.getHostAddress())) { + if (address.isLoopbackAddress()) { + // Fall-back and return "localhost" for loopback address if it's not resolved. + // This is safe because InetAddress implements a reverse fall-back to loopback address + // in case the resolution of "localhost" hostname fails. + return super.buildHttpHost("localhost", port); + } else { + throw new IllegalStateException("failed to resolve [" + host + "] to FQDN"); + } + } else { + return super.buildHttpHost(hostname, port); + } } catch (UnknownHostException e) { assumeNoException("failed to resolve host [" + host + "]", e); }