#!/bin/bash
# vim: set ts=4 sw=4 sts=4 et :
#
# enable-firewall - Called by systemd to setup a proper firewall for Whonix
#                   gateway, workstation or template
#
# This file is part of Qubes+Whonix.
# Copyright (C) 2014 - 2015 Jason Mehring <nrgaway@gmail.com>
# License: GPL-2+
# Authors: Jason Mehring
#
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the GNU General Public License
#   as published by the Free Software Foundation; either version 2
#   of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

source /usr/lib/qubes-whonix/utility_functions.sh

[ -n "$iptables_cmd" ] || iptables_cmd="iptables --wait"
[ -n "$ip6tables_cmd" ] || ip6tables_cmd="ip6tables --wait"

# Gateway or Workstation
if [ -e /var/run/qubes-service/whonix-gateway ] || [ -e /var/run/qubes-service/whonix-workstation ]; then

    # Gateway: Set interfaces for Whonix firewall
    if [ -e /var/run/qubes-service/whonix-gateway ]; then
        export INT_IF="vif+"
        export INT_TIF="vif+"
    fi

    # Load the Whonix firewall
    /usr/bin/whonix_firewall || touch /var/run/qubes-service/whonix-firewall-failed

# Template
elif [ -e /var/run/qubes-service/whonix-template ]; then

    # Check if a secure Tor update server is available
    if [ ! -e /var/run/qubes-service/whonix-secure-proxy ]; then
        curl.anondist-orig --connect-timeout 3 "${PROXY_SERVER}" | grep -q "${PROXY_META}" && {
            sudo touch /var/run/qubes-service/whonix-secure-proxy
        }
    fi

else
    touch /var/run/qubes-service/whonix-firewall-failed
fi

# Something is not right; lock down networking.  User will be notified
if [ -e /var/run/qubes-service/whonix-firewall-failed ]; then

    # Set secure defaults.
    $iptables_cmd -P INPUT DROP
    $iptables_cmd -P FORWARD DROP
    $iptables_cmd -P OUTPUT DROP

    # Flush old rules.
    $iptables_cmd -F
    $iptables_cmd -X
    $iptables_cmd -t nat -F
    $iptables_cmd -t nat -X
    $iptables_cmd -t mangle -F
    $iptables_cmd -t mangle -X
fi

exit 0
