Skip to content

Instantly share code, notes, and snippets.

@xjdrew
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save xjdrew/b0dc74fe845ba15d093a to your computer and use it in GitHub Desktop.

Select an option

Save xjdrew/b0dc74fe845ba15d093a to your computer and use it in GitHub Desktop.
Automatically loading iptables rules on Ubuntu
#!/bin/sh
PRIVATE_IP=8.8.8.8
/bin/cp -f /etc/iptables.rules /etc/iptables.rules.old-$(date +%Y-%m-%d-%H:%M:%S)
cat > /etc/iptables.rules <<EOF
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:ICMPALL - [0:0]
# Accept all established inbound connections
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -j REJECT
# Allow ping
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT
# ssh
-A INPUT -p tcp --dport 22 -j ACCEPT
# web
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
# pptp
-A INPUT -p tcp --dport 1723 -j ACCEPT
# 自定义端口
-A INPUT -p tcp --dport 12306:12400 -j ACCEPT
# ntp
-A INPUT -p udp --dport 123 -j ACCEPT
# dhcp
-A INPUT -p udp --dport 68 -j ACCEPT
# radius
-A INPUT -p udp --dport 1812:1813 -j ACCEPT
# l2tp
-A INPUT -p udp -m multiport --dports 500,4500 -j ACCEPT
-A INPUT -p udp --dport 1701 -m policy --dir in --pol ipsec -j ACCEPT
-A INPUT -p udp --dport 1701 -j DROP
# pptp
-A FORWARD -i eth+ -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i ppp+ -o eth+ -j ACCEPT
# Log iptables denied calls
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
# drop all
-A INPUT -j DROP
-A FORWARD -j DROP
COMMIT
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -j SNAT --to-source ${PRIVATE_IP} -o eth+
COMMIT
EOF
cat > /etc/network/if-pre-up.d/iptablesload <<EOF
#!/bin/sh
/sbin/iptables-restore < /etc/iptables.rules
exit 0
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment