diff --git a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java index 13601d2fe202f..8888ce33be57f 100644 --- a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java +++ b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java @@ -13,7 +13,6 @@ import org.apache.kerby.kerberos.kerb.client.KrbConfig; import org.apache.kerby.kerberos.kerb.server.KdcConfigKey; import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; -import org.apache.kerby.util.NetworkUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.ExceptionsHelper; @@ -22,6 +21,9 @@ import org.elasticsearch.test.ESTestCase; import java.io.IOException; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -31,6 +33,8 @@ import java.util.Locale; import java.util.concurrent.TimeUnit; +import javax.net.ServerSocketFactory; + /** * Utility wrapper around Apache {@link SimpleKdcServer} backed by Unboundid * {@link InMemoryDirectoryServer}.
@@ -127,14 +131,14 @@ private void prepareKdcServerAndStart() throws Exception { simpleKdc.setWorkDir(workDir.toFile()); simpleKdc.setKdcHost(host); simpleKdc.setKdcRealm(realm); - if (kdcPort == 0) { - kdcPort = NetworkUtil.getServerPort(); - } if (transport != null) { - if (transport.trim().equals("TCP")) { + if (kdcPort == 0) { + kdcPort = getServerPort(transport); + } + if (transport.trim().equalsIgnoreCase("TCP")) { simpleKdc.setKdcTcpPort(kdcPort); simpleKdc.setAllowUdp(false); - } else if (transport.trim().equals("UDP")) { + } else if (transport.trim().equalsIgnoreCase("UDP")) { simpleKdc.setKdcUdpPort(kdcPort); simpleKdc.setAllowTcp(false); } else { @@ -221,4 +225,21 @@ public Void run() throws Exception { logger.info("SimpleKdcServer stoppped."); } + private static int getServerPort(String transport) { + if (transport != null && transport.trim().equalsIgnoreCase("TCP")) { + try (ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1, + InetAddress.getByName("127.0.0.1"))) { + return serverSocket.getLocalPort(); + } catch (Exception ex) { + throw new RuntimeException("Failed to get a TCP server socket point"); + } + } else if (transport != null && transport.trim().equalsIgnoreCase("UDP")) { + try (DatagramSocket socket = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) { + return socket.getLocalPort(); + } catch (Exception ex) { + throw new RuntimeException("Failed to get a UDP server socket point"); + } + } + throw new IllegalArgumentException("Invalid transport: " + transport); + } }