How to block all private IP addresses using iptables in Linux

I need to block all private IP address on my Linux server. How do I block all private IP address using iptables?

You can use the iptables as follows to block an IP address:

iptables -I INPUT -s {IP_HERE} -j DROP
iptables -I INPUT -s {SUB/NET} -j DROP

Block IP addresses in Linux with iptables

sudo iptables -I INPUT -s 192.168.1.100 -j DROP
sudo iptables -I INPUT -s 192.168.1.0/24 -j DROP

Replace iptables with ip6tables for IPv6 version.

Block private IPv4 addresses subnets

According to RFC https://tools.ietf.org/html/rfc1918 we have the following IPv4 in private space:

  • 192.168.0.0/16
  • 172.16.0.0/12
  • 10.0.0.0/8
    We could write it as follows to block all IPv4 ranges:
sudo iptables -I INPUT -s 192.168.0.0/16,172.16.0.0/12,10.0.0.0/8 -j DROP

Don’t forget to save your rules using the iptables-save.

Ubuntu/Debian Linux block all private IP addresses using ufw

Some distro such as Ubuntu/Debian Linux use the ufw and that can be used as follows:

sudo ufw deny from 192.168.0.0/16
sudo ufw deny from 172.16.0.0/12
sudo ufw deny from 10.0.0.0/8

See UFW tutorials for detailed info:

  1. Install UFW firewall on Ubuntu 16.04 LTS server
  2. Configure Firewall with UFW on Ubuntu 20.04 LTS
  3. Block an IP address with ufw on Ubuntu Linux server

RHEL/CentOS/OpenSUSE Linux deny and drop private spaces using firewall-cmd/firewalld

sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.0.0/16' reject"
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='172.16.0.0/12' reject"
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='10.0.0.0/8' reject"

See firewall-cmd tutorials:

  1. How to set up a firewall using FirewallD on CentOS 8
  2. RHEL 8 FirewallD
  3. OpenSUSE 15.1 FirewallD

See the following url for more info

Good post, but I’d recommend blocking the same address spaces also outbound instead of only inbound.

That way contact either way is impossible.

@rautamiekka Yes, but one need to review outbound connections as in many cases internal network might be part of the LAN/VLAN and so on. Best policy to deny both INPUT, OUTPUT and FORWARD chains and then allow required ports and sub/net ranges.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki