#!/bin/bash
# info: add firewall chain
# options: CHAIN [PORT] [PROTOCOL] [PROTOCOL]
#
# The function adds new rule to system firewall


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Importing system variables
source /etc/profile

# Argument definition
chain=$(echo $1 | tr '[:lower:]' '[:upper:]')
port=$2
protocol=${4-TCP}
protocol=$(echo $protocol|tr '[:lower:]' '[:upper:]')

# Defining absolute path to iptables
iptables="/sbin/iptables"

# Get vesta port by reading nginx.conf
vestaport=$(grep 'listen' $VESTA/nginx/conf/nginx.conf | awk '{print $2}' | sed "s|;||")
if [ -z "$vestaport" ]; then
    vestaport=8083
fi

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '1' "$#" 'CHAIN [PORT] [PROTOCOL]'
is_format_valid 'chain'
is_system_enabled "$FIREWALL_SYSTEM" 'FIREWALL_SYSTEM'


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Checking known chains
case $chain in
    SSH)        # Get ssh port by reading ssh config file.
                sshport=$(grep '^Port ' /etc/ssh/sshd_config | head -1 | cut -d ' ' -f 2)
                if [ -z "$sshport" ]; then
                    sshport=22
                fi
                port=$sshport; 
                protocol=TCP ;;
    FTP)        port=21; protocol=TCP  ;;
    MAIL)       port='25,465,587,2525,110,995,143,993'; protocol=TCP  ;;
    DNS)        port=53; protocol=UDP  ;;
    WEB)        port='80,443'; protocol=TCP  ;;
    DB)         port='3306,5432'; protocol=TCP  ;;
    VESTA)      port=$vestaport; protocol=TCP  ;;
    *)          check_args '2' "$#" 'CHAIN PORT' ;;
esac

# Adding chain
$iptables -N fail2ban-$chain 2>/dev/null
if [ $? -eq 0 ]; then
    $iptables -A fail2ban-$chain -j RETURN

    # Adding multiport module
    if [[ "$port" =~ ,|-|: ]] ; then
        port_str="-m multiport --dports $port"
    else
        port_str="--dport $port"
    fi
    $iptables -I INPUT -p $protocol $port_str -j fail2ban-$chain
fi

# Preserving chain
chains=$VESTA/data/firewall/chains.conf
check_chain=$(grep "CHAIN='$chain'" $chains 2>/dev/null)
if [ -z "$check_chain" ]; then
    echo "CHAIN='$chain' PORT='$port' PROTOCOL='$protocol'" >> $chains
fi

# Changing permissions
chmod 660 $chains


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Logging
log_event "$OK" "$ARGUMENTS"

exit
