Skip to content

Commit bc9678f

Browse files
committed
Add validation IpAddressMatcher
gh-13621
1 parent bdc0bd6 commit bc9678f

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public final class IpAddressMatcher implements RequestMatcher {
4747
* come.
4848
*/
4949
public IpAddressMatcher(String ipAddress) {
50+
assertStartsWithHexa(ipAddress);
5051
if (ipAddress.indexOf('/') > 0) {
5152
String[] addressAndMask = StringUtils.split(ipAddress, "/");
5253
ipAddress = addressAndMask[0];
@@ -66,6 +67,7 @@ public boolean matches(HttpServletRequest request) {
6667
}
6768

6869
public boolean matches(String address) {
70+
assertStartsWithHexa(address);
6971
InetAddress remoteAddress = parseAddress(address);
7072
if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) {
7173
return false;
@@ -88,6 +90,13 @@ public boolean matches(String address) {
8890
return true;
8991
}
9092

93+
private void assertStartsWithHexa(String ipAddress) {
94+
Assert.isTrue(
95+
ipAddress.charAt(0) == '[' || ipAddress.charAt(0) == ':'
96+
|| Character.digit(ipAddress.charAt(0), 16) != -1,
97+
"ipAddress must start with a [, :, or a hexadecimal digit");
98+
}
99+
91100
private InetAddress parseAddress(String address) {
92101
try {
93102
return InetAddress.getByName(address);

web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,10 @@ public void ipv6RequiredAddressMaskTooLongThenIllegalArgumentException() {
105105
"fe80::21f:5bff:fe33:bd68", 129));
106106
}
107107

108+
@Test
109+
public void invalidAddressThenIllegalArgumentException() {
110+
assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher("invalid-ip"))
111+
.withMessage("ipAddress must start with a [, :, or a hexadecimal digit");
112+
}
113+
108114
}

0 commit comments

Comments
 (0)