shell script to generate iptables with whitelist ip's
The following is a simple IPTables firewall script to allow particular ip or domain and block all others
********************************
Step 1 : Creating whitelist file
********************************
mkdir /usr/src/firewall
touch /usr/src/firewall/whitelist.txt
********************************
Step 2 : Enter the allowed ip & domain in whitelist.txt
********************************
vi /usr/src/firewall/whitelist.txt
1.1.1.1
2.2.2.2
3.3.3.3
save and exit
********************************
Step 3 : Locate where the iptables located
********************************
type the below command
which iptables
which iptables-save
it will outputs as below
/sbin/iptables
/sbin/iptables-save
********************************
Step 4 : Script
********************************
vi /usr/src/firewall/firewall.sh
copy and paste the below script
#!/bin/bash
# allowed ip file location
WHITELIST=/usr/src/firewall/whitelist.txt
#
## Specify where IP Tables is located
#
IPTABLES=/sbin/iptables
IPTABLES_SAVE=/sbin/iptables-save
#
## Save current iptables running configuration in case we want to revert back
## To restore using our example we would run "/sbin/iptables-restore < /usr/src/iptables.last"
#
$IPTABLES_SAVE > /usr/src/iptables.last
#
## Clear current rules
#
##If current INPUT policy is set to DROP we will be locked out once we flush the rules
## so we must first ensure it is set to ACCEPT.
#
$IPTABLES -P INPUT ACCEPT
echo 'Setting default INPUT policy to ACCEPT'
$IPTABLES -F
echo 'Clearing Tables F'
$IPTABLES -X
echo 'Clearing Tables X'
$IPTABLES -Z
echo 'Clearing Tables Z'
#Always allow localhost.
echo 'Allowing Localhost'
$IPTABLES -A INPUT -s 127.0.0.1 -j ACCEPT
$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#
## Whitelist
#
for x in `grep -v ^# $WHITELIST | awk '{print $1}'`; do
echo "Permitting $x..."
$IPTABLES -A INPUT -s $x -j ACCEPT
done
# block all other traffice
$IPTABLES -A INPUT -p all -j DROP
#
## Save the rules so they are persistent on reboot.
#
/etc/init.d/iptables save
********************************
note: replace the IPTABLES= value to the output of the step 3
********************************
********************************
Step 5 : making the firewall.sh as executable.
********************************
chmod +x /usr/src/firewall/firewall.sh
********************************
Step 6 : run the scritp
********************************
/usr/src/firewall/firewall.sh
********************************
Step 6 : check the iptables rules
********************************
iptables -L -n
********************************
Also see:
Installing Fail2ban to protect asterisk ClickHere
Script to block ssh attack automatically ClickHere
Also see:
Installing Fail2ban to protect asterisk ClickHere
Script to block ssh attack automatically ClickHere
For support contact skype :striker24x7