I have many ports to block, but iptables multiport rule has a restriction and only allows a maximum of 15 ports.
severalports="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16"
iptables -A INPUT -p tcp -m multiport --dports $severalports -J DROP
iptables v1.4.21: too many ports specified
I'd like to know if there is any way to create a custom rule to bypass the maximum 15 ports limit (so I don't have to split the rule). thanks
PD: Ports 1:16 is just to explain the idea. Actual ports are not in sequence
The implicit
-m tcp
,-m udp
(and sctp etc.) all accept port range parameters. So your current example could be simplified into simply:It's the same for
-m multiport
except a range eats two slots:So if there are up to 7 ranges (+1 single port), you can do something like:
If you plan on an arbitrary high number of ports without adding a high number of rules, you can switch to using ipset (which also requires using the
ipset
tool) and aset
match:EDIT: actually the specific case above (all values in one single range) can also be simplified by using a range syntax in ipset (support might depend on version though) instead of the loop if needed. Won't change the set result:
Single iptables rule:
A bitmap should have O(1) lookup: constant (and what could matter: very fast) time.
ipset can be dynamically changed while in use:
even from the packet path if really needed.
It offers a lot of other list types (like
hash:ip,port
), most of them hashed. They can be loaded with hundred of thousand of entries and still keep a fast lookup, and help having simple and generic rules.