How to Whitelist or Block IPs in your Firewall on Linux – iptables, firewalld, ufw

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.

IPTables:
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 1.1.1.1 is the IP you want to allow through the Firewall):

# sudo iptables -A INPUT -s 1.1.1.1 -j ACCEPT

Denying the IP is very similar, just changing ACCEPT to DROP:

# sudo iptables -A INPUT -s 1.1.1.1 -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.

Firewalld:
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=1.1.1.1

Range:

# firewall-cmd --permanent --zone=public --add-source=1.1.0.0/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=1.1.1.1 reject"

Range:

# firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=1.1.0.0/16 reject"

We can also view all of the whitelisted IPs in our zone via:

# firewall-cmd --permanent --zone=public --list-sources

UFW:
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.33.44.55

Blocking and IP is just as simple, with the following command:

# sudo ufw deny from 22.33.44.55

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.