Iptables example block all except specified

From vpsget wiki
Revision as of 10:27, 24 April 2014 by Vq (talk | contribs)
Jump to: navigation, search

Here we are provide simple sample of most popular iptables config. We will block all connections except speficied ports/connection modes/

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

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 75.81.19.123 --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 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

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

""