#!/bin/bash

function _Setting() {
    ### Chain Flush
    ${IPTABLES} -F WHITELIST
    ${IPTABLES} -F STRING
    ${IPTABLES} -F SSH
    ${IPTABLES} -F MYSQL
    ${IPTABLES} -F INPUT
    ${IPTABLES} -F FORWARD
    ${IPTABLES} -F OUTPUT
    ### Chain Delete
    ${IPTABLES} -X STRING
    ${IPTABLES} -X WHITELIST
    ${IPTABLES} -X SSH
    ${IPTABLES} -X MYSQL
    ### Chain Create
    ${IPTABLES} -N STRING
    ${IPTABLES} -N WHITELIST
    ${IPTABLES} -N SSH
    ${IPTABLES} -N MYSQL
    ### INPUT Filter
    ${IPTABLES} -A INPUT -j WHITELIST
    ${IPTABLES} -A INPUT -p tcp -m tcp --dport 80 -j STRING
    ${IPTABLES} -A INPUT -p tcp -m tcp --dport 22 -j SSH
    ${IPTABLES} -A INPUT -p tcp -m tcp --dport 3306 -j MYSQL
    ${IPTABLES} -A INPUT -p tcp -m multiport -s 0.0.0.0/0 -d $IPADDR --dport 80,443 -j ACCEPT
    ${IPTABLES} -A INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
    ${IPTABLES} -A INPUT -p udp -m state --state ESTABLISHED,RELATED -j ACCEPT
    ${IPTABLES} -A INPUT -j DROP
    ### SSH   
    ${IPTABLES} -A SSH -s ${IPADDR} -j ACCEPT
    ${IPTABLES} -A SSH -j DROP
    ### MySQL
    ${IPTABLES} -A MYSQL -s ${IPADDR} -j ACCEPT
    ${IPTABLES} -A MYSQL -j DROP
  
    ### Whitelist
    ${IPTABLES} -A WHITELIST -p all -s 127.0.0.1 -j ACCEPT
    ${IPTABLES} -A WHITELIST -p all -s ${IPADDR} -j ACCEPT
  
    ### Customer All Allow
    #${IPTABLES} -A WHITELIST -s [IP] -j ACCEPT
    #### ICMP Drop
    ${IPTABLES} -A OUTPUT -p ICMP -j DROP
    ${IPTABLES} -A OUTPUT -o lo -p tcp --dport 22 -j DROP

    ### String
    ${IPTABLES} -A STRING -m string --string "pma_user" --algo bm --to 65535 -j DROP
    ${IPTABLES} -A STRING -m string --string "wget" --algo bm --to 65535 -j DROP
    # END
    echo "iptables setting end."
}
function _VarCheck() {
    OS_VER=$(cat /etc/redhat-release | head -n 1 | awk -F"." '{print $1}' | awk '{print $NF}')
    CHK_IPTABLES=$(which iptables | awk '{print $2}')
    if [ ${#CHK_IPTABLES} -ne 0 ]
    then
        echo "Check iptables command. (which iptables)"
        exit 0;
    else
        IPTABLES=$(which iptables)
    fi
    if [ ${OS_VER} -eq 5 -o ${OS_VER} -eq 6 ]
    then
        IPADDR=$(ifconfig -a | egrep "inet" | egrep -v "inet6|127.0.0.1" | awk -F":" '{print $2}' | awk '{print $1}' | head -n 1)
    elif [ ${OS_VER} -eq 7 ]
    then
        IPADDR=$(ifconfig -a | egrep "inet" | egrep -v "inet6|127.0.0.1" | awk '{print $2}' | head -n 1)
    else
        echo "Could not determine os version."
        exit 0;
    fi
}
function _Fail2ban() {
    CHK_FAIL2=$(rpm -qa | egrep -c fail2ban)
    if [ ${CHK_FAIL2} -ne 0 ]
    then
        echo "fail2ban restart."
        if [ ${OS_VER} -eq 5 -o ${OS_VER} -eq 6 ]
        then
            /etc/init.d/fail2ban restart
        elif [ ${OS_VER} -eq 7 ]
        then
            systemctl restart fail2ban
        fi
    else
        echo "fail2ban not installed."
    fi
}
function _Main() {
    _VarCheck
    _Setting
    _Fail2ban
}
_Main