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

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

# SLES16 ships its default sshd_config at /usr/etc/ssh/sshd_config (the
# vendor-owned file, not meant to be edited) and includes
# /etc/ssh/sshd_config.d/*.conf near the top of it via OpenSSH's own native
# Include mechanism. So instead of editing the live config in place, this
# script only ever has to manage its own drop-in file here.
SSHD_VENDOR_CONFIG="/usr/etc/ssh/sshd_config"
SSHD_DROPIN_DIR="/etc/ssh/sshd_config.d"
SSHD_DROPIN="$SSHD_DROPIN_DIR/50-cc.conf"

# Single canonical list of accepted public-key algorithm families (RSA and
# ECDSA P-384/P-521 - the only key types the CC evaluation guidance's
# key-generation requirement sanctions), used below for every sshd_config
# directive that restricts key/signature algorithms.
# warn_stranded_keys_20_config_sshd spells the same set in ssh-keygen -l's
# vocabulary.
PUBKEY_ALGOS="rsa-sha2-256,rsa-sha2-512,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521"

# What sshd must actually run with (guide: "SSH Server Configuration", and no
# direct root login from "Gaining administrative access"), in `sshd -T`'s
# output format: lower-case keywords, sizes and times in bytes and seconds.
# The drop-in apply writes sets these; usepam yes is the vendor default that
# 30-cc-pam-config's pam_loginuid relies on. PasswordAuthentication isn't
# here: the guide allows it, but doesn't require it.
SSHD_EFFECTIVE=(
	"permitrootlogin no"
	"pubkeyauthentication yes"
	"kbdinteractiveauthentication no"
	"gssapiauthentication no"
	"kerberosauthentication no"
	"hostbasedauthentication no"
	"permitemptypasswords no"
	"usepam yes"
	"ciphers aes256-gcm@openssh.com"
	"kexalgorithms ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512"
	"macs hmac-sha2-256,hmac-sha2-512"
	"hostkeyalgorithms $PUBKEY_ALGOS"
	"hostbasedacceptedalgorithms $PUBKEY_ALGOS"
	"pubkeyacceptedalgorithms $PUBKEY_ALGOS"
	"rekeylimit 1073741824 3600"
)

# sshd's options from /etc/sysconfig/ssh, which sshd.service passes to sshd.
sshd_opts_20_config_sshd() {
	(
		set +eu
		SSHD_OPTS=""
		# shellcheck source=/dev/null
		[ -r /etc/sysconfig/ssh ] && . /etc/sysconfig/ssh >/dev/null 2>&1
		echo "$SSHD_OPTS"
	)
}

# Prints "FILE: KEYWORD" for each keyword of SSHD_EFFECTIVE set inside a
# Match block of sshd's configuration files, which `sshd -T` without the
# matching connection doesn't show.
sshd_match_overrides_20_config_sshd() {
	local -a files=()
	local f
	for f in /usr/etc/ssh/sshd_config /etc/ssh/sshd_config /usr/etc/ssh/sshd_config.d/*.conf /etc/ssh/sshd_config.d/*.conf; do
		[ -f "$f" ] && files+=("$f")
	done
	[ "${#files[@]}" -gt 0 ] || return 0
	awk -v guarded="$(printf '%s\n' "${SSHD_EFFECTIVE[@]}" | cut -d' ' -f1 | tr '\n' ' ')" '
		BEGIN { n = split(guarded, g, " "); for (i = 1; i <= n; i++) kw[g[i]] = 1 }
		FNR == 1 { inmatch = 0 }
		{ k = tolower($1); sub(/=.*/, "", k) }
		k == "match" { inmatch = 1; next }
		inmatch && (k in kw) { print FILENAME ": " k }
	' "${files[@]}"
}

