Skip to content

Add validation IpAddressMatcher #14491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -66,6 +67,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;
Expand All @@ -88,6 +90,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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

}