#!/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 entry of 'ARY_CRYPT_MOUNT_PATHS'.
# Globals:
#   ARY_CRYPT_MOUNT_PATHS
#   DIR_BAK
#   DIR_CNF
#   DIR_LOG
#   HMP_EPHEMERAL_ENCLABEL
#   HMP_EPHEMERAL_FS_LABEL
#   HMP_PATH_DEV_PART
#   HMP_PATH_ENCLABEL
#   HMP_PATH_FSUUID
#   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: 4210() - [Mount Path:LUKS UUID].
  declare -Ag HMP_PATH_FSUUID        # Used in: 3240() - [Mount Path:Filesystem UUID].
                                     # Used in: 3290() - [Mount Path:Filesystem UUID].
                                     # Used in: 4200() - [Mount Path:Filesystem UUID].
                                     # Used in: 4210() - [Mount Path:Filesystem UUID].
  declare -Ag HMP_EPHEMERAL_ENCLABEL # Used in: 4200() - [Mount Path:LUKS Encryption Label].
  declare -Ag HMP_EPHEMERAL_FS_LABEL # Used in: 4210() - [Mount Path:Ephemeral Host FS Label]. Substituted by FS-UUID

  declare -Ag HMP_PATH_ENCLABEL      # Used in: 4210() - [Mount Path:LUKS Encryption Label].

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

  declare     var_encryption_path="" var_dev_part="" var_dev="" \
              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="" \
              var_fs_uuid=""

  declare -a  ary_luks_opts=()

  for var_encryption_path in "${ARY_CRYPT_MOUNT_PATHS[@]}"; do

    ### Initialize Arrays and Variables
    ary_luks_opts=()

    ### Generates physical device location.
    var_dev_part="${HMP_PATH_DEV_PART["${var_encryption_path}"]}"
    var_dev="${var_dev_part//./}"

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

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

    if [[ "${var_encryption_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

      ### Preparation of Ephemeral 'SWAP' and '/tmp' as per https://wiki.archlinux.org/title/Dm-crypt/Swap_encryption#UUID_and_LABEL
      case "${var_encryption_path,,}" in

        swap|/tmp)

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

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

          var_fs_uuid=$(blkid -s UUID -o value "/dev/${var_dev}")
          ### Gathering information for '/etc/fstab'-generation in 4040() and '/etc/crypttab'-generation in 4060().
          # shellcheck disable=SC2034
          HMP_PATH_FSUUID["${var_encryption_path}"]="${var_fs_uuid}"
          do_log "debug" "file_only" "3220() [HMP_PATH_FSUUID]       : '${var_encryption_path}' -> '${HMP_PATH_FSUUID["${var_encryption_path}"]}'"

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

          do_log "debug" "file_only" "3220() [HMP_EPHEMERAL_ENCLABEL]: '${var_encryption_path}' -> '${HMP_EPHEMERAL_ENCLABEL["${var_encryption_path}"]}'"
          do_log "debug" "file_only" "3220() [HMP_EPHEMERAL_FS_LABEL]: '${var_encryption_path}' -> '${HMP_EPHEMERAL_FS_LABEL["${var_encryption_path}"]}'"

          ### The setup of ephemeral devices MUST stop here.
          continue
          ;;

        *)

          do_log "error" "file_only" "3220() Invalid mount path: '${var_encryption_path}' for partition: '/dev/${var_dev}'."
          ### There is no other need to implement ephemeral devices.
          continue
          ;;

      esac

    fi

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

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

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

    else

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

    fi

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

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

    ### Create luksDump log entry.
    cryptsetup luksDump "/dev/${var_dev}" >> "${DIR_LOG}/cryptsetup_luksdump_${var_dev}.log"

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

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

    HMP_PATH_LUKSUUID["${var_encryption_path}"]="${var_uuid}"
    HMP_PATH_ENCLABEL["${var_encryption_path}"]="${var_encryption_label}"

    do_log "debug" "file_only" "3220() [HMP_PATH_LUKSUUID]: '${var_encryption_path}' -> '${HMP_PATH_LUKSUUID["${var_encryption_path}"]}'"
    do_log "debug" "file_only" "3220() [HMP_PATH_ENCLABEL]: '${var_encryption_path}' -> '${HMP_PATH_ENCLABEL["${var_encryption_path}"]}'"

  done

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