#!/bin/bash

source /etc/profile
iptable_shell=/etc/firewalld/iptables_security.sh
telnet_port=`awk '/port / {print $2}' /etc/telnetd.conf`
[ -z "$telnet_port" ] && telnet_port=23
only_local=/etc/ssh/sshd_extend
chain_list="
FORWARD_FIREWALL
INPUT_FIREWALL
INPUT_PROTECT
"

get_ssh_port(){
    local ports=`awk '/^Port / {print $2}' /etc/ssh/sshd_config 2>/dev/null`
    for port in $ports
    do
        if [ ! -z "$port" ]; then
            echo $port
            return 0
        fi
    done
    return 1
}
ssh_port=`get_ssh_port`

clean_iptable(){
    iptables -P INPUT ACCEPT
    iptables -P FORWARD ACCEPT
    for chain in $chain_list; do
        local enter="INPUT"
        [ "$chain" = "FORWARD_FIREWALL" ] && enter="FORWARD"
        iptables -D $enter -p all -j $chain > /dev/null 2>&1
        iptables -F $chain
        iptables -X $chain
    done
}

only_local_stat(){
    if [ ! -e $only_local ]; then
        echo 1
        return 0
    fi
    local content=`awk -F= '/only_local/ {print $2}' $only_local`
    if [ -z "$content" ]; then
        echo 1
        return 0
    fi
    echo $content
    return 0
}

system_protected(){
	local onlystat=`only_local_stat`
	if [ "$onlystat" = "1" ]; then
		iptables -L -n | grep 'Chain INPUT_PROTECT' > /dev/null
		[ $? -ne 0 ] && iptables -N INPUT_PROTECT
		iptables -F INPUT_PROTECT
		local ret=`iptables -C INPUT -p all -j INPUT_PROTECT 2>&1`
		echo "$ret" | grep "No chain/target/match" > /dev/null
		[ $? -eq 0 ] && iptables -A INPUT -p all -j INPUT_PROTECT
		route -n | grep -v UG | grep -v Destination | grep -v Kernel | while read line
		do
			local ip=`echo $line | awk '{print $1}'`
			local mask=`echo $line | awk '{print $3}'`
            [ "$ip" = "239.0.0.0" ] && continue
			local subnet=`masksum $ip $mask`
			iptables -A INPUT_PROTECT -p tcp -s $subnet -m tcp --dport $ssh_port -j ACCEPT
			iptables -A INPUT_PROTECT -p tcp -s $subnet -m tcp --dport $telnet_port -j ACCEPT
		done
		iptables -A INPUT_PROTECT -p tcp -m tcp --dport $ssh_port -j DROP
		iptables -A INPUT_PROTECT -p tcp -m tcp --dport $telnet_port -j DROP
	fi
}

case $1 in
    start)
        system_protected
        $iptable_shell
        exit 0 ;;
    stop)     
        clean_iptable
        exit 0 ;;
    restart)
        clean_iptable
        system_protected
        $iptable_shell
        exit 0 ;;
    *)                                                  
        echo "Usage: `basename $0` {start|stop|restart}"
        exit 1 ;;
esac
