Skip to content

Instantly share code, notes, and snippets.

@amalc
Last active December 19, 2015 15:19
Show Gist options
  • Save amalc/5975128 to your computer and use it in GitHub Desktop.
Save amalc/5975128 to your computer and use it in GitHub Desktop.
Firewall rules with ssh , OpenVPN, ntp, dns, icmp for a specific host, and PostgresSQL.
# Flush all rules
sudo iptables -F
# If a pre-existing connection exists, allow it
sudo iptables -A INPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A INPUT -p udp -m state --state RELATED,ESTABLISHED -j ACCEPT
# Setup bi-directional ping for this hosts internal address
SERVER_IP="192.168.130.189"
sudo iptables -A INPUT -p icmp --icmp-type 8 -s 0/0 -d $SERVER_IP -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -p icmp --icmp-type 0 -s $SERVER_IP -d 0/0 -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -p icmp --icmp-type 8 -s $SERVER_IP -d 0/0 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -p icmp --icmp-type 0 -s 0/0 -d $SERVER_IP -m state --state ESTABLISHED,RELATED -j ACCEPT
# Accept and send all OpenVPN traffic on the VPN network adapter
sudo iptables -A INPUT -i tun0 -j ACCEPT
sudo iptables -A OUTPUT -o tun0 -j ACCEPT
# Accept and send all traffic on the loopback network adapter
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
# Allow OpenVPN to connect and setup tunnel
sudo iptables -A INPUT -i eth0 -p tcp -m tcp --dport 1194 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -o eth0 -p tcp -m tcp --sport 1194 -m state --state NEW,ESTABLISHED -j ACCEPT
# Comment the following out to prevent access via ssh on the external network adapter once VPN is running
# and has auto-started after a reboot
sudo iptables -A INPUT -i eth0 -p tcp -m tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -o eth0 -p tcp -m tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
# Allow dns to work
sudo iptables -A OUTPUT -p udp -m udp --sport 1024:65535 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp -m tcp --sport 1024:65535 --dport 53 -m state --state NEW,ESTABLISHED -j ACCEPT
# Allow ntp to work
sudo iptables -A OUTPUT -p udp -m udp --sport 1024:65535 --dport 123 -m state --state NEW,ESTABLISHED -j ACCEPT
# Allow access to PostgresSQL from a specific client on the internal network
CLIENT_IP="192.168.165.14"
sudo iptables -A INPUT -p tcp -s $CLIENT_IP --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp -d $CLIENT_IP --sport 5432 -m state --state ESTABLISHED -j ACCEPT
# Drop everything that doesn't match the above
sudo iptables -A INPUT -j DROP
sudo iptables -A FORWARD -j DROP
# Save rules to survive through a reboot
sudo service iptables save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment