#!/bin/sh
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; ZIMNOL, Andre H.; <git.cs@physnet.eu>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

# Firewall script for Dropbear SSH inside initramfs.
# This script runs at the "init-bottom" stage of the early boot process.
#
# It configures basic iptables rules to restrict SSH access to Dropbear
# while the system is in the pre-boot phase (before root is decrypted).
#
# IPv6 is not supported in initramfs at this stage due to complexity.
# Only trusted IPv4 addresses are allowed.
#
# ┌─────────────────────────────────────────────────────────────┐
# │ ACCESS LOGIC:                                               │
# │                                                             │
# │ - If is_jump_host = true:                                   │
# │     then allow all IPv4 connections to the Dropbear port    │
# │                                                             │
# │ - If is_jump_host = false:                                  │
# │     then allow only the bastion/jump-server IPv4 address    │
# └─────────────────────────────────────────────────────────────┘

PREREQ="dropbear"

prereqs() { echo "$PREREQ"; }

case "$1" in
  prereqs) prereqs; exit 0 ;;
esac

### Check if the firewall is enabled via the config file.
DROPBEAR_FW_CONF="/etc/initramfs-tools/conf.d/dropbear_fw.cnf"
if [ -f "${DROPBEAR_FW_CONF}" ]; then
  # shellcheck disable=SC1090
  . "${DROPBEAR_FW_CONF}"
fi

### Abort if the firewall flag is not set or disabled.
if [ "${DROPBEAR_FIREWALL_ENABLED}" != "1" ]; then
  echo "Dropbear firewall disabled by 'dropbear_fw.cnf'."
  exit 0
fi

### Ensure iptables is available.
if command -v iptables >/dev/null 2>&1; then

  ### Reset any existing rules.
  iptables -F
  iptables -X

  ### Default policy: block everything unless explicitly allowed.
  iptables -P INPUT DROP
  iptables -P FORWARD DROP
  iptables -P OUTPUT ACCEPT

  ### Allow local loopback.
  iptables -A INPUT -i lo -j ACCEPT

  ### Access control based on the host role.
  if [ "${DROPBEAR_BASTION_ENABLE}" = true ]; then

    ### SSH Bastion Host: allow any source IP on the dropbear SSH port.
    iptables -A INPUT -p tcp --dport "${DROPBEAR_PORT}" -j ACCEPT

  else

    ### Infrastructure host / Jump-Server / VPN-Exit-Node: only allow SSH from the specified IPv4.
    iptables -A INPUT -p tcp --dport "${DROPBEAR_PORT}" -s "${DROPBEAR_JUMP_SERVER_IP}" -j ACCEPT
  fi

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