Persistent ipset rules for firewalld.
With the release of firewalld version 0.4.3 came direct support for ipset via the firewall-cmd command, thus there is no longer any need to create a dedicated service to manage ipset lists. This article gives a concise description about the new ipset-related commands.
By using a typical blacklist scenario, we can achieve two goals in one article. We can demonstrate all the major firewall-cmd ipset commands and at the same time show the reader how to build a proper IP blacklist.
The first step is to create an ipset list (IPv4 in this case):
firewall-cmd --permanent --new-ipset=ipv4blacklist --type=hash:net --option=family=inet --option=hashsize=4096 --option=maxelem=200000
The second step is to tell firewalld to use this list for blocking:
firewall-cmd --permanent --zone=block --add-source=ipset:ipv4blacklist
You will notice that there are no drop parameters, no iptables commands and nothing related to IP packets. That is because we are using the source feature of firewalld, when an IP address matches the source (be that a source interface, or source IP or even a source MAC address) then the above rule redirects the IP address to a specific zone, which in this case is “block”.
Alternatively, we could use the “drop” zone, which is a black hole for all connections.
At this point our blacklist is ready and we may prepare it by adding IP addresses or whole net blocks. There are two ways to add new addresses, by mass-loading from a file or adding them one by one. To load from a file (the format is simple, just one IP address or net block per line), we use the following command:
firewall-cmd --permanent --ipset=ipv4blacklist --add-entries-from-file=/some/file/blacklist.xml
To load a single IP address or net block, we use the following command:
firewall-cmd --permanent --ipset=ipv4blacklist --add-entry=<ipaddress or net block>
Once we are finished, we may load our permanent commands into our running configuration:
The above procedure should get a server ready to block IPv4 addresses and whole net blocks, without the previous requirements on direct ipset commands that would not persist across reboots. In addition, there is no need of a custom ipset service for systemd, because our rules and ipset lists will load with the firewalld service automatically. The only thing left, is to create a second list for IPv6 addresses, but that is left as an exercise to the reader.
- Posted by Dimitris Dimitropoulos · April 3, 2017