#!/bin/bash
set -Eeuo pipefail
shopt -s inherit_errexit

# shellcheck source=scripts/libcc
. /usr/lib/common-criteria/scripts/libcc

###########################################
# Hardware crypto acceleration disabling: the kernel side through the
# modprobe blacklist (config/cc-modules-blacklist.conf, plus a CPUID mask for
# SHA-NI on x86_64), and OpenSSL's own CPU-feature dispatch through an
# environment variable (guide's "x86/ARM64/IBM Z System Configuration" and
# "OpenSSL on x86/IBM Z/ARM Architecture" sections). Power has no guide
# section and is handled the same way: only the crypto instructions are
# turned off, not plain vector (SIMD) code.

# The OpenSSL variable goes to login sessions through pam_env and to every
# system service, sshd included, through the systemd manager's
# DefaultEnvironment: pam_env never touches the sshd processes that encrypt
# the SSH connection itself, and the guide requires the variable "for
# OpenSSH and the openssl application".
ENV_DROPIN_DIR="/etc/environment.d"
ENV_DROPIN="$ENV_DROPIN_DIR/50-cc-crypto.conf"
SYSTEMD_DROPIN_DIR="/etc/systemd/system.conf.d"
SYSTEMD_DROPIN="$SYSTEMD_DROPIN_DIR/50-cc-crypto.conf"
MODPROBE_BLACKLIST="/lib/modprobe.d/cc-modules-blacklist.conf"
GRUB_DEFAULT="/etc/default/grub"

# guide's "OpenSSL on IBM Z Architecture" value without its kimd and klmd
# fields: with either of those two, SUSE's OpenSSL FIPS provider fails its
# self-test and refuses to load, which in FIPS mode leaves every OpenSSL
# user without crypto. CPACF hashing therefore stays enabled, and the check
# reports that as not compliant until the guidance is settled.
S390X_PARTIAL_CAP="km:0:0;kmc:0:0;kmac:0:0;kmctr:0:0;kmo:0:0;kmf:0:0;prno:0:0;kma:0:0;pcc:0:0;kdsa:0:0"
S390X_GAP="OPENSSL_s390xcap leaves kimd/klmd (CPACF hashing) enabled, because the guide's full value makes the OpenSSL FIPS provider fail its self-test - not compliant until the guidance for IBM Z is settled"

