#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-11-12; 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
# SPDX-Comment: unlock_wrapper.sh to be executed as 'dropbear-initramfs' SSH forced command.
# shellcheck disable=SC2034

set -Ceu -o pipefail -o ignoreeof
shopt -s failglob
shopt -s lastpipe
shopt -u nullglob
umask 0077
declare -g PATH="/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr"

### Will be replaced at build time:
declare -gr CDLB_DB_EXP_FPR="@EXP_FPR@"
declare -gr CDLB_DB_EXP_CA_FPR="@EXP_CA_FPR@"
declare -gr CDLB_MAPPER_NAME="crypt_liveiso"
declare -gr CDLB_MAPPER_DEV="/dev/mapper/${CDLB_MAPPER_NAME}"

#######################################
# Variable declaration
#######################################
# shellcheck disable=SC2016
declare -r REGEX='^\$6\$(rounds=([1-9][0-9]{3,8})\$)?([./A-Za-z0-9]{1,16})\$([./A-Za-z0-9]{86})$'
# shellcheck disable=SC2155
declare -r CURRENTDATE=$(date +"%F %T")
declare -g ERRTRAP='false'
declare -r GRE='\e[0;92m'
declare -r MAG='\e[0;95m'
declare -r RED='\e[0;91m'
declare -r RES='\e[0m'
declare -r NL='\n'
declare -g PASSPHRASE=''

#######################################
# Read passphrase strictly from STDIN (SSH channel), not '/dev/console'.
# Arguments:
#   1: Prompt to print on terminal
#   2: Variable name to capture passphrase
#######################################
ask_via_stdin() {
  declare -r  prompt="$1"
  declare -r  varname="$2"
  ### Prompt to STDERR so pipes don't capture it.
  printf "%s" "${prompt}" >&2
  ### Silent, canonical read from FD 0 (SSH channel when forced-command).
  IFS= read -r -s "${varname?}" <&0
  printf "\n" >&2
  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f ask_via_stdin

#######################################
# Printed text in color.
# Arguments:
#   1: Color code.
#   *: Text to print.
#######################################
color_echo() { declare c="${1}"; shift; declare msg="${*}"; printf "%b%s %b%b" "${c}" "${msg}" "${RES}" "${NL}"; return 0; }
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f color_echo

#######################################
# Die Helper: print and then exit hard.
# Globals:
#   NC
#   RED
# Arguments:
#   1: Message string to print.
#######################################
die() { printf "%b✘ %s %b%b" "${RED}" "$1" "${RES}" "${NL}" >&2; power_off 3; }
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f die

#######################################
# Drop into the bash environment.
# Arguments:
#   None
#######################################
drop_bash() { stty echo 2>/dev/null || true; prompt_string; exec /bin/bash -i; }
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f drop_bash

#######################################
# Unified power-off routine.
# Arguments:
#   1: Sleep time before power-off in seconds (Default to 0 seconds).
#######################################
power_off() {
  declare -r  wait="${1:-0}"
  sleep "${wait}"
  sync
  echo 1 >| /proc/sys/kernel/sysrq
  echo o >| /proc/sysrq-trigger
  ### The System powers off immediately; no further code is executed.
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f power_off

#######################################
# Print Error Message for Trap on 'ERR' on Terminal.
# Globals:
#   NL
#   RED
# Arguments:
#   1: ${?}
#   2: ${BASH_SOURCE[0]}
#   3: ${LINENO}
#   4: ${FUNCNAME[0]:-main}
#   5: ${BASH_COMMAND}
#######################################
print_scr_err() {
  declare -r  scr_err_errcode="$1"
  declare -r  scr_err_errscrt="$2"
  declare -r  scr_err_errline="$3"
  declare -r  scr_err_errfunc="$4"
  declare -r  scr_err_errcmmd="$5"

  printf "%b" "${NL}" >&2

  color_echo "${RED}" "✘ System caught an 'ERROR'. System Power Off in 16 seconds." >&2
  printf "%b" "${NL}" >&2
  color_echo "${RED}" "✘ Error               : [${scr_err_errcode}]" >&2
  color_echo "${RED}" "✘ Line                : [${scr_err_errline}]" >&2
  color_echo "${RED}" "✘ Script              : [${scr_err_errscrt}]" >&2
  color_echo "${RED}" "✘ Function            : [${scr_err_errfunc}]" >&2
  color_echo "${RED}" "✘ Command             : [${scr_err_errcmmd}]" >&2
  printf "%b" "${NL}" >&2

  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f print_scr_err

#######################################
# Print Error Message for '0'-Exit-Code on Terminal.
# Globals:
#   GRE
# Arguments:
#   None
#######################################
print_scr_scc() { color_echo "${GRE}" "✅ Script exited successfully. Proceeding with booting."; sleep 3; }
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f print_scr_scc

#######################################
# Generates an informative shell prompt.
# Globals:
#   PS1
# Arguments:
#   None
#######################################
prompt_string() {
  declare -gx PS1="\
\[\033[1;91m\]\d\[\033[0m\]|\[\033[1;91m\]\u\[\033[0m\]@\
\[\033[1;95m\]\h\[\033[0m\]:\
\[\033[1;96m\]\w\[\033[0m\]/>>\
\$(if [[ \$? -eq 0 ]]; then \
  # Show exit status in green if zero
  echo -e \"\[\033[1;92m\]\$?\[\033[0m\]\"; \
else \
  # Show exit status in red otherwise
  echo -e \"\[\033[1;91m\]\$?\[\033[0m\]\"; \
fi)\
|~\$ "
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f prompt_string

#######################################
# Read the passphrase interactively.
# Globals:
#   PASSPHRASE
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
read_passphrase() {
  ### Read from SSH STDIN (or TTY fallback), never via '/lib/cryptsetup/askpass'.
  ask_via_stdin "Enter passphrase: " PASSPHRASE
  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f read_passphrase

#######################################
# Securely unset the 'PASSPHRASE'-variable.
# Globals:
#   PASSPHRASE
# Arguments:
#   None
#######################################
secure_unset_pass() { unset PASSPHRASE; PASSPHRASE=""; return 0; }
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f secure_unset_pass

#######################################
# Trap function to be called on 'ERR'.
# Arguments:
#   1: ${?}
#   2: ${BASH_SOURCE[0]}
#   3: ${LINENO}
#   4: ${FUNCNAME[0]:-main}
#   5: ${BASH_COMMAND}
#######################################
trap_on_err() {
  declare -r  errcode="$1"
  declare -r  errscrt="$2"
  declare -r  errline="$3"
  declare -r  errfunc="$4"
  declare -r  errcmmd="$5"
  declare -g  ERRTRAP='true'

  trap - ERR INT TERM
  stty echo 2>/dev/null || true
  print_scr_err "${errcode}" "${errscrt}" "${errline}" "${errfunc}" "${errcmmd}"
  power_off 16
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f trap_on_err

#######################################
# Security Trap on 'EXIT'.
# Globals:
#   ERRTRAP
# Arguments:
#   None
#######################################
trap_on_exit() {
  trap - ERR EXIT INT TERM
  [[ "${ERRTRAP,,}" == "false" ]] && print_scr_scc
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f trap_on_exit

#######################################
# Security Trap on 'INT' and 'TERM' to provide a deterministic way to not circumvent the nuke routine.
# Globals:
#   NL
#   RED
# Arguments:
#   None
#######################################
trap_on_term() {
  trap - ERR INT TERM
  stty echo 2>/dev/null || true
  printf "%b" "${NL}"
  color_echo "${RED}" "✘ Received termination signal. System Power Off in 3 seconds."
  power_off 3
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f trap_on_term

#######################################
# Check the integrity and authenticity of this script itself.
# Globals:
#   GRE
#   MAG
#   RED
# Arguments:
#   0: Script Name
#######################################
verify_script() {
  declare     dir
  # shellcheck disable=SC2312
  dir="$(dirname "$(readlink -f "${0}")")"
  declare     script; script="$(basename "${0}")"
  declare -a  algo=( "sha512" )
  declare     cmd="" computed="" expected="" hashfile="" item="" sigfile=""

  for item in "${algo[@]}"; do

    hashfile="${dir}/${script}.${item}sum.txt"
    sigfile="${hashfile}.sig"
    cmd="${item}sum"

    color_echo "${MAG}" "🔏 Verifying signature of: [${hashfile}]"

    if ! gpgv --keyring "/etc/ciss/keys/${CDLB_DB_EXP_FPR}.gpg" "${sigfile}" "${hashfile}"; then

      color_echo "${RED}" "✘ Signature verification failed for: [${hashfile}]"
      color_echo "${RED}" "✘ System Power Off in 3 seconds."
      power_off 3

    else

      color_echo "${GRE}" "🔏 Verifying signature of: [${hashfile}] successful."

    fi


    color_echo "${MAG}" "🔢 Recomputing Hash: [${item}]"

    declare _=""
    # shellcheck disable=SC2312
    read -r computed _ < <("${cmd}" "${dir}/${script}")
    read -r expected _ < "${hashfile}"

    if [[ "${computed}" != "${expected}" ]]; then

      color_echo "${RED}" "✘ Recomputed hash mismatch for     : [${item}]"
      color_echo "${RED}" "✘ System Power Off in 3 seconds."
      power_off 3

    fi

    color_echo "${GRE}" "🔢 Recomputing Hash: [${item}] successful."

  done

  color_echo "${GRE}" "🔏 All signatures and hashes verified successfully. Proceeding."
  return 0
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f verify_script

#######################################
# Main Program Sequence.
# Globals:
#   CDLB_MAPPER_DEV
#   CURRENTDATE
#   GRE
#   MAG
#   NL
#   PASSPHRASE
#   RED
# Arguments:
#   None
#######################################
main() {
  declare PASS="" COUNTER=0 PASS_SENT=0 WAIT_LOOP=0

  mkdir -p /var/log
  : >| /var/log/wtmp

  exec 1>&2

  trap 'trap_on_err "$?" "${BASH_SOURCE[0]}" "${LINENO}" "${FUNCNAME[0]:-main}" "${BASH_COMMAND}"' ERR
  trap 'trap_on_exit' EXIT
  trap 'trap_on_term' INT TERM

  uname -a

  printf "%b" "${NL}"
  color_echo "${RED}" "Coresecret Connection established."
  color_echo "${RED}" "Starting Time: ${CURRENTDATE}"

  printf "%b" "${NL}"
  color_echo "${MAG}" "Integrity self-check ..."
  verify_script

  while :; do

    if [[ -b "${CDLB_MAPPER_DEV}" ]]; then

      secure_unset_pass
      printf "%b" "${NL}"
      color_echo "${GRE}" "CISS LUKS Container successfully opened. Closing dropbear connection in 3 seconds."
      sleep 3
      exit 0

    fi

    if [[ "${COUNTER}" -ge 3 && "${PASS_SENT}" -eq 0 ]]; then

      secure_unset_pass
      break

    fi

    if [[ "${PASS_SENT}" -eq 0 ]]; then

      COUNTER=$((COUNTER + 1))

      # shellcheck disable=SC2310
      read_passphrase || continue

      printf '%s\n' "${PASSPHRASE}" >| /lib/cryptsetup/passfifo 2>/dev/null || :

      PASS_SENT=1
      WAIT_LOOP=0

    else

      WAIT_LOOP=$((WAIT_LOOP + 1))
      COUNTER=$((COUNTER + 1))

      if [[ "${WAIT_LOOP}" -ge 160 ]]; then

        color_echo "${GRE}" "Please try again"

        PASS_SENT=0
        WAIT_LOOP=0

      fi

    fi

    sleep 0.1

  done

  printf "%b" "${NL}"
  color_echo "${GRE}" "No LUKS operations successful. Dropping to bash ..."
  drop_bash
}
### Prevents accidental 'unset -f'.
# shellcheck disable=SC2034
readonly -f main

main "${@}"
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
