Casbay Knowledge Base

Search our articles or browse by category below

HOW TO: Block all ports in IPtables

Last modified: October 1, 2022
Estimated reading time: 2 min

HOW TO: Block all ports in IPtables

Here we provide a sample of the most popular iptables configuration.

We will block all connections except specific ports

First of all, to exclude any errors because of the 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 forget 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 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

In case you need to allow some port range use the 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 the “-d” parameter:

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 add all “allow” rules do not forget to save the current iptables config to the file:

iptables-save >/etc/sysconfig/iptables

And restart the service:

service iptables restart

Read more on HOW TO: Check if IP is blocked from IPtables or visit Casbay VPS Hosting for more information!

Was this article helpful?
Dislike 0
Previous: AntiVirus: ClamAV
Next: Sending email using PHP (PHPMailer)