#!/bin/sh
# Allow OpenVPN traffic.
# © 2012, Multapplied Networks, Inc.

NAME="40_openvpn"
INPUT_CHAIN="allow_openvpn"
. /usr/share/bondingadmin/default/openvpn-vars
test -f /etc/default/bondingadmin/openvpn && . /etc/default/bondingadmin/openvpn
test -f /etc/default/firewall.d/40_openvpn && . /etc/default/firewall.d/40_openvpn

iptables_4() {
    iptables "$@"
}


iptables_6() {
    ip6tables "$@"
}


iptables_all() {
    iptables "$@"
    ip6tables "$@"
}


start () {
    log_progress_msg $NAME

    remove 2> /dev/null # Remove first to avoid duplicate rules

    # Incoming to mgmt server
    iptables_all -N $INPUT_CHAIN
    iptables_all -A $INPUT_CHAIN -p udp --dport $PORT -j ACCEPT # OpenVPN client UDP traffic

    iptables_4 -A $INPUT_CHAIN -i $TUN_NAME -d $SERVER_IP -j ACCEPT # Incoming tunneled traffic from nodes to mgmt server
    iptables_6 -A $INPUT_CHAIN -i $TUN_NAME -d $SERVER_IP6 -j ACCEPT # Incoming tunneled traffic from nodes to mgmt server

    iptables_all -A INPUT -j $INPUT_CHAIN

    # Forward traffic from remote hosts going to nodes through OpenVPN
    iptables_all -I FORWARD -i $TUN_NAME -o $TUN_NAME -j DROP
    # And NAT it to mgmt OpenVPN IP so that responses from nodes get routed back here
    iptables_4 -I POSTROUTING -t nat -o $TUN_NAME ! -s $SERVER_NETWORK/$SERVER_NETMASK -j SNAT --to-source $SERVER_IP
}
stop () {
    log_progress_msg $NAME
    remove
}
remove () {
    iptables_4 -D POSTROUTING -t nat -o $TUN_NAME ! -s $SERVER_NETWORK/$SERVER_NETMASK -j SNAT --to-source $SERVER_IP
    iptables_all -D FORWARD -i $TUN_NAME -o $TUN_NAME -j DROP

    iptables_all -D INPUT -j $INPUT_CHAIN
    iptables_all -F $INPUT_CHAIN
    iptables_all -X $INPUT_CHAIN

    # LEGACY-LAST-VERSION: 2015.4
    # Remove rules added in 2015.3 and no longer used. By the time an admin runs
    # "service firewall restart", this script will already have been upgraded
    # to 2015.4, so we have to handle those 2015.3 rules here until all mgmt
    # servers are upgraded to 2015.4.
    iptables_4 -D INPUT -p udp --dport $PORT -j ACCEPT >/dev/null 2>&1 || true
    iptables_4 -D INPUT -i $TUN_NAME -d $SERVER_IP -j ACCEPT >/dev/null 2>&1 || true
}
status () {
    iptables -L -nv
}

test -f /lib/lsb/init-functions && . /lib/lsb/init-functions

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|force-reload)
        stop
        start
        ;;
    status)
        status
        exit 0
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
        ;;
esac
