HOW TO: Block all ports in IPtables
Posted by on 19 June 2018 09:58 AM

Here we provide sample of most popular iptables configuration.

We will block all connections except specific ports

First of all to exclude any errors because of previous config we will delete all current iptables rules.

SSH to your server with root and execute the commands below:

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 keep established connections (you can skip it but we recommend to put these rules)

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

Allow loopback connections (necessary in some cases . we recommend to add this rule to exclude possible applications issues)

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

And now we are ready to add "allowed rules" For example we will allow http traffic:

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

And also do not forgot about SSH (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 also can open ssh port for specific IP

iptables -I INPUT -p tcp -m tcp -s --dport 22 -j ACCEPT
iptables -I INPUT -p tcp -m tcp -s --dport 22 -j DROP

In case you need to allow some port range use next example:

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

You can add allowed nameservers with "-d" parameter:

iptables -A OUTPUT -p udp --dport 53 -d -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -d -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 add all "allow" rules do not forgot to save the current iptables config to the file:

iptables-save >/etc/sysconfig/iptables

And restart the service:

service iptables restart


(0 vote(s))
Not helpful

Comments (0)
Copyright © 1998 - 2021 Shinjiru International Inc. All Rights Reserved.