# OPENSSL_armcap replaces OpenSSL's hardware detection rather than masking
# it, so it has to be computed for this CPU. These are the bits the guide's
# "OpenSSL on ARM Architecture" script keeps after its disable mask (cpuid,
# rng, sm3, sm4, sve, sve2); every other bit it sets is masked out again.
# Whole-word matching against the kernel's feature names, not the script's
# substring grep, so that e.g. "svesm4" doesn't count as "sm4".
cc50_armcap() {
	local features
	local entry
	local value=0
	features=$(awk '/^Features/ { sub(/^[^:]*:/, ""); print " " $0 " "; exit }' /proc/cpuinfo)
	for entry in cpuid:7 rng:8 sm3:9 sm4:10 sve:13 sve2:14; do
		case "$features" in
		*" ${entry%:*} "*)
			value=$((value | (1 << ${entry#*:})))
			;;
		esac
	done
	echo "$value"
}

# OPENSSL_ppccap also replaces OpenSSL's hardware detection, so it is computed
# the way OpenSSL's crypto/ppccap.c detects the CPU from the auxiliary vector,
# leaving out only PPC_CRYPTO207 (4): the vector crypto instructions behind
# OpenSSL's AES, SHA-2 and GHASH code. The other bits select plain vector or
# scalar code: PPC_FPU64 (1, power6x), PPC_ALTIVEC (2), PPC_FPU (8),
# PPC_MADD300 (16, arch_3_00), PPC_BRD31 (128, arch_3_1).
cc50_ppccap() {
	local caps
	local entry
	local value=0
	caps=" $(LD_SHOW_AUXV=1 /bin/true | awk -F: '$1 == "AT_HWCAP" || $1 == "AT_HWCAP2" { printf "%s ", $2 }') "
	caps=$(echo "$caps" | tr -s ' \t' '  ')
	for entry in power6x:0 altivec:1 fpu:3 arch_3_00:4 arch_3_1:7; do
		case " $caps " in
		*" ${entry%:*} "*)
			value=$((value | (1 << ${entry#*:})))
			;;
		esac
	done
	echo "$value"
}

# The OpenSSL capability assignment for this architecture, empty if there is
# none.
cc50_openssl_assignment() {
	case "$(uname -m)" in
	x86_64)
		echo "OPENSSL_ia32cap=~0x200000200000000"
		;;
	aarch64)
		echo "OPENSSL_armcap=$(cc50_armcap)"
		;;
	s390x)
		echo "OPENSSL_s390xcap=$S390X_PARTIAL_CAP"
		;;
	ppc64le)
		echo "OPENSSL_ppccap=$(cc50_ppccap)"
		;;
	esac
}

# Names of the modules the blacklist turns into "install NAME /bin/true",
# one per line.
cc50_blocked_modules() {
	awk '$1 == "install" && $3 == "/bin/true" { print $2 }' "$MODPROBE_BLACKLIST"
}

# Are the module blacklist and the systemd drop-in inside every kernel's
# initrd, identical to the installed files? Both act during the initrd
# stage: the CPU-feature aliases that autoload the blacklisted modules fire
# there, and systemd-cryptsetup unlocks the root disk there through
# libcryptsetup, which uses OpenSSL. Every kernel's, not only the running
# one's: the next boot can use a newer kernel, e.g. from an update waiting
# in the same transactional-update snapshot. False if there is no initrd.
cc50_initrd_current() {
	local initrd
	local entry
	local copy
	local found=0
	for initrd in /boot/initrd-*; do
		case "$initrd" in
		*-kdump) continue ;;
		esac
		[ -f "$initrd" ] || continue
		found=1
		for entry in "usr/lib/modprobe.d/cc-modules-blacklist.conf:$MODPROBE_BLACKLIST" \
			"etc/systemd/system.conf.d/50-cc-crypto.conf:$SYSTEMD_DROPIN"; do
			copy=$(lsinitrd -f "${entry%%:*}" "$initrd" 2>/dev/null) || return 1
			[ "$copy" = "$(cat "${entry#*:}")" ] || return 1
		done
	done
	[ "$found" = 1 ]
}

# Did the running sshd start after the systemd drop-in was last written, and
# so with the variable? Its environment can't be read back: sshd overwrites
# /proc/PID/environ with its process title. sshd-session inherits the
# listener's environment, so the listener is the one to look at. True if no
# sshd is running.
cc50_sshd_current() {
	local pid
	local elapsed
	pid=$(systemctl show -p MainPID --value sshd.service 2>/dev/null) || pid=0
	if [ -z "$pid" ] || [ "$pid" = 0 ]; then
		return 0
	fi
	elapsed=$(ps -o etimes= -p "$pid" 2>/dev/null) || return 0
	[ $(($(date +%s) - elapsed)) -ge "$(stat -c %Y "$SYSTEMD_DROPIN")" ]
}

# Write $2 to $1 (mode 644) unless it already has exactly that content, so
# that re-running apply leaves the drop-in's mtime, which
# cc50_sshd_current relies on, alone.
cc50_write() {
	local file="$1"
	local content="$2"
	if [ -f "$file" ] && [ "$(cat "$file")" = "$content" ]; then
		echo "$file already up to date"
		return 0
	fi
	printf '%s\n' "$content" >"$file.$$"
	chmod 644 "$file.$$"
	mv "$file.$$" "$file"
	echo "Installed $file"
}

# Prints each place outside this package's drop-ins that sets or removes an
# OPENSSL_*cap variable for login sessions or sshd, or that resets systemd's
# DefaultEnvironment (an empty assignment drops the earlier ones), one per
# line.
cc50_env_overrides() {
	local f
	local unit_env
	for f in /etc/security/pam_env.conf /etc/security/pam_env.conf.d/*.conf \
		/usr/etc/security/pam_env.conf /usr/etc/security/pam_env.conf.d/*.conf \
		/etc/sysconfig/ssh; do
		[ -f "$f" ] || continue
		if grep -qE '^[^#]*OPENSSL_[a-z0-9]*cap' "$f"; then
			echo "$f sets an OPENSSL_*cap variable"
		fi
	done
	for f in /etc/systemd/system.conf /etc/systemd/system.conf.d/*.conf \
		/run/systemd/system.conf.d/*.conf /usr/lib/systemd/system.conf.d/*.conf; do
		if [ ! -f "$f" ] || [ "$f" = "$SYSTEMD_DROPIN" ]; then
			continue
		fi
		if grep -qE '^[[:space:]]*DefaultEnvironment=[[:space:]]*$|^[[:space:]]*DefaultEnvironment=.*OPENSSL_' "$f"; then
			echo "$f resets DefaultEnvironment or sets an OPENSSL_*cap variable in it"
		fi
	done
	# In a chroot, systemctl show describes nothing (see cc_in_chroot).
	unit_env=""
	if ! cc_in_chroot; then
		unit_env=$(systemctl show -p Environment -p UnsetEnvironment --value sshd.service 2>/dev/null) || unit_env=""
	fi
	if grep -q OPENSSL_ <<<"$unit_env"; then
		echo "sshd.service sets or unsets an OPENSSL_*cap variable (Environment/UnsetEnvironment)"
	fi
}

# Prints each module of the blacklist that modprobe's effective
# configuration doesn't turn into "install /bin/true", e.g. because a file of
# the same name in /etc/modprobe.d replaces this package's (modprobe.d(5)).
# modprobe -n -v lists the module's dependencies first; its own line is the
# last.
cc50_modules_not_blocked() {
	local module
	while IFS= read -r module; do
		if [ "$(modprobe -n -v "$module" 2>/dev/null | tail -n 1 | sed 's/[[:space:]]*$//')" != "install /bin/true" ]; then
			echo "$module"
		fi
	done < <(cc50_blocked_modules)
}

# Configuration first (1 when wrong), then the running system (2 when only a
# reboot is missing: the blacklist and clearcpuid= act at boot, and services
# started before the systemd drop-in lack the variable). Returning 2 rather
# than 1 for the latter follows the 0/1/2 convention `apply` and `check`
# share.
check_50_config_crypto_hwaccel() {
	local arch
	local assignment
	local module
	local overrides
	local verify
	local unblocked
	local manager_env
	arch=$(uname -m)
	case "$arch" in
	x86_64 | aarch64 | s390x | ppc64le) ;;
	*)
		echo "hardware crypto acceleration disabling not implemented for $arch"
		return 1
		;;
	esac

	assignment=$(cc50_openssl_assignment)
	if [ ! -f "$ENV_DROPIN" ] || ! grep -qxF "$assignment" "$ENV_DROPIN"; then
		echo "$ENV_DROPIN missing or without $assignment"
		return 1
	fi
	# systemd's user environment generator reads environment.d as the user.
	if [ $((8#$(stat -c %a "$ENV_DROPIN_DIR") & 8#005)) -ne 5 ]; then
		echo "$ENV_DROPIN_DIR (mode $(stat -c %a "$ENV_DROPIN_DIR")) isn't readable for users, so their systemd user services don't get $assignment"
		return 1
	fi
	# pam_env reads only /etc/environment while it exists, and skips
	# environment.d altogether (pam_env(8)).
	if [ -e /etc/environment ] && ! grep -qxF "$assignment" /etc/environment; then
		echo "/etc/environment exists, so pam_env ignores $ENV_DROPIN; add $assignment to /etc/environment or remove that file"
		return 1
	fi
	if [ ! -f "$SYSTEMD_DROPIN" ] || ! grep -qxF "DefaultEnvironment=\"$assignment\"" "$SYSTEMD_DROPIN"; then
		echo "$SYSTEMD_DROPIN missing or without DefaultEnvironment=\"$assignment\""
		return 1
	fi
	overrides=$(cc50_env_overrides)
	if [ -n "$overrides" ]; then
		echo "${overrides//$'\n'/; }"
		return 1
	fi
	if [ ! -f "$MODPROBE_BLACKLIST" ]; then
		echo "$MODPROBE_BLACKLIST missing - reinstall certification-sles-eal4"
		return 1
	fi
	# rpm -V exits non-zero for any difference in the package, so its exit
	# status says nothing about this file.
	verify=$(rpm -V --nomtime certification-sles-eal4 2>/dev/null) || true
	if grep -qF " $MODPROBE_BLACKLIST" <<<"$verify"; then
		echo "$MODPROBE_BLACKLIST differs from the one this package ships - reinstall certification-sles-eal4"
		return 1
	fi
	unblocked=$(cc50_modules_not_blocked)
	if [ -n "$unblocked" ]; then
		echo "modprobe's configuration doesn't block $(echo "$unblocked" | tr '\n' ' ')(another modprobe.d file overrides $MODPROBE_BLACKLIST)"
		return 1
	fi
	if ! cc50_initrd_current; then
		echo "an initrd in /boot lacks the current $MODPROBE_BLACKLIST or $SYSTEMD_DROPIN (dracut not run since they changed)"
		return 1
	fi

	if [ "$arch" = x86_64 ]; then
		if [ ! -f "$GRUB_DEFAULT" ]; then
			echo "$GRUB_DEFAULT missing"
			return 1
		fi
		# SHA-NI is bundled inside sha1_ssse3/sha256_ssse3 on this kernel
		# rather than being its own module, so it can't be blacklisted
		# without also losing the AVX2/AVX/SSSE3 code paths. Masking the
		# CPUID bit at boot leaves those intact.
		if ! cc_grub_default_has "clearcpuid=sha_ni"; then
			echo "$GRUB_DEFAULT missing clearcpuid=sha_ni"
			return 1
		fi
		if ! cc_grub_cfg_has "clearcpuid=sha_ni"; then
			if cc_is_chroot; then
				# In a chroot/build environment, grub.cfg might not exist yet, but it's configured in /etc/default/grub.
				return 2
			fi
			echo "not every grub.cfg has clearcpuid=sha_ni (grub2-mkconfig not yet regenerated with it, or no grub.cfg found at all)"
			return 1
		fi
	fi

	if [ "$arch" = s390x ]; then
		echo "$S390X_GAP"
		return 1
	fi

	if cc_in_chroot; then
		echo "configured, in effect once this system is booted"
		return 2
	fi
	if [ "$arch" = x86_64 ]; then
		if [[ " $(cat /proc/cmdline) " != *" clearcpuid=sha_ni "* ]]; then
			echo "configured correctly, but the running kernel's cmdline does not have clearcpuid=sha_ni yet - reboot required"
			return 2
		fi
		if grep -qw sha_ni /proc/cpuinfo; then
			echo "clearcpuid=sha_ni is on the running kernel's cmdline, but the CPU still reports sha_ni in /proc/cpuinfo"
			return 1
		fi
	fi
	while IFS= read -r module; do
		if grep -q "^$module " /proc/modules; then
			echo "configured correctly, but blacklisted module $module is still loaded - reboot required"
			return 2
		fi
	done < <(cc50_blocked_modules)
	manager_env=$(systemctl show-environment 2>/dev/null) || manager_env=""
	if ! grep -qxF "$assignment" <<<"$manager_env"; then
		echo "configured correctly, but systemd's environment ('systemctl show-environment') lacks $assignment - reboot required"
		return 2
	fi
	if ! cc50_sshd_current; then
		echo "configured correctly, but the running sshd started before $SYSTEMD_DROPIN was written, so without $assignment - reboot (or restart sshd.service) required"
		return 2
	fi
}

apply_50_config_crypto_hwaccel() {
	local arch
	local assignment
	local rc
	local out
	arch=$(uname -m)

	rc=0
	out=$(check_50_config_crypto_hwaccel 2>&1) || rc=$?
	if [ "$rc" -eq 0 ]; then
		echo "hardware crypto acceleration already disabled"
		return 0
	fi
	if [ "$rc" -eq 2 ]; then
		echo "hardware crypto acceleration already configured, reboot required before it's fully in effect"
		return 2
	fi

	case "$arch" in
	x86_64 | aarch64 | s390x | ppc64le) ;;
	*)
		echo "FAILED: $out"
		return 1
		;;
	esac

	assignment=$(cc50_openssl_assignment)
	mkdir -p "$ENV_DROPIN_DIR" "$SYSTEMD_DROPIN_DIR"
	# mkdir -p follows the caller's umask, and systemd's user environment
	# generator reads the directory as the user.
	chmod 755 "$ENV_DROPIN_DIR"
	cc50_write "$ENV_DROPIN" "# Common Criteria evaluated configuration - managed by certification-sles-eal4.
# Do not edit; changes here will be overwritten.
$assignment"
	cc50_write "$SYSTEMD_DROPIN" "# Common Criteria evaluated configuration - managed by certification-sles-eal4.
# Do not edit; changes here will be overwritten.
[Manager]
DefaultEnvironment=\"$assignment\""
	if cc_in_chroot; then
		echo "services get $assignment once this system is booted"
	else
		systemctl daemon-reload
		echo "services started from now on get $assignment"
	fi

	if [ -f "$MODPROBE_BLACKLIST" ] && ! cc50_initrd_current; then
		dracut -f --regenerate-all
		echo "every kernel's initrd regenerated with the current module blacklist and systemd drop-in"
	fi

	if [ "$arch" = x86_64 ]; then
		if [ ! -f "$GRUB_DEFAULT" ] || ! command -v grub2-mkconfig >/dev/null 2>&1; then
			echo "FAILED: grub2 not found ($GRUB_DEFAULT or grub2-mkconfig missing) - cannot configure clearcpuid=sha_ni"
			return 1
		fi
		if grep -q "clearcpuid=sha_ni" "$GRUB_DEFAULT"; then
			echo "clearcpuid=sha_ni already present in $GRUB_DEFAULT"
		else
			sed '/^GRUB_CMDLINE_LINUX_DEFAULT=/ s/"$/ clearcpuid=sha_ni"/' "$GRUB_DEFAULT" >"$GRUB_DEFAULT.$$"
			cc_replace "$GRUB_DEFAULT.$$" "$GRUB_DEFAULT"
			rm -f "$GRUB_DEFAULT.$$"
			echo "clearcpuid=sha_ni added to $GRUB_DEFAULT"
		fi
		if ! cc_grub_cfg_has "clearcpuid=sha_ni"; then
			cc_grub_regenerate
			echo "every applicable grub.cfg regenerated"
		fi
	fi

	rc=0
	out=$(check_50_config_crypto_hwaccel 2>&1) || rc=$?
	if [ "$rc" -eq 2 ]; then
		echo "hardware crypto acceleration disabling configured - reboot required before it's fully in effect"
		return 2
	fi
	if [ "$rc" -ne 0 ]; then
		if [ "$arch" = s390x ] && [ "$out" = "$S390X_GAP" ]; then
			echo "FAILED: applied as far as possible, but $out"
		else
			echo "FAILED: still not in place after applying: $out"
		fi
		return 1
	fi
}