# Runs sshd with the given arguments (-T for the effective configuration).
# sshd refuses to run without a host key and without its privilege
# separation directory /var/lib/empty. In a chroot, the host keys may not
# exist yet (sshd-gen-keys-start creates them on first boot), so a throwaway
# key stands in. Inside a transactional-update snapshot, /var is an empty
# mount point rather than the running system's /var; a tmpfs there, in a
# private mount namespace, provides the directory without writing into the
# snapshot.
sshd_run_20_config_sshd() {
	local key_dir=""
	local rc=0
	local -a sshd=(/usr/sbin/sshd "$@")

	if ! cc_in_chroot; then
		"${sshd[@]}"
		return
	fi
	if ! ls /etc/ssh/ssh_host_*_key >/dev/null 2>&1; then
		key_dir=$(mktemp -d)
		ssh-keygen -q -t ecdsa -b 384 -N "" -f "$key_dir/key" || rc=$?
		sshd+=(-h "$key_dir/key")
	fi
	if [ "$rc" -eq 0 ] && [ -d /var/lib/empty ]; then
		"${sshd[@]}" || rc=$?
	elif [ "$rc" -eq 0 ]; then
		# shellcheck disable=SC2016 # expanded by the inner sh
		unshare -m sh -c 'mount -t tmpfs -o mode=755 cc-sshd-test /var && mkdir -p /var/lib/empty && exec "$@"' \
			sh "${sshd[@]}" || rc=$?
	fi
	if [ -n "$key_dir" ]; then
		rm -rf "$key_dir"
	fi
	return "$rc"
}

# Read-only: does sshd's effective configuration, as `sshd -T` resolves it
# from the vendor file, every drop-in and /etc/sysconfig/ssh's options, have
# every value of SSHD_EFFECTIVE? `sshd -T` also fails like `sshd -t` on a
# configuration that doesn't parse. Used both to skip re-applying when
# already compliant and to verify after applying.
check_20_config_sshd() {
	local opts effective root_view line overrides
	opts=$(sshd_opts_20_config_sshd)
	# shellcheck disable=SC2086 # SSHD_OPTS is a word list, as in sshd.service
	if ! effective=$(sshd_run_20_config_sshd -T $opts 2>&1); then
		echo "sshd configuration fails 'sshd -T': $effective"
		return 1
	fi
	for line in "${SSHD_EFFECTIVE[@]}"; do
		if ! grep -qxF "$line" <<<"$effective"; then
			echo "sshd's effective configuration ('sshd -T') lacks '$line', has '$(grep -m1 "^${line%% *} " <<<"$effective" || echo "${line%% *} (unset)")'"
			return 1
		fi
	done
	# shellcheck disable=SC2086
	root_view=$(sshd_run_20_config_sshd -T $opts -C user=root,host=localhost,addr=127.0.0.1 2>&1) || true
	if ! grep -qx "permitrootlogin no" <<<"$root_view"; then
		echo "a Match block lets root log in over SSH ('sshd -T -C user=root,...' lacks 'permitrootlogin no')"
		return 1
	fi
	overrides=$(sshd_match_overrides_20_config_sshd)
	if [ -n "$overrides" ]; then
		echo "a Match block overrides a setting the evaluated configuration fixes: ${overrides//$'\n'/, }"
		return 1
	fi
	local sshd_err
	sshd_err=$(/usr/sbin/sshd -t -f "$SSHD_VENDOR_CONFIG" 2>&1) || {
		echo "merged sshd configuration fails 'sshd -t': $sshd_err"
		return 1
	}
}

# PUBKEY_ALGOS makes sshd reject ssh-ed25519, ECDSA P-256 and security-key
# (sk-*) keys, and the OSPP crypto-policy module that 51-config-crypto-policies
# selects sets RequiredRSASize 3072. Warn about each member of the 'trusted'
# group, and of the UID 1000 account that 10-add_user_to_trusted_group adds
# to it, whose authorized keys would all be rejected, and whether a usable
# password is left to log in with. Root isn't checked here: PermitRootLogin no
# rejects its keys whatever their type.
warn_stranded_keys_20_config_sshd() {
	local u h f keys pw
	for u in $({
		getent group trusted | cut -d: -f4 | tr ',' '\n'
		id -nu 1000 2>/dev/null || true
	} | sort -u); do
		h=$(getent passwd "$u" | cut -d: -f6) || continue
		if [ ! -d "$h" ]; then
			echo "NOTE: $u's home directory $h isn't there, so their authorized_keys were not checked: sshd accepts only RSA keys of 3072 bits or more and ECDSA P-384/P-521 keys"
			continue
		fi
		f="$h/.ssh/authorized_keys"
		[ -r "$f" ] || continue
		# ssh-keygen -l parses option prefixes and prints "BITS FP COMMENT (TYPE)"
		# per key; it exits non-zero when the file holds no key at all.
		keys=$(ssh-keygen -lf "$f" 2>/dev/null) || continue
		if awk '($NF == "(RSA)" && $1 >= 3072) || ($NF == "(ECDSA)" && ($1 == 384 || $1 == 521)) { ok = 1 }
			END { exit !ok }' <<<"$keys"; then
			continue
		fi
		echo "WARNING: $f holds no RSA (3072 bits or more) or ECDSA P-384/P-521 key, so sshd rejects all of $u's keys"
		pw=$(passwd -S "$u" 2>/dev/null) || pw=""
		if [[ "$pw" == "$u P "* ]]; then
			echo "WARNING: $u can still log in over SSH with their password"
		else
			echo "WARNING: $u has no usable password either and is locked out of new SSH logins (open sessions stay up): add a key from ssh-keygen -t rsa -b 3072 (or larger) or -t ecdsa -b 384/521"
		fi
	done
}

