Friday, October 19, 2012

iptables on Ubuntu

Last week, I got one of OpenVZ based VPS at really cheap price, and have tried to install ufw with no success. There is fix for that. But it did not work at least for me. It seemed working, but no individual rules worked. Also I am not much comfortable with 'fixing' several system modules.

So I began to touch iptables directly. It is not that much complicated, and it is even cleaner than using other front-end utilities such as ufw. For a basic firewall setting for web server, I don't think we need any other tools at all even for a beginner like me.

Install

apt-get install iptables
apt-get install iptables-persistent

Basic Setup

#local loop and allowing established sessions
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

#open ssh & web ports
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

#apply default policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

#if you have a safe ip to be allowed everything
iptables -A INPUT -s 123.123.123.123 -j ACCEPT

Making auto-start at boot

iptables-save > /etc/iptables/rules
update-rc.d iptables-persistent defaults

Reset iptables & reload from a file

Ubuntu has no script files to start/stop iptables. You may create a shell script based on following commands.
#reset iptables
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

#reload rules from a file
iptables-restore < /etc/iptables/rules
 

Delete a rule

iptables -L INPUT -n --line-numbers

#You'll get the list of all blocked IP. Look at the number on the left, then :
iptables -D INPUT "line-number"

#Or
iptables -D rule
iptables -D INPUT -s 202.100.85.0/24 -j DROP
 

Insert a rule at line number x

iptables -I INPUT 3 -p tcp --dport 22 -j ACCEPT

Add log

iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

Some more guides


No comments:

Post a Comment