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 18.104.22.168 is the IP you want to allow through the Firewall):
# sudo iptables -A INPUT -s 22.214.171.124 -j ACCEPT
Denying the IP is very similar, just changing ACCEPT to DROP:
# sudo iptables -A INPUT -s 126.96.36.199 -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=188.8.131.52
# firewall-cmd --permanent --zone=public --add-source=184.108.40.206/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=220.127.116.11 reject"
# firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=18.104.22.168/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 22.214.171.124
Blocking and IP is just as simple, with the following command:
# sudo ufw deny from 126.96.36.199