Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Created December 11, 2015 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarymartin/9535c886e6e362d7fdbe to your computer and use it in GitHub Desktop.
Save mrgarymartin/9535c886e6e362d7fdbe to your computer and use it in GitHub Desktop.
Lockdown IPTables to all traffic Expect STATIC IPs.
#!/usr/bin/env bash
## Author: Gary Martin
##
## Usage ./lockdown.sh {IPADDRESS} {IPADDRESS2}
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
return 0
else
return 1
fi
}
IP1=${1?param missing - IP Address. Usage: lockdown.sh IPADDRESS IPADDRESS2};
read -r -p "Are You Sure? [Y/n] " input
case $input in
[yY][eE][sS]|[yY])
echo ""
;;
[nN][oO]|[nN])
echo "Exiting"
exit 1
;;
*)
echo "Invalid input. Select Y or N"
exit 1
;;
esac
if valid_ip $IP1 ;
then
echo "IP is Valid at $IP1"
else
echo "IP Address not valid."
exit 1
fi
## Starting IPTABLE RULES
#Delete Existing Rules
iptables -F
#Set Default Chain Policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
for var in "$@"
do
if valid_ip $var ;
then
echo "Allowing INPUT for ports: 21,22,25,53,80,110,143,3306,443 on $var"
iptables -A INPUT -i eth0 -p tcp -s ${var}/32 -m multiport --dports 21,22,25,53,80,110,143,3306,443 -m state --state NEW,ESTABLISHED -j ACCEPT
else
echo "$var Address not valid."
fi
done
## remaining RULES
echo "Adding remaining IP rules"
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 21,22,25,53,80,110,143,3306,443 -m state --state ESTABLISHED -j ACCEPT
#Allow Ping from Outside to Inside
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT
#Allow Ping from Inside to Outside
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
#Allow Loopback Access
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
#Allow Internal Network to External network.
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment