iptables range is reversed and will never match

2 minute read Modified:

This blogpost was original posted on Capitar’s blog

The problem

When customers ask us to allow some IP addresses to their services they might give us an IP-range in the following way.

10.0.0.1-6

This means they want the following IP addresses to have access: 10.0.0.1, 10.0.0.2, 10.0.0.3, 10.0.0.4, 10.0.0.5 and 10.0.0.6. But when you use this notation with iptables it gives an warning.

# iptables -A INPUT -m iprange --src-range 10.0.0.1-6 -j ACCEPT
xt_iprange: range 10.0.0.1-6 is reversed and will never match

This message is not displayed when 10.0.0.1-16 is used, although this will not result in the expected result.

When searching for the error message, the source code of netfilter project iptables was given as a result. This code reveals the issue and solution.

The issue

The range that is given is split on the ‘-’ and then those ranges are compared to make sure that the lowest IP is mentioned first. In our case this is 10.0.0.1. But because we specify only a 6 after the ‘-’, this is converted to an IP address 6.0.0.0, which is lower than 10.0.0.1 and thus the warning message is displayed.

The range 10.0.0.1-16 is translated to 10.0.0.1-16.0.0.0 which is a valid range, but not what you would expect. And this would result in access to the service from a lot more systems than wanted.

The solution

When specifying an IP-range for iptables, you have to use full IP addresses on both sides of the ‘-’, so use 10.0.0.1-10.0.0.6 to get the result the customer wants.

Recent posts
- full list -