From c1adeef0dab446df4c04f51f744b2c3285309e62 Mon Sep 17 00:00:00 2001 From: Federico Herrera Date: Wed, 24 Jan 2024 23:08:05 -0300 Subject: [PATCH] Add validation IpAddressMatcher Closes gh-13621 --- .../security/web/util/matcher/IpAddressMatcher.java | 9 +++++++++ .../security/web/util/matcher/IpAddressMatcherTests.java | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java index 7df1aaa3e4c..80c344fb275 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java @@ -47,6 +47,7 @@ public final class IpAddressMatcher implements RequestMatcher { * come. */ public IpAddressMatcher(String ipAddress) { + assertStartsWithHexa(ipAddress); if (ipAddress.indexOf('/') > 0) { String[] addressAndMask = StringUtils.split(ipAddress, "/"); ipAddress = addressAndMask[0]; @@ -67,6 +68,7 @@ public boolean matches(HttpServletRequest request) { } public boolean matches(String address) { + assertStartsWithHexa(address); InetAddress remoteAddress = parseAddress(address); if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) { return false; @@ -89,6 +91,13 @@ public boolean matches(String address) { 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) { try { return InetAddress.getByName(address); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java index 0362917be13..17c2bbadb3a 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java @@ -105,4 +105,10 @@ public void ipv6RequiredAddressMaskTooLongThenIllegalArgumentException() { "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"); + } + }