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

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

###########################################
# PAM configuration for CC configuration

# Module options this script configures, each listed once: check_* looks
# for exactly these in the PAM files, and apply_* turns the same lists into
# pam-config arguments (minlen=12 -> --pwquality-minlen=12).
# enforcing=1 is pam_pwquality's default, but /etc/security/pwquality.conf
# (or a pwquality.conf.d file) can turn it off, which leaves only a warning;
# as a module argument it overrides those files.
PWQUALITY_OPTS=(retry=3 difok=3 minlen=12 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1 enforcing=1)
PWHISTORY_OPTS=(use_authtok enforce_for_root remember=7)
LOGINUID_OPTS=(require_auditd)
# Account lockout, as the SLES15 package configured it with pam_tally2
# (deny=5, no automatic unlock) for the services that authenticate a login:
# the console, SSH, and vlock's terminal lock. root is never locked
# (pam_faillock's default without even_deny_root). pam_tally2 counted
# failures of any age; 604800 s (7 days) is the longest window pam_faillock
# accepts. Module arguments override /etc/security/faillock.conf.
FAILLOCK_OPTS=(deny=5 unlock_time=0 fail_interval=604800)
FAILLOCK_SERVICES=(login sshd vlock)

# Does $1 have a $2 (PAM type) line for module $3 whose control is required
# or requisite, carrying every remaining argument as a whole option? Prints
# what's missing if not. With optional or sufficient, the module's verdict
# doesn't decide the outcome. Reads the file itself rather than
# `pam-config -q`, which doesn't report every option pam-config writes: it
# omits pam_pwhistory's use_authtok even while that is in the file.
pam_line_has() {
	local file=$1
	local type=$2
	local module=$3
	local line
	local opt
	shift 3

	line=$(grep -E "^${type}[[:space:]]+[^[:space:]]+[[:space:]]+${module//./\\.}([[:space:]]|$)" "$file" 2>/dev/null) || {
		echo "no '$type' line for $module in $file"
		return 1
	}
	if [ "$(wc -l <<<"$line")" -ne 1 ]; then
		echo "more than one '$type' line for $module in $file"
		return 1
	fi
	case "$(awk '{ print $2 }' <<<"$line")" in
	required | requisite) ;;
	*)
		echo "$module in $file is not 'required' or 'requisite'"
		return 1
		;;
	esac
	for opt in "$@"; do
		case " $line " in
		*[[:space:]]"$opt"[[:space:]]*) ;;
		*)
			echo "$module in $file is missing option $opt"
			return 1
			;;
		esac
	done
}

# Does module $2's password line come before pam_unix.so's in $1? pam_unix
# sets the new password; a check after it comes too late.
pam_password_before_unix() {
	local file=$1
	local module=$2
	local mine unix
	mine=$(grep -n -E "^password[[:space:]]+[^[:space:]]+[[:space:]]+${module//./\\.}([[:space:]]|$)" "$file" | cut -d: -f1 | head -n 1) || true
	unix=$(grep -n -E "^password[[:space:]]+[^[:space:]]+[[:space:]]+pam_unix\.so([[:space:]]|$)" "$file" | cut -d: -f1 | head -n 1) || true
	if [ -n "$mine" ] && [ -n "$unix" ] && [ "$mine" -gt "$unix" ]; then
		echo "$module comes after pam_unix.so in $file"
		return 1
	fi
}

# Print service file $1 with exactly the pam_faillock lines this package
# configures: preauth before the common-auth include, authfail after it,
# and an account line before the common-account include. Any other
# pam_faillock line is dropped. Fails if $1 lacks either include.
# The service files pull in common-auth as a substack or include, so no
# line can skip authfail on success: it runs after a successful
# authentication too. It then returns PAM_IGNORE, which 'required' ignores
# and a [default=die] control would turn into a denial; the account line
# clears the failure it records.
pam_faillock_render() {
	awk -v opts="${FAILLOCK_OPTS[*]}" '
		$3 == "pam_faillock.so" { next }
		$1 == "auth" && $3 == "common-auth" && !auth {
			print "auth\trequired\tpam_faillock.so preauth " opts
			print
			print "auth\trequired\tpam_faillock.so authfail " opts
			auth = 1
			next
		}
		$1 == "account" && $3 == "common-account" && !account {
			print "account\trequired\tpam_faillock.so"
			account = 1
		}
		{ print }
		END { exit !(auth && account) }
	' "$1"
}

# Does service file $1 contain the pam_faillock lines as
# pam_faillock_render writes them?
pam_faillock_ok() {
	local expected
	expected=$(pam_faillock_render "$1") || {
		echo "$1 doesn't include common-auth and common-account"
		return 1
	}
	if [ "$expected" != "$(<"$1")" ]; then
		echo "$1 lacks pam_faillock.so (${FAILLOCK_OPTS[*]}) around its common-auth and common-account includes"
		return 1
	fi
}

# The PAM file a service uses: /etc/pam.d replaces /usr/lib/pam.d as a
# whole. Empty if the service doesn't exist on this system.
pam_service_file() {
	local f
	for f in "/etc/pam.d/$1" "/usr/lib/pam.d/$1"; do
		if [ -e "$f" ]; then
			echo "$f"
			return 0
		fi
	done
}

