#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-10-11; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: LicenseRef-CNCL-1.1 OR LicenseRef-CCLA-1.1
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.live.builder
# SPDX-Security-Contact: security@coresecret.eu
set -Ceuo pipefail

printf "\e[95m++++ ++++ ++++ ++++ ++++ ++++ ++ 🧪 '%s' starting ... \e[0m\n" "${0}"

declare -r UFW_OUT_POLICY="deny"
declare -r SSHPORT="SSHPORT_MUST_BE_SET"

ufw --force reset

ufw logging medium

ufw default deny incoming

ufw default "${UFW_OUT_POLICY}" outgoing

ufw default deny forward

ufw allow in "${SSHPORT}"/tcp comment 'Incoming SSH (Custom-Port)'

ufw limit "${SSHPORT}"/tcp comment 'Rate-Limit for SSH (Custom-Port)'

if [[ ${UFW_OUT_POLICY,,} == "deny"  ]]; then
  ufw allow out   21/tcp comment 'Outgoing FTP'
  ufw allow out   22/tcp comment 'Outgoing SSH'
  ufw allow out   25/tcp comment 'Outgoing SMTP'
  ufw allow out   53/tcp comment 'Outgoing DNS'
  ufw allow out   80/tcp comment 'Outgoing HTTP'
  ufw allow out  123/tcp comment 'Outgoing NTP'
  ufw allow out  143/tcp comment 'Outgoing IMAP'
  ufw allow out  443/tcp comment 'Outgoing HTTPS'
  ufw allow out  465/tcp comment 'Outgoing SMTPS'
  ufw allow out  587/tcp comment 'Outgoing SMTPS'
  ufw allow out  853/tcp comment 'Outgoing DoT'
  ufw allow out  993/tcp comment 'Outgoing IMAPS'
  ufw allow out 4460/tcp comment 'Outgoing NTS'
  ufw allow out "${SSHPORT}"/tcp comment 'Outgoing SSH (Custom-Port)'
  ufw allow out   53/udp comment 'Outgoing DNS'
  ufw allow out  123/udp comment 'Outgoing NTP'
  ufw allow out  443/udp comment 'Outgoing QUIC'
  ufw allow out  853/udp comment 'Outgoing DoQ'
fi

### Allowing ICMP IPv4 outgoing per default.
sed -i "/# ok icmp code for FORWARD/i \# ok icmp codes for OUTPUT" /etc/ufw/before.rules
sed -i "/# ok icmp code for FORWARD/i \-A ufw-before-output -p icmp --icmp-type destination-unreachable -j ACCEPT" /etc/ufw/before.rules
sed -i "/# ok icmp code for FORWARD/i \-A ufw-before-output -p icmp --icmp-type time-exceeded -j ACCEPT" /etc/ufw/before.rules
sed -i "/# ok icmp code for FORWARD/i \-A ufw-before-output -p icmp --icmp-type parameter-problem -j ACCEPT" /etc/ufw/before.rules
sed -i "/# ok icmp code for FORWARD/i \-A ufw-before-output -p icmp --icmp-type echo-request -j ACCEPT" /etc/ufw/before.rules

sed -i 's/^ENABLED=no/ENABLED=yes/' /etc/ufw/ufw.conf
ln -sf /lib/systemd/system/ufw.service /etc/systemd/system/multi-user.target.wants/ufw.service

printf "\e[92m++++ ++++ ++++ ++++ ++++ ++++ ++ ✅ '%s' applied successfully. \e[0m\n" "${0}"

exit 0
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
