#!/bin/bash -e
# vim: set ts=4 sw=4 sts=4 et :
#
# enable-firewall - Called by systemd to setup a proper firewall for
#                   Whonix-Gateway or Whonix-Workstation.
#
# This file is part of Qubes+Whonix.
# Copyright (C) 2014 - 2015 Jason Mehring <nrgaway@gmail.com>
# Copyright (C) 2014 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
# License: GPL-2+
# Authors: Jason Mehring
# Authors: Patrick Schleizer
#
#   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/>.

#### meta start
#### project Whonix
#### category networking and firewall
#### description
## Wrapper to start firewall and create failure status files on failure.
#### meta end

[ -n "$nftables_cmd" ] || nftables_cmd="nft"

failed_status_file_create() {
  mkdir -p /run/anon-firewall || true
  touch /run/anon-firewall/failed.status || true

  ## Legacy.
  ## mkdir should not be required for Qubes-Whonix, just as a defensive action.
  ## mkdir is required for simpler Non-Qubes-Whonix code.
  mkdir -p /run/qubes-service || true
  touch /run/qubes-service/whonix-firewall-failed || true
}

firewall_lockdown() {
  $nftables_cmd add table inet nat
  $nftables_cmd add table inet filter

  ## Flush old rules.
  $nftables_cmd flush table inet nat
  $nftables_cmd flush table inet filter

  ## Set secure defaults.
  $nftables_cmd "add chain inet filter input { type filter hook input priority 0; policy drop; }"
  $nftables_cmd "add chain inet filter forward { type filter hook forward priority 0; policy drop; }"
  $nftables_cmd "add chain inet filter output { type filter hook output priority 0; policy drop; }"
}

on_failure() {
  failed_status_file_create
  firewall_lockdown || true
  exit 1
}

if [ -e /usr/share/anon-gw-base-files/gateway ] || [ -e /usr/share/anon-ws-base-files/workstation ]; then
  /usr/bin/whonix_firewall || on_failure
else
  on_failure
fi
