Bash scripting/Iptables help
by KrazyKanuk from LinuxQuestions.org on (#5HHTN)
I am creating a bash script that will start on boot of my slackware-current system, which it does. But it is inserting the rules into iptables not in the desired order, and i think this is due to my lack of bash scripting knowledge. Basically I have a WHITELIST variable that is a small list of IP's that I want to be able to connect to the system, that I run through a loop that goes into a second loop to get the service type and protocol and port (ie SSH tcp 22). I am trying to do it this way for the simple fact is if you need to add/remove a WHITELIST IP you simply remove it from the variable and re-run the script. As it is now if I have an IP to add i need to go through every service I have and add a rule for that IP. What I have looks like this:
Code:#!/bin/bash
WHITELIST=(127.0.0.1 192.168.0.0/24 111.222.333.4/24)
SERVICES=(SSH FTP)
do_whitelist() {
for ipaddy in "${WHITELIST[@]}"
do
do_service
done
}
do_service() {
for service in "${SERVICES[@]}"
do
if [ $SERVICES = SSH ]; then
PROTO=tcp
PORT=22
fi
if [ $SERVICES = FTP ]; then
PROTO=tcp
PORT=20
fi
do_${service}
done
}
do_SSH() {
iptables -A INPUT -p $PROTO --dport $PORT -s $ipaddy -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p $PROTP --dport $PORT -m state --state NEW -m recent --set
iptables -A INPUT -p $PROTO --dport $PORT -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j LOG --log-prefix "SSH Packet DROPPED " --log-level 4
}What I want it to do is add the line for every IP in WHITELIST and then add the last 2 lines. What it is doing is adding all 3 lines for the first IP and then starting on second IP and adding the 3 lines for it as well. I am unclear on what I am doing wrong or how to fix it.


Code:#!/bin/bash
WHITELIST=(127.0.0.1 192.168.0.0/24 111.222.333.4/24)
SERVICES=(SSH FTP)
do_whitelist() {
for ipaddy in "${WHITELIST[@]}"
do
do_service
done
}
do_service() {
for service in "${SERVICES[@]}"
do
if [ $SERVICES = SSH ]; then
PROTO=tcp
PORT=22
fi
if [ $SERVICES = FTP ]; then
PROTO=tcp
PORT=20
fi
do_${service}
done
}
do_SSH() {
iptables -A INPUT -p $PROTO --dport $PORT -s $ipaddy -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p $PROTP --dport $PORT -m state --state NEW -m recent --set
iptables -A INPUT -p $PROTO --dport $PORT -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j LOG --log-prefix "SSH Packet DROPPED " --log-level 4
}What I want it to do is add the line for every IP in WHITELIST and then add the last 2 lines. What it is doing is adding all 3 lines for the first IP and then starting on second IP and adding the 3 lines for it as well. I am unclear on what I am doing wrong or how to fix it.