Knowing how to Whitelist and Blacklist IPs in your firewall can be very important when you want to allow or deny connection to your server, based on an IP address. Below we will cover how to allow and deny connections from IPs in IP Tables, Firewalld, and UFW.
Allowing or Denying connections from IPs in IP Tables is quite simple. To accept the connection, or whitelist the IP, you would use the following command (where 188.8.131.52 is the IP you want to allow through the Firewall):
# sudo iptables -A INPUT -s 184.108.40.206 -j ACCEPT
Denying the IP is very similar, just changing ACCEPT to DROP:
# sudo iptables -A INPUT -s 220.127.116.11 -j DROP
You can also change DROP or REJECT if you want your server to respond back to the request with a Rejection instead of just dropping the traffic all together.
To whitelist IPs on Firewall-CMD, we’ll want to use the –add-source flag. We can whitelist an IP or an IP Subnets via the following commands:
# firewall-cmd --permanent --zone=public --add-source=18.104.22.168
# firewall-cmd --permanent --zone=public --add-source=22.214.171.124/16
Blocking an IP is a bit difficult, as it requires a more complex command. The command that you would want to use to block traffic from an IP would be:
# firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=126.96.36.199 reject"
# firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=188.8.131.52/16 reject"
We can also view all of the whitelisted IPs in our zone via:
# firewall-cmd --permanent --zone=public --list-sources
Allowing and blocking IPs in UFW is very simple and straight forward. We can allow connections from a specific IP via the following command:
# sudo ufw allow from 184.108.40.206
Blocking and IP is just as simple, with the following command:
# sudo ufw deny from 220.127.116.11