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

#######################################
# Function to encrypt the respective partition on each device according to the chosen recipe string.
# Globals:
#   DIR_BAK
#   DIR_CNF
#   DIR_LOG
#   HMP_EPHEMERAL_ENCLABEL
#   HMP_EPHEMERAL_FS_LABEL
#   HMP_PATH_ENCLABEL
#   HMP_PATH_LUKSUUID
#   VAR_CRYPT_RECOVERY
#   VAR_CRYPT_ROOT
#   VAR_ITER_TIME
#   VAR_KDF_ITERATIONS
#   VAR_KDF_MEMORY
#   VAR_KDF_THREADS
#   VAR_RECIPE_STRING
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
partition_encryption() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -Ag HMP_PATH_LUKSUUID      # Used in: 3290() - [Mount Path:LUKS UUID].
                                     # Used in: 4060() - [Mount Path:LUKS UUID].
  declare -Ag HMP_EPHEMERAL_ENCLABEL
  declare -Ag HMP_EPHEMERAL_FS_LABEL

  declare -Ag HMP_PATH_ENCLABEL

  declare -gx VAR_CRYPT_ROOT=""      # LUKS UUID of '/'.
  declare -gx VAR_CRYPT_RECOVERY=""  # LUKS UUID of '/recovery'.

  declare     var_dev="" var_part="" \
              var_encryption_enable="" var_encryption_ephemeral="" var_encryption_integrity="" var_encryption_cipher="" \
              var_encryption_hash="" var_encryption_key="" var_encryption_label="" var_encryption_meta="" var_encryption_slot="" \
              var_encryption_pbkdf="" var_encryption_rng="" var_filesystem_label="" var_mount_path="" var_uuid="" var_fs=""

  declare -a  ary_devs=() ary_parts=() ary_luks_opts=()

  ### Iterate over all devices in the recipe.
  # shellcheck disable=SC2312
  readarray -t ary_devs < <(yq e -r ".recipe.${VAR_RECIPE_STRING}.dev | keys | .[]" "${VAR_SETUP_PART}")
  for var_dev in "${ary_devs[@]}"; do

    touch "${DIR_LOG}/${var_dev}_cryptsetup_luksdump.log"
    chmod 0600 "${DIR_LOG}/${var_dev}_cryptsetup_luksdump.log"

    ### Iterate over all partitions for this device.
    # shellcheck disable=SC2312
    readarray -t ary_parts < <(yq e -r ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev} | keys | .[]" "${VAR_SETUP_PART}")
    for var_part in "${ary_parts[@]}"; do

      ### Extract parameters from YAML.
      var_encryption_enable=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.enable"       "${VAR_SETUP_PART}")
      var_encryption_ephemeral=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.ephemeral" "${VAR_SETUP_PART}")
      var_encryption_integrity=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.integrity" "${VAR_SETUP_PART}")
      var_encryption_cipher=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.cipher"       "${VAR_SETUP_PART}")
      var_encryption_hash=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.hash"           "${VAR_SETUP_PART}")
      var_encryption_key=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.key"             "${VAR_SETUP_PART}")
      var_encryption_slot=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.keyslotssize"   "${VAR_SETUP_PART}")
      var_encryption_meta=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.metadatasize"   "${VAR_SETUP_PART}")
      var_encryption_pbkdf=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.pbkdf"         "${VAR_SETUP_PART}")
      var_encryption_rng=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.encryption.rng"             "${VAR_SETUP_PART}")
      var_fs=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.filesystem.version"                     "${VAR_SETUP_PART}")
      var_mount_path=$(yq_val ".recipe.${VAR_RECIPE_STRING}.dev.${var_dev}.${var_part}.mount.path"                     "${VAR_SETUP_PART}")

      if [[ "${var_encryption_enable,,}" != "true" ]]; then
        continue
      fi

      var_encryption_label=$(get_label "${var_mount_path}" "${var_fs}" "luks")

      if [[ "${var_mount_path,,}" == "/boot" ]]; then
        ary_luks_opts=( --key-file "${DIR_CNF}/password_luks_boot.txt" )
        ary_luks_opts+=(
          --iter-time "${VAR_ITER_TIME:-3000}"
        )
      else
        ary_luks_opts=( --key-file "${DIR_CNF}/password_luks_common.txt" )
        ary_luks_opts+=(
          --pbkdf-parallel "${VAR_KDF_THREADS:-1}"
          --pbkdf-memory "${VAR_KDF_MEMORY:-4}"
          --pbkdf-force-iterations "${VAR_KDF_ITERATIONS:-4}"
        )
      fi

      ary_luks_opts+=(
        --type luks2
        --cipher "${var_encryption_cipher:-aes-xts-plain64}"
        --hash "${var_encryption_hash:-sha512}"
        --key-size "${var_encryption_key:-512}"
        --label "${var_encryption_label}"
        --luks2-keyslots-size "${var_encryption_slot:-16777216}"
        --luks2-metadata-size "${var_encryption_meta:-4194304}"
        --pbkdf "${var_encryption_pbkdf:-argon2id}"
        "--${var_encryption_rng}"
        --batch-mode
        --verbose
      )

      [[ "${var_encryption_integrity,,}" == "true" ]] && ary_luks_opts+=( --integrity hmac-sha512 )

      if [[ "${var_encryption_ephemeral,,}" == "true" ]]; then

        case "${var_mount_path,,}" in

          swap|/tmp)

            var_filesystem_label=$(get_label "${var_mount_path}" "${var_fs}" "file")

            mkfs.ext4 -L "${var_filesystem_label}" "/dev/${var_dev}${var_part}" 1M
            do_log "info" "file_only" "3220() Ephemeral: '${var_mount_path}' prepared on: '/dev/${var_dev}${var_part}'."


            HMP_EPHEMERAL_ENCLABEL["${var_mount_path}"]="${var_encryption_label}"
            HMP_EPHEMERAL_FS_LABEL["${var_mount_path}"]="${var_filesystem_label}"

            do_log "debug" "file_only" "3220() Stored in HashMap [HMP_EPHEMERAL_ENCLABEL]: '${var_mount_path}' -> '${HMP_EPHEMERAL_ENCLABEL["${var_mount_path}"]}'"
            do_log "debug" "file_only" "3220() Stored in HashMap [HMP_EPHEMERAL_FS_LABEL]: '${var_mount_path}' -> '${HMP_EPHEMERAL_FS_LABEL["${var_mount_path}"]}'"
            continue
            ;;

          *)
            do_log "error" "file_only" "3220() Invalid mount path: '${var_mount_path}' for partition: '/dev/${var_dev}${var_part}'."
            continue
            ;;

        esac

      fi

      cryptsetup luksFormat "${ary_luks_opts[@]}" "/dev/${var_dev}${var_part}"

      if [[ "${var_encryption_integrity,,}" == "true" ]]; then

        do_log "debug" "file_only" "3220() [cryptsetup luksFormat ${ary_luks_opts[*]} /dev/${var_dev}${var_part}]."
        do_log "info" "file_only" "3220() Partition: '/dev/${var_dev}${var_part}' dm-integrity encrypted."

      else

        do_log "debug" "file_only" "3220() [cryptsetup luksFormat ${ary_luks_opts[*]} /dev/${var_dev}${var_part}]."
        do_log "info" "file_only" "3220() Partition: '/dev/${var_dev}${var_part}' encrypted."

      fi

      cryptsetup luksHeaderBackup --header-backup-file="${DIR_BAK}/luks_header_${var_dev}${var_part}.bak" "/dev/${var_dev}${var_part}"
      do_log "info" "file_only" "3220() Partition: '/dev/${var_dev}${var_part}' LUKS Header saved: '${DIR_BAK}/luks_header_${var_dev}${var_part}.bak'."

      ### Opening encrypted container.
      if [[ "${var_mount_path,,}" == "/boot" ]]; then
        cryptsetup luksOpen "/dev/${var_dev}${var_part}" \
          --key-file="${DIR_CNF}/password_luks_boot.txt" \
          "${var_encryption_label}"
      else
        cryptsetup luksOpen "/dev/${var_dev}${var_part}" \
          --key-file="${DIR_CNF}/password_luks_common.txt" \
          "${var_encryption_label}"
      fi
      do_log "info" "file_only" "3220() Partition: '/dev/${var_dev}${var_part}' opened as '/dev/mapper/${var_encryption_label}'."

      ### Create luksDump log entry.
      printf "#------------------------------------------------------------------#\n" >> "${DIR_LOG}/${var_dev}_cryptsetup_luksdump.log"
      cryptsetup luksDump "/dev/${var_dev}${var_part}" >> "${DIR_LOG}/${var_dev}_cryptsetup_luksdump.log"

      ### Store UUID of the LUKS container.
      var_uuid=$(blkid -s UUID -o value "/dev/${var_dev}${var_part}")

      [[ "${var_mount_path}" == "/" ]] && declare -grx VAR_CRYPT_ROOT="${var_uuid}"
      [[ "${var_mount_path}" == "/recovery" ]] && declare -grx VAR_CRYPT_RECOVERY="${var_uuid}"

      HMP_PATH_LUKSUUID["${var_mount_path}"]="${var_uuid}"
      HMP_PATH_ENCLABEL["LABEL_${var_mount_path}"]="${var_encryption_label}"

      do_log "debug" "file_only" "3220() Stored in HashMap [HMP_PATH_LUKSUUID]     : '${var_mount_path}' -> '${HMP_PATH_LUKSUUID["${var_mount_path}"]}'"
      do_log "debug" "file_only" "3220() Stored in HashMap [HMP_PATH_ENCLABEL]     : '${var_mount_path}' -> '${HMP_PATH_ENCLABEL["LABEL_${var_mount_path}"]}'"

    done

  done

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