IPTables rules for a server

Here are some useful iptables rules, that let you run ssh (22), openvpn server (1194), mail (25,110, 143, 993, 995), rsync (873), ping (icmp), SOCKS (1080), and web servers (80, 443), while blocking all other ports. These are assumed to be in a script that you can run at startup (for example in /etc/rc.local). On an openVZ machine, I had to replace ‘eth’ by ‘venet’ in this script.  Also, for the INPUT chain, it should also be ok (better) to have all the states (NEW, ESTABLISHED, RELATED) instead just (NEW, RELATED).

 

#! /bin/bash
#all output on tun and eth are ok
iptables -A OUTPUT -o tun+ -j ACCEPT
iptables -A OUTPUT -o eth+ -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

#allow specific incoming connections:
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p udp --dport 1194 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport ssh -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 873 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 25 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 143 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 993 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 110 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 995 -j ACCEPT
iptables -A INPUT -i eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 1080 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -i eth0 -j DROP

#allow tun interface to forward to eth:
iptables -A FORWARD -i tun+ -j ACCEPT
iptables -A FORWARD -i tun+ -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth0 -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT
#definitely need this one:
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
#can also have instead, if MASQUERADE does not work:
#iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j SNAT --to-source your_vps_ip
exit 0

Leave a Reply

Your email address will not be published. Required fields are marked *