Skip to content
Open
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
7 changes: 7 additions & 0 deletions src/main/java/org/apache/commons/net/util/SubnetUtils6.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
* Performs subnet calculations given an IPv6 network address and a prefix length.
Expand Down Expand Up @@ -180,6 +181,8 @@ public String toString() {
private static final String PARSE_FAIL = "Could not parse [%s]";
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger MAX_VALUE = TWO.pow(NBITS).subtract(BigInteger.ONE);
// Hex digits and a colon first so InetAddress parses it as a literal; an optional scope ID follows '%'
private static final Pattern IPV6_LITERAL = Pattern.compile("\\[?[0-9a-fA-F]*:[0-9a-fA-F:.]*(%[^\\]]*)?\\]?");

/**
* Formats a BigInteger as an IPv6 address string using {@link InetAddress#getHostAddress()}.
Expand Down Expand Up @@ -228,6 +231,10 @@ private static byte[] toByteArray16(final BigInteger value) {
* @throws IllegalArgumentException if the address cannot be parsed.
*/
private static byte[] toBytes(final String address) {
// InetAddress.getByName() would resolve a host name through DNS
if (address == null || !IPV6_LITERAL.matcher(address).matches()) {
throw new IllegalArgumentException(String.format(PARSE_FAIL, address) + " - not an IPv6 address");
}
try {
final InetAddress inetAddr = InetAddress.getByName(address);
if (inetAddr instanceof Inet6Address) {
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/org/apache/commons/net/util/SubnetUtils6Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,18 @@ void testIsInRangeWithInvalidString() {
assertThrows(IllegalArgumentException.class, () -> info.isInRange("192.168.1.1"));
}

@Test
void testHostNameIsNotResolved() {
final SubnetInfo info = new SubnetUtils6("::1/128").getInfo();
// Host names must be rejected, not resolved, even when they map to an address in range
assertThrows(IllegalArgumentException.class, () -> info.isInRange("localhost"));
assertThrows(IllegalArgumentException.class, () -> info.isInRange("ip6-localhost"));
assertThrows(IllegalArgumentException.class, () -> info.isInRange(""));
assertThrows(IllegalArgumentException.class, () -> new SubnetUtils6("localhost/128"));
assertTrue(info.isInRange("[::1]"));
assertTrue(new SubnetUtils6("fe80::/10").getInfo().isInRange("fe80::1%1"));
}

@Test
void testLinkLocalAddress() {
final SubnetUtils6 utils = new SubnetUtils6("fe80::/10");
Expand Down