#!/bin/bash
# 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; WEIDNER, Marc S.; <msw@coresecret.dev>
# 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
# SPDX-Comment: SSH-Hardening Integrity Check (Centurion SSH Audit Support)

set -Ceuo pipefail
IFS=$'\n\t'

declare -r REF_CONFIG="/path/to/includes/etc/ssh/sshd_config"
declare -r LIVE_CONFIG="/etc/ssh/sshd_config"
declare -r REF_SSHD_T="/path/to/includes/etc/ssh/sshd_config.sshdT"

hash_file() {
  sha256sum "$1" | awk '{print $1}'
}

bold()  { tput bold; echo "$1"; tput sgr0; }
red()   { tput setaf 1; echo "$1"; tput sgr0; }
green() { tput setaf 2; echo "$1"; tput sgr0; }

echo
bold "🛡️  Checking SSH Configuration Integrity..."

if [[ ! -f "${REF_CONFIG}" ]]; then
  red "ERROR: Reference config '${REF_CONFIG}' not found."
  exit 1
fi

if [[ ! -f "${LIVE_CONFIG}" ]]; then
  red "ERROR: Live config '${LIVE_CONFIG}' not found."
  exit 1
fi

declare -r HASH_REF=$(hash_file "${REF_CONFIG}")
declare -r HASH_LIVE=$(hash_file "${LIVE_CONFIG}")

if [[ "${HASH_REF}" == "${HASH_LIVE}" ]]; then
  green "✓ sshd_config matches reference (SHA256: ${HASH_LIVE})"
else
  red "✗ sshd_config has been modified!"
  diff -u "${REF_CONFIG}" "${LIVE_CONFIG}" || true
fi

# Vergleich der sshd -T Ausgabe
echo
bold "🔍 Verifying sshd -T output..."

if [[ ! -f "${REF_SSHD_T}" ]]; then
  red "ERROR: Reference sshd -T output not found: '${REF_SSHD_T}'"
  exit 1
fi

TMP_SSHD_T=$(mktemp)
sshd -T > "${TMP_SSHD_T}"

if diff -q "${TMP_SSHD_T}" "${REF_SSHD_T}" >/dev/null; then
  green "✓ sshd -T output matches expected configuration."
else
  red "✗ sshd -T output has changed:"
  diff -u "${REF_SSHD_T}" "${TMP_SSHD_T}" || true
fi

rm -f "${TMP_SSHD_T}"
echo
bold "✔ SSH config integrity check completed."
exit 0
