jgonian / commons-ip-math

https://github.com/jgonian/commons-ip-math
MIT License
74 stars 19 forks source link

AbstractRange.RangeIterator breaks when last IP is 255.255.255.255 #25

Closed Jaap-Jan closed 1 year ago

Jaap-Jan commented 2 years ago

When a range is created that includes 255.255.255.255 as last IP, RangeIterator behaves incorrectly because it calls Rangeable#next without checking that it doesn't overflow.

Steps to reproduce:

import java.util.Iterator;

import com.github.jgonian.ipmath.Ipv4;
import com.github.jgonian.ipmath.Ipv4Range;

class RangeIteratorOverflow {
    public static void main(String[] args) {
        Ipv4Range range = Ipv4Range.parse("255.255.255.255-255.255.255.255");
        Iterator<Ipv4> it = range.iterator();
        System.out.println(it.hasNext());
        System.out.println(it.next());
        System.out.println(it.hasNext());
    }
}

Expected result:

true
255.255.255.255
false

Actual result:

true
Exception in thread "main" java.lang.IllegalArgumentException: Value of IPv4 has to be less than or equal to 4294967295
    at com.github.jgonian.ipmath.Validate.isTrue(Validate.java:37)
    at com.github.jgonian.ipmath.Ipv4.<init>(Ipv4.java:55)
    at com.github.jgonian.ipmath.Ipv4.next(Ipv4.java:139)
    at com.github.jgonian.ipmath.Ipv4.next(Ipv4.java:29)
    at com.github.jgonian.ipmath.AbstractRange$RangeIterator.next(AbstractRange.java:173)
    at com.github.jgonian.ipmath.AbstractRange$RangeIterator.next(AbstractRange.java:161)
    at nl.shockmedia.ws.servers.dto.ip.RangeIteratorOverflow.main(RangeIteratorOverflow.java:13)
jgonian commented 1 year ago

Thanks for reporting @Jaap-Jan. The bug is triggered on the last value of the range iterator and seems to be affecting all range classes (AsnRange, Ipv4Range and Ipv6Range). I try to provide a fix in the upcoming days.