Browse Source

Add validation IpAddressMatcher

Closes gh-13621
Federico Herrera 1 year ago
parent
commit
c1adeef0da

+ 9 - 0
web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java

@@ -47,6 +47,7 @@ public final class IpAddressMatcher implements RequestMatcher {
 	 * come.
 	 * come.
 	 */
 	 */
 	public IpAddressMatcher(String ipAddress) {
 	public IpAddressMatcher(String ipAddress) {
+		assertStartsWithHexa(ipAddress);
 		if (ipAddress.indexOf('/') > 0) {
 		if (ipAddress.indexOf('/') > 0) {
 			String[] addressAndMask = StringUtils.split(ipAddress, "/");
 			String[] addressAndMask = StringUtils.split(ipAddress, "/");
 			ipAddress = addressAndMask[0];
 			ipAddress = addressAndMask[0];
@@ -67,6 +68,7 @@ public final class IpAddressMatcher implements RequestMatcher {
 	}
 	}
 
 
 	public boolean matches(String address) {
 	public boolean matches(String address) {
+		assertStartsWithHexa(address);
 		InetAddress remoteAddress = parseAddress(address);
 		InetAddress remoteAddress = parseAddress(address);
 		if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) {
 		if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) {
 			return false;
 			return false;
@@ -89,6 +91,13 @@ public final class IpAddressMatcher implements RequestMatcher {
 		return true;
 		return true;
 	}
 	}
 
 
+	private void assertStartsWithHexa(String ipAddress) {
+		Assert.isTrue(
+				ipAddress.charAt(0) == '[' || ipAddress.charAt(0) == ':'
+						|| Character.digit(ipAddress.charAt(0), 16) != -1,
+				"ipAddress must start with a [, :, or a hexadecimal digit");
+	}
+
 	private InetAddress parseAddress(String address) {
 	private InetAddress parseAddress(String address) {
 		try {
 		try {
 			return InetAddress.getByName(address);
 			return InetAddress.getByName(address);

+ 6 - 0
web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java

@@ -105,4 +105,10 @@ public class IpAddressMatcherTests {
 					"fe80::21f:5bff:fe33:bd68", 129));
 					"fe80::21f:5bff:fe33:bd68", 129));
 	}
 	}
 
 
+	@Test
+	public void invalidAddressThenIllegalArgumentException() {
+		assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher("invalid-ip"))
+			.withMessage("ipAddress must start with a [, :, or a hexadecimal digit");
+	}
+
 }
 }