diff --git a/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java index cb966c8451..57611e1a51 100644 --- a/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/IpAddressMatcher.java @@ -17,7 +17,7 @@ import org.springframework.util.StringUtils; * @author Luke Taylor * @since 3.0.2 */ -public class IpAddressMatcher implements RequestMatcher { +public final class IpAddressMatcher implements RequestMatcher { private final int nMaskBits; private final InetAddress requiredAddress; @@ -34,19 +34,23 @@ public class IpAddressMatcher implements RequestMatcher { ipAddress = addressAndMask[0]; nMaskBits = Integer.parseInt(addressAndMask[1]); } else { - nMaskBits = 0; + nMaskBits = -1; } requiredAddress = parseAddress(ipAddress); } public boolean matches(HttpServletRequest request) { - InetAddress remoteAddress = parseAddress(request.getRemoteAddr()); + return matches(request.getRemoteAddr()); + } + + public boolean matches(String address) { + InetAddress remoteAddress = parseAddress(address); if (!requiredAddress.getClass().equals(remoteAddress.getClass())) { return false; } - if (nMaskBits == 0) { + if (nMaskBits < 0) { return remoteAddress.equals(requiredAddress); } diff --git a/web/src/test/java/org/springframework/security/web/util/IpAddressMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/IpAddressMatcherTests.java index 7ae21a0ad6..e9febc7cd4 100644 --- a/web/src/test/java/org/springframework/security/web/util/IpAddressMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/IpAddressMatcherTests.java @@ -28,7 +28,6 @@ public class IpAddressMatcherTests { assertTrue(v6matcher.matches(ipv6Request)); } - @Test public void ipv6MatcherDoesntMatchIpv4Address() { assertFalse(v6matcher.matches(ipv4Request)); @@ -48,4 +47,27 @@ public class IpAddressMatcherTests { ipv4Request.setRemoteAddr("192.168.1.159"); // 159 = 0x9f assertTrue(matcher.matches(ipv4Request)); } + + @Test + public void ipv6RangeMatches() throws Exception { + IpAddressMatcher matcher = new IpAddressMatcher("2001:DB8::/48"); + + assertTrue(matcher.matches("2001:DB8:0:0:0:0:0:0")); + assertTrue(matcher.matches("2001:DB8:0:0:0:0:0:1")); + assertTrue(matcher.matches("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF")); + assertFalse(matcher.matches("2001:DB8:1:0:0:0:0:0")); + } + + // SEC-1733 + @Test + public void zeroMaskMatchesAnything() throws Exception { + IpAddressMatcher matcher = new IpAddressMatcher("0.0.0.0/0"); + + assertTrue(matcher.matches("123.4.5.6")); + assertTrue(matcher.matches("192.168.0.159")); + + matcher = new IpAddressMatcher("192.168.0.159/0"); + assertTrue(matcher.matches("123.4.5.6")); + assertTrue(matcher.matches("192.168.0.159")); + } }