# Copy a vendor service file to /etc/pam.d, as pam-config does for
# --service, so it can be changed. The explicit mode matters: a plain copy
# would inherit the caller's umask.
pam_service_override() {
	if [ ! -e "/etc/pam.d/$1" ] && [ -e "/usr/lib/pam.d/$1" ]; then
		install -m 0644 "/usr/lib/pam.d/$1" "/etc/pam.d/$1"
	fi
}

# Rewrite /etc/pam.d/$1 as pam_faillock_render prints it.
pam_faillock_write() {
	local file=/etc/pam.d/$1
	local tmp

	tmp=$(mktemp)
	if ! pam_faillock_render "$file" >"$tmp"; then
		rm -f "$tmp"
		echo "FAILED: $file doesn't include common-auth and common-account - no account lockout configured for it"
		return 1
	fi
	# Writing through the existing file keeps its mode, owner and SELinux
	# label.
	cat "$tmp" >"$file"
	rm -f "$tmp"
}

check_30_cc_pam_config() {
	local svc file
	pam_line_has /etc/pam.d/common-password password pam_pwquality.so "${PWQUALITY_OPTS[@]}" || return 1
	pam_line_has /etc/pam.d/common-password password pam_pwhistory.so "${PWHISTORY_OPTS[@]}" || return 1
	pam_password_before_unix /etc/pam.d/common-password pam_pwquality.so || return 1
	pam_password_before_unix /etc/pam.d/common-password pam_pwhistory.so || return 1
	pam_line_has /etc/pam.d/sshd session pam_loginuid.so "${LOGINUID_OPTS[@]}" || return 1
	for svc in "${FAILLOCK_SERVICES[@]}"; do
		file=$(pam_service_file "$svc")
		if [ -n "$file" ]; then
			pam_faillock_ok "$file" || return 1
		fi
	done
	# In a chroot, is-active reports success for any unit.
	if cc_in_chroot; then
		if ! systemctl is-enabled --quiet auditd; then
			echo "auditd is not enabled"
			return 1
		fi
	elif ! systemctl is-active --quiet auditd; then
		echo "auditd is not running"
		return 1
	fi
}

apply_30_cc_pam_config() {
	local svc file

	if check_30_cc_pam_config >/dev/null; then
		echo "PAM already configured"
		return 0
	fi

	# password quality check is always performed
	pam-config -a --pwquality "${PWQUALITY_OPTS[@]/#/--pwquality-}"
	echo "pam_pwquality.so configured for global service"

	# password history. Must run after --pwquality above, not before: each
	# --pwquality run rewrites the password stack without pam_pwhistory's
	# use_authtok, which this run puts back.
	pam-config -a --pwhistory "${PWHISTORY_OPTS[@]/#/--pwhistory-}"
	echo "pam_pwhistory.so configured for global service"

	# require auditd to be running for remote logins. pam_loginuid.so's
	# require_auditd option denies the whole session (not just this check)
	# if auditd isn't active at login time - applying it while auditd is
	# stopped would lock out every subsequent SSH login, including a
	# still-connected administrator's own session, so make sure auditd is
	# actually running first rather than trusting it already is. In a chroot,
	# nobody logs in until the system is booted, and auditd only has to start
	# then.
	if cc_in_chroot; then
		if ! systemctl is-enabled --quiet auditd; then
			systemctl enable auditd
			echo "auditd was not enabled - enabled it, so it starts when this system is booted"
		fi
	elif ! systemctl is-active --quiet auditd; then
		systemctl enable --now auditd || {
			echo "FAILED: could not start auditd - refusing to enable pam_loginuid's require_auditd (would lock out SSH logins)"
			return 1
		}
		echo "auditd was not running - enabled and started it"
	fi

	# sshd's PAM file only exists in /usr/lib/pam.d until something overrides
	# it. pam-config copies it to /etc/pam.d itself, but prints "Cannot stat
	# '/etc/pam.d/sshd'" while doing so, which reads like a failure. Copying
	# it first gives the same file without the message.
	pam_service_override sshd
	pam-config --service sshd -a --loginuid "${LOGINUID_OPTS[@]/#/--loginuid-}"
	echo "pam_loginuid.so configured for service sshd"

	# pam-config has no option for pam_faillock, but keeps the lines of
	# modules it doesn't manage when it rewrites a file.
	for svc in "${FAILLOCK_SERVICES[@]}"; do
		file=$(pam_service_file "$svc")
		if [ -z "$file" ]; then
			echo "NOTE: no PAM service $svc - no account lockout configured for it"
			continue
		fi
		if pam_faillock_ok "$file" >/dev/null; then
			continue
		fi
		pam_service_override "$svc"
		pam_faillock_write "$svc" || return 1
		echo "pam_faillock.so configured for service $svc (${FAILLOCK_OPTS[*]})"
	done

	check_30_cc_pam_config || {
		echo "FAILED: PAM configuration does not verify after applying"
		return 1
	}
}
