#!/usr/bin/bash

readonly OVPN_ARP_CHAIN="ovpn_INPUT"
readonly OVPN_PREROUTING_CHAIN="ovpn_PREROUTING"

function ifaces_all() {
    ifconfig -s | grep --invert-match -w Iface | awk '{print $1}' | grep --invert-match -w lo
}

function ifaces_not_tun() {
    ifaces_all | grep --invert-match tun
}

function ifaces_tun() {
    ifaces_all | grep tun
}

function tun_ips() {
    for TUN_IFACE in $(ifaces_tun); do
        local IP=$(ifconfig ${TUN_IFACE} | grep -w inet | awk '{print $2}')
        if [ z"${IP}" != z"" ]; then
            echo ${IP}
        fi
    done
}

function arp_protector() {
    #
    #	Clean and delete OVPN chain
    #
    arptables -D INPUT -j ${OVPN_ARP_CHAIN}
    arptables -F ${OVPN_ARP_CHAIN}
    arptables -X ${OVPN_ARP_CHAIN}
    
    
    if [ z"${TUN_IPS}" != z"" ]; then
        #
        #	Create OVPN chain
        #
        arptables -N ${OVPN_ARP_CHAIN}
        
        #
        #	Add rules to disable ARP'ing by local interfaces
        #
        for IFACE in ${IFACES}; do
            for TUN_IP in ${TUN_IPS}; do
                arptables -A ${OVPN_ARP_CHAIN} -i ${IFACE} -d ${TUN_IP} -j DROP
            done
        done
        
        #
        #	Connect OVPN chain to INPUT
        #
        arptables -A INPUT -j ${OVPN_ARP_CHAIN}
    fi
    
}

function cve_2019_14899_protector() {
    #
    #	Clean and delete OVPN chain
    #
    iptables -t raw -D PREROUTING -j ${OVPN_PREROUTING_CHAIN}
    iptables -t raw -F ${OVPN_PREROUTING_CHAIN}
    iptables -t raw -X ${OVPN_PREROUTING_CHAIN}
    
    if [ z"${TUN_IPS}" != z"" ]; then
        #
        #	Create OVPN chain
        #
        iptables -t raw -N ${OVPN_PREROUTING_CHAIN}
        
        #
        #	Add rules to disable ARP'ing by local interfaces
        #
        for IFACE in ${IFACES}; do
            for TUN_IP in ${TUN_IPS}; do
                iptables -t raw -I ${OVPN_PREROUTING_CHAIN} -i ${IFACE} -d ${TUN_IP}  -j DROP
            done
        done
        
        #
        #	Connect OVPN chain to RAW::PREROUTING
        #
        iptables -t raw -A PREROUTING -j ${OVPN_PREROUTING_CHAIN}
    fi
    
}

#
#	Collect information to create rules
#

TUN_IPS=$(tun_ips)
IFACES=$(ifaces_not_tun)

#
#	Set ARP rules
#
arp_protector

#
#	Protect against CVE-2019-14899
#
cve_2019_14899_protector