Describe the bug
The class IpAddressMatcher allows hostnames due to incorrect validation of IPv4 addresses. This happens because the regular expression used to validate IPv4 does not escape dots properly.
To Reproduce
new IpAddressMatcher("10x1x1x1"); // looking up '10x1x1x1'
var matcher = new IpAddressMatcher("10.33.1.0/24");
matcher.matches("www"); // looking up 'www'
Expected behavior
It is expected that IpAddressMatcher should only process literal IP addresses (v4 or v6) or subnet mask.
Sample
Here is a small repo reproducing the problem.
Comment From: therepanic
Hi, @levry!. I think this change makes sense, so I decided to make the regex more strictly, i.e., to solve the problem you described. PTAL
Comment From: levry
@therepanic Thank you — I really appreciate the attention to this issue!
However, it's worth considering the valid IPv4 formats accepted by InetAddress, which are also currently supported by IpAddressMatcher.
For example, addresses like "10.1.2" and "10.1" are parsed as valid IPv4 literals by InetAddress.
Here’s a test demonstrating the current behavior:
@CsvSource({
"10.1.2, 10.1.0.2, true",
"10.1.0.2, 10.1.2, true",
"10.1, 10.0.0.1, true",
"10.1/16, 10.0.123.1, true",
"10.1/16, 10.0.123.23, true",
"10.1/16, 10.3.123.23, false",
"10.0/24, 10.0.0.12, true",
"10.0/24, 10.0.1.12, false",
})
@ParameterizedTest
void matchesWhenIpV4(String matcherAddress, String ipAddress, boolean valid) {
var matcher = new IpAddressMatcher(matcherAddress);
assertThat(matcher.matches(ipAddress)).isEqualTo(valid);
}
Comment From: therepanic
Thanks for the correction, @levry. I tweaked the new regex a little bit and now it also covers all the cases you provided.