#!/bin/ksh # https://gist.github.com/801684 # A basic iptables rules setup # (C) 2011 GitHub Inc. All rights reserved. IPT=/sbin/iptables ## Make some new chains (should be self explanatory) $IPT -N bad_tcp_packets $IPT -N allowed $IPT -N tcp_packets $IPT -N udp_packets $IPT -N icmp_packets ## Drop bad packets $IPT -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK -m state --state NEW -j REJECT --reject-with tcp-reset $IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG --log-prefix "New not syn:" $IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP ## Set up allowed chain, this is were accepted packets will jump $IPT -A allowed -p TCP --syn -j ACCEPT $IPT -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT $IPT -A allowed -p TCP -j DROP ## Setup some rules for the tcp_packets chain. ## Generally all rules in this chain will jump to allowed $IPT -A tcp_packets -p TCP -s 0/0 --dport 22 -j allowed $IPT -A tcp_packets -p TCP -s 0/0 --dport 80 -j allowed ## Do the same for udp, and icmp chains ## Start adding new chains to the INPUT chain ## Replace a.b.c.d with your internet address $IPT -A INPUT -p tcp -j bad_tcp_packets $IPT -A OUTPUT -p tcp -j bad_tcp_packets $IPT -A FORWARD -p tcp -j bad_tcp_packets $IPT -A INPUT -p ALL -d a.b.c.d -m state --state ESTABLISHED,RELATED -j ACCEPT $IPT -A INPUT -p TCP -i eth0 -j tcp_packets $IPT -A INPUT -p ICMP -i eth0 -j icmp_packets $IPT -A INPUT -p UDP -i eth0 -j udp_packets ## Allow outbound traffic, replace a.b.c.d with your internet address $IPT -A OUTPUT -p ALL -s a.b.c.d -j ACCEPT ## Setup logging (with limits) before the packet falls of the end $IPT -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT INPUT packet died: " $IPT -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT FORWARD packet died: " $IPT -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT OUTPUT packet died: " ## Postrouting masquerading rule. Make sure /proc/sys/net/ipv4/ip_forward = 1 ## Replace a.b.c.d with your internet address $IPT -t nat -A POSTROUTING -o eth0 -j SNAT --to-source a.b.c.d ## Set the default policy to DROP. Anything not jumped through ## to allowed will drop $IPT -P INPUT DROP $IPT -P OUTPUT DROP $IPT -P FORWARD DROP exit 0