From 8917cdb404979ec23694ffe081ac891aa2e82bbd Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Mon, 1 Jul 2024 11:34:56 -0600 Subject: [PATCH] Improve Performance of IPv4 Check Closes gh-15324 --- .../web/util/matcher/IpAddressMatcher.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) 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 c2f547e48b..e7a4fdab03 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 @@ -18,7 +18,7 @@ package org.springframework.security.web.util.matcher; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.Scanner; +import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; @@ -37,6 +37,8 @@ import org.springframework.util.StringUtils; */ public final class IpAddressMatcher implements RequestMatcher { + private static Pattern IPV4 = Pattern.compile("\\d{0,3}.\\d{0,3}.\\d{0,3}.\\d{0,3}(/\\d{0,3})?"); + private final int nMaskBits; private final InetAddress requiredAddress; @@ -93,16 +95,13 @@ public final class IpAddressMatcher implements RequestMatcher { } private void assertNotHostName(String ipAddress) { + boolean isIpv4 = IPV4.matcher(ipAddress).matches(); + if (isIpv4) { + return; + } String error = "ipAddress " + ipAddress + " doesn't look like an IP Address. Is it a host name?"; Assert.isTrue(ipAddress.charAt(0) == '[' || ipAddress.charAt(0) == ':' - || Character.digit(ipAddress.charAt(0), 16) != -1, error); - if (!ipAddress.contains(":")) { - Scanner parts = new Scanner(ipAddress); - parts.useDelimiter("[./]"); - while (parts.hasNext()) { - Assert.isTrue(parts.hasNextInt() && parts.nextInt() >> 8 == 0, error); - } - } + || (Character.digit(ipAddress.charAt(0), 16) != -1 && ipAddress.contains(":")), error); } private InetAddress parseAddress(String address) {