#!/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

guard_sourcing

#######################################
# Setup ssh server.
# Globals:
#   BASH_REMATCH
#   DIR_BAK
#   DIR_LOG
#   TARGET
#   VAR_FINAL_FQDN
#   VAR_FINAL_IPV4
#   VAR_FINAL_IPV6
#   VAR_SETUP_PATH
#   ssh_port
#   ssh_root_ca
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
installation_ssh() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -a ary_user=()
  declare -i i=0
  declare    var_auth="" var_name="" var_ca=""

  do_in_target "${TARGET}" apt-get install -y --no-install-recommends --no-install-suggests ssh

  install -D -m 0644 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/banner" "${TARGET}/etc/"
  install -D -m 0644 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/motd" "${TARGET}/etc/"
  do_log "info" "file_only" "4420() Installed SSH '/etc/banner' and '/etc/motd'."

  ### Only process those for which both *_name and *_authentication_access_ssh are set.
  for ((i = 0; i <= VAR_USER_MAX; i++)); do
    var_auth="user_user${i}_authentication_access_ssh"
    var_name="user_user${i}_name"

    if [[ -v "${var_auth}" && -v "${var_name}" && "${!var_auth}" == "true" ]]; then
      ary_user+=("${!var_name}")
    fi
  done

  rm -rf "${TARGET}"/etc/ssh/ssh_host_*key*

  #shellcheck disable=SC2312
  do_in_target "${TARGET}" ssh-keygen -o -N "" -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -C "root@${VAR_FINAL_FQDN}-$(date -I)"
  #shellcheck disable=SC2312
  do_in_target "${TARGET}" ssh-keygen -o -N "" -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -C "root@${VAR_FINAL_FQDN}-$(date -I)"

  mkdir -p "${TARGET}/root/.ciss/cdi/backup/etc/ssh"
  cp "${TARGET}/etc/ssh/sshd_config" "${TARGET}/root/.ciss/cdi/backup/etc/ssh/sshd_config.bak"
  cp "${TARGET}/etc/ssh/ssh_config" "${TARGET}/root/.ciss/cdi/backup/etc/ssh/ssh_config.bak"
  rm -f "${TARGET}/etc/ssh/sshd_config"

  install -D -m 0600 -o root -g root "${VAR_SETUP_PATH}/includes/target/etc/ssh/sshd_config" "${TARGET}/etc/ssh/sshd_config"
  chmod 0600 "${TARGET}/etc/ssh/ssh_config"

  insert_comments "${TARGET}/etc/ssh/sshd_config"

  # shellcheck disable=SC2153
  sed -i -E "s|^[[:space:]]*ListenAddressIPV4[[:space:]]+.*$|$(printf '%-29s%s' 'ListenAddress' "${VAR_FINAL_IPV4}")|" "${TARGET}/etc/ssh/sshd_config"

  if [[ -n "${VAR_FINAL_IPV6}" ]]; then
    sed -i -E "s|^[[:space:]]*ListenAddressIPV6[[:space:]]+.*$|$(printf '%-29s%s' 'ListenAddress' "${VAR_FINAL_IPV6}")|" "${TARGET}/etc/ssh/sshd_config"
  else
    sed -i "/^[[:space:]]*ListenAddressIPV6[[:space:]]*/d" "${TARGET}/etc/ssh/sshd_config"
  fi

  sed -i -E "s|^[[:space:]]*Port[[:space:]]+.*$|$(printf '%-29s%s' 'Port' "${ssh_port}")|" "${TARGET}/etc/ssh/sshd_config"

  if (( ${#ary_user[@]} > 0 )); then
    sed -i -E "s|^\s*AllowUsers\s+.*$|$(printf '%-29s%s' 'AllowUsers' "root ${ary_user[*]}")|" "${TARGET}/etc/ssh/sshd_config"
  fi

  if [[ -n "${ssh_root_ca}" ]]; then
    var_ca="${ssh_root_ca##*/}"
    install -D -m 0644 -o root -g root "${VAR_SETUP_PATH}${ssh_root_ca}" "${TARGET}/etc/ssh/"
    sed -i -E "s|^\s*TrustedUserCAKeys\s+.*$|$(printf '%-29s%s' 'TrustedUserCAKeys' "/etc/ssh/${var_ca}")|" "${TARGET}/etc/ssh/sshd_config"
  fi

  ### Preparing the test environment in chroot.
  do_in_target "${TARGET}" install -d -o root -g root -m 0755 /run/sshd

  ### Syntax test (hard).
  if ! do_in_target_script "${TARGET}" "sshd -t -f /etc/ssh/sshd_config"; then
    do_log "emergency" "file_only" "4420() [sshd -t -f /etc/ssh/sshd_config] failed."
    return "${ERR_CONF_VALIDATION}"
  fi

  ### Effective configuration (soft, purely informative).
  if ! do_in_target_script "${TARGET}" "sshd -T -f /etc/ssh/sshd_config >| /root/.ciss/cdi/log/sshd_config.log"; then
    do_log "warn" "file_only" "4420() [sshd -T -f /etc/ssh/sshd_config] failed. Likely env. Continuing."
  fi

  do_in_target_script "${TARGET}" "ssh-keygen -r ${VAR_FINAL_FQDN}. >| /root/.ciss/cdi/log/SSHFP.log"

  ###########################################################################################
  # The file /etc/profile.d/idle-users.sh is created to set the read-only                   #
  # environment variables: TMOUT                                                            #
  # TMOUT=14400 ensures that users are automatically logged out after 4 hours of inactivity.#
  ###########################################################################################
  cat << EOF >| "${TARGET}/etc/profile.d/idle-users.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; 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

# Static file system information: /etc/profile.d/idle-users.sh
# Generated by CISS.debian.installer ${VAR_VERSION}
# Architecture: ${VAR_ARCHITECTURE}
# Distribution: ${VAR_CODENAME}

EOF
  cat << 'EOF' >> "${TARGET}/etc/profile.d/idle-users.sh"
case $- in
  *i*)
    TMOUT=14400
    export TMOUT
    readonly TMOUT
  ;;
esac

# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
EOF
  chmod 0644 "${TARGET}/etc/profile.d/idle-users.sh"
  insert_comments "${TARGET}/etc/profile.d/idle-users.sh"

  guard_dir && return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
