From 55a34982890c98ea6560052bdf9d83f6f3eccd5c Mon Sep 17 00:00:00 2001 From: Ross Lawley Date: Wed, 7 Aug 2024 17:20:10 +0100 Subject: [PATCH] Connection String (#1467) Don't output the host and port information if the port is invalid. Reduces risk of leaking password information if the password has not been correctly urlencoded. JAVA-5560 --- .../src/main/com/mongodb/ConnectionString.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/driver-core/src/main/com/mongodb/ConnectionString.java b/driver-core/src/main/com/mongodb/ConnectionString.java index 9914c0d0aa7..42f64ed0172 100644 --- a/driver-core/src/main/com/mongodb/ConnectionString.java +++ b/driver-core/src/main/com/mongodb/ConnectionString.java @@ -1157,7 +1157,7 @@ private List parseHosts(final List rawHosts) { } int idx = host.indexOf("]:"); if (idx != -1) { - validatePort(host, host.substring(idx + 2)); + validatePort(host.substring(idx + 2)); } } else { int colonCount = countOccurrences(host, ":"); @@ -1166,7 +1166,7 @@ private List parseHosts(final List rawHosts) { + "Reserved characters such as ':' must be escaped according RFC 2396. " + "Any IPv6 address literal must be enclosed in '[' and ']' according to RFC 2732.", host)); } else if (colonCount == 1) { - validatePort(host, host.substring(host.indexOf(":") + 1)); + validatePort(host.substring(host.indexOf(":") + 1)); } } hosts.add(host); @@ -1175,19 +1175,17 @@ private List parseHosts(final List rawHosts) { return hosts; } - private void validatePort(final String host, final String port) { - boolean invalidPort = false; + private void validatePort(final String port) { try { int portInt = Integer.parseInt(port); if (portInt <= 0 || portInt > 65535) { - invalidPort = true; + throw new IllegalArgumentException("The connection string contains an invalid host and port. " + + "The port must be an integer between 0 and 65535."); } } catch (NumberFormatException e) { - invalidPort = true; - } - if (invalidPort) { - throw new IllegalArgumentException(format("The connection string contains an invalid host '%s'. " - + "The port '%s' is not a valid, it must be an integer between 0 and 65535", host, port)); + throw new IllegalArgumentException("The connection string contains an invalid host and port. " + + "The port contains non-digit characters, it must be an integer between 0 and 65535. " + + "Hint: username and password must be escaped according to RFC 3986."); } }