# platform = multi_platform_all

{{{ bash_instantiate_variables("var_password_hashing_algorithm_pam") }}}

# Allow multiple algorithms, but choose the first one for remediation
var_password_hashing_algorithm_pam="$(echo $var_password_hashing_algorithm_pam | cut -d \| -f 1)"

{{% if 'sle' in product or 'slmicro' in product -%}}
PAM_FILE_PATH="/etc/pam.d/common-password"
{{% set control = "required" %}}
{{%- elif 'ubuntu' in product or 'debian' in product -%}}
{{{ bash_pam_unix_enable() }}}
PAM_FILE_PATH=/usr/share/pam-configs/cac_unix
{{%- else -%}}
PAM_FILE_PATH="/etc/pam.d/system-auth"
{{% set control = "sufficient" %}}
{{%- endif %}}

# Ensure all the hashing algorithm option is removed.
declare -a HASHING_ALGORITHMS_OPTIONS=("sha512" "yescrypt" "gost_yescrypt" "blowfish" "sha256" "md5" "bigcrypt")

for hash_option in "${HASHING_ALGORITHMS_OPTIONS[@]}"; do
  {{% if 'ubuntu' in product or 'debian' in product -%}}
    sed -i -E '/^Password:/,/^[^[:space:]]/ {
    /pam_unix\.so/ {
      s/\s*\b'"$hash_option"'\b//g
    }
    }' "$PAM_FILE_PATH"
    sed -i -E '/^Password-Initial:/,/^[^[:space:]]/ {
    /pam_unix\.so/ {
      s/\s*\b'"$hash_option"'\b//g
    }
    }' "$PAM_FILE_PATH"
    DEBIAN_FRONTEND=noninteractive pam-auth-update
  {{%- else -%}}
  if grep -qP "^\s*password\s+.*\s+pam_unix.so\s+.*\b$hash_option\b" "$PAM_FILE_PATH"; then
    {{{ bash_remove_pam_module_option_configuration("$PAM_FILE_PATH", 'password', ".*", 'pam_unix.so', "$hash_option") }}}
  fi
  {{%- endif %}}
done

{{% if 'ubuntu' in product or 'debian' in product -%}}
if ! grep -qzP "Password:\s*\n\s+.*\s+pam_unix.so\s+.*\b$var_password_hashing_algorithm_pam\b" "$PAM_FILE_PATH"; then
  sed -i -E '/^Password:/,/^[^[:space:]]/ {
    /pam_unix\.so/ {
        s/$/ '"$var_password_hashing_algorithm_pam"'/g
    }
}' "$PAM_FILE_PATH"
fi

if ! grep -qzP "Password-Initial:\s*\n\s+.*\s+pam_unix.so\s+.*\b$var_password_hashing_algorithm_pam\b" "$PAM_FILE_PATH"; then
  sed -i -E '/^Password-Initial:/,/^[^[:space:]]/ {
    /pam_unix\.so/ {
        s/$/ '"$var_password_hashing_algorithm_pam"'/g
    }
}' "$PAM_FILE_PATH"
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update

{{%- else -%}}
{{{ bash_ensure_pam_module_configuration("$PAM_FILE_PATH", 'password', control, 'pam_unix.so', "$var_password_hashing_algorithm_pam", '', '') }}}
{{%- endif %}}
