How to Block all ports in IPtables

We’ve included an example of one of the most common iptables configurations. Except for particular ports, we will block all connections.

To begin, we’ll erase all present iptables rules to eliminate any errors caused by the prior configuration.

SSH into your server as root and run the following commands:

iptables -t filter -F 
iptables -t filter -X 

Now, we will block all traffic:

iptables -t filter -P INPUT DROP 
iptables -t filter -P FORWARD DROP 
iptables -t filter -P OUTPUT DROP 

We will maintain our existing relationships (you can skip it but we recommend putting these rules in place):

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 

Allow loopback connections (this is required in some situations). We propose adding this rule to rule out any potential application difficulties):

iptables -t filter -A INPUT -i lo -j ACCEPT 
iptables -t filter -A OUTPUT -o lo -j ACCEPT 

We’re now ready to add “acceptable rules” to the mix. We will, for example, enable http traffic:

iptables -t filter -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 80 -j ACCEPT

Don’t forget about SSH as well (in case you use differ ssh port -change it)

iptables -t filter -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -t filter -A OUTPUT -p tcp --dport 22 -j ACCEPT

You can also open an ssh port for a certain IP address:

iptables -I INPUT -p tcp -m tcp -s 101.69.69.101 --dport 22 -j ACCEPT
iptables -I INPUT -p tcp -m tcp -s 0.0.0.0/0 --dport 22 -j DROP

Use the following example if you need to allow a specific port range:

iptables -t filter -A OUTPUT -p tcp --dport 1024:2000 -j ACCEPT
iptables -t filter -A INPUT -p tcp --dport 1024:2000 -j ACCEPT

Block all UDP except port 53 (DNS):

#allow dns requests 
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
#block all other udp
iptables -A OUTPUT -p udp -j DROP
ip6tables -A OUTPUT -p udp -j DROP

NOTE: The “-d” argument can be used to specify permitted nameservers:

iptables -A OUTPUT -p udp --dport 53 -d 8.8.8.8 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -d 8.8.4.4 -j ACCEPT

Disable outgoing ping echo request:

iptables -A OUTPUT -p icmp --icmp-type echo-request -j DROP

Disable incoming pings:

iptables -A INPUT -p icmp --icmp-type echo-request -j REJECT

After you’ve added all of the “allow” rules, save the current iptables configuration to the file:

iptables-save >/etc/sysconfig/iptables

Restart the service:

service iptables restart