apply_20_config_sshd() {
	[ -f "$SSHD_VENDOR_CONFIG" ] || {
		echo "OpenSSH server does not appear to be installed ($SSHD_VENDOR_CONFIG missing) - skipping configuration"
		return 0
	}

	if check_20_config_sshd; then
		echo "$SSHD_DROPIN already installed and verified"
		return 0
	fi

	mkdir -p "$SSHD_DROPIN_DIR"

	cat > "$SSHD_DROPIN" <<EOF
# Common Criteria evaluated configuration - managed by certification-sles-eal4.
# Do not edit; changes here will be overwritten. sshd applies the first
# value it encounters for each keyword and ignores later ones (confirmed:
# an earlier-sorting drop-in's Ciphers wins over a later one's), so a local
# exception needs a file that sorts BEFORE this one in
# /etc/ssh/sshd_config.d/, not after.
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication yes
KbdInteractiveAuthentication no
GSSAPIAuthentication no
HostbasedAuthentication no
Ciphers aes256-gcm@openssh.com
KexAlgorithms ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
MACs hmac-sha2-256,hmac-sha2-512
HostKeyAlgorithms $PUBKEY_ALGOS
HostbasedAcceptedAlgorithms $PUBKEY_ALGOS
# Note: the SLES15 SP7 CC evaluation guidance document's "SSH Server
# Configuration" section lists ecdh-sha2-nistp384/521 (KEX algorithm names)
# as the required value here, but sshd rejects those with "Bad key types"
# since this directive takes public-key signature algorithm names, not KEX
# names - that section of the guide appears to have a copy/paste error.
# Using the same set the guide specifies for HostKeyAlgorithms instead, as
# the closest available approximation of intent.
PubkeyAcceptedAlgorithms $PUBKEY_ALGOS
RekeyLimit 1G 1h
EOF
	chmod 644 "$SSHD_DROPIN"
	echo "Installed $SSHD_DROPIN"

	# Validate the full merged configuration before declaring success, so a
	# bad directive is reported loudly instead of silently leaving sshd
	# unable to start or reload.
	check_20_config_sshd || {
		echo "FAILED: sshd configuration does not pass verification after installing $SSHD_DROPIN"
		return 1
	}
	echo "$SSHD_DROPIN installed and verified with 'sshd -T'"

	# A running sshd keeps its old configuration until reloaded. The unit's
	# reload is a SIGHUP, which leaves open sessions alone; a stopped sshd
	# is left as is.
	if cc_in_chroot; then
		echo "sshd.service gets the new configuration when this system is booted"
	elif ! systemctl try-reload-or-restart sshd.service; then
		echo "FAILED: could not reload sshd.service with the new configuration"
		return 1
	else
		echo "Reloaded sshd.service if it was running"
	fi

	warn_stranded_keys_20_config_sshd
	if ssh-keygen -lf "$(getent passwd root | cut -d: -f6)/.ssh/authorized_keys" >/dev/null 2>&1; then
		echo "WARNING: root has authorized SSH keys, but PermitRootLogin no rejects them: log in remotely as a member of the 'trusted' group instead"
	fi
}
