#!/bin/bash

. /usr/lib/common-criteria/scripts/libcc

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

# password quality check is always performed
cc_exec_log pam-config -a --cracklib --cracklib-retry=3 --cracklib-difok=3 --cracklib-minlen=12 --cracklib-dcredit=-1 --cracklib-ucredit=-1 --cracklib-lcredit=-1 --cracklib-ocredit=-1 || {
	ret=$?
	cc_echo "Cannot configure pam_cracklib.so"
	cc_exit $ret
}
cc_echo "pam_cracklib.so configured for global service"

# password history
cc_exec_log pam-config -a --pwhistory --pwhistory-use_authtok --pwhistory-enforce_for_root --pwhistory-remember=7 || {
	ret=$?
	cc_echo "Cannot configure pam_pwhistory.so"
	cc_exit $ret
}
cc_echo "pam_pwhistory.so configured for global service"

# require auditd to be running for remote logins
cc_exec_log pam-config --service sshd -a --loginuid --loginuid-require_auditd || {
	ret=$?
	cc_echo "Cannot configure pam_loginuid for service sshd"
	cc_exit $ret
}
cc_echo "pam_loginuid.so configured for service sshd"

# This is the last step - nothing must come afterwards
# we do not include su as this is restricted to the wheel group
# we do not include sudo,passwd,vlock,... as they require your own password
FILES="login sshd"

for i in $FILES
do
	trapfiles="$trapfiles $i.$$"
done
trap "cd /etc/pam.d; cc_exec_log rm -f $trapfiles" 0 1 2 3 15

cd /etc/pam.d
for file in $FILES
do
	[ ! -f $file ] && {
		cc_echo "PAM configuration file $file does not exist"
		continue
	}
	foundauth=0
	foundaccount=0
	while read line
	do
		# we remove all pam_tally entries to allow that script
		# to be called multiple times
		echo $line | grep -q -v "pam_tally2.so" || continue
		[ $(echo $line | cut -f1 -d" ") = "auth" ] && foundauth=1
		[ $(echo $line | cut -f1 -d" ") = "account" ] && foundaccount=1

		# we add the pam_tally2.so before the common-* includes
		[ "$foundauth" = "1" -a $(echo $line | cut -f3 -d" ") = "common-auth" ] && {
			foundauth=2
			echo -e "auth\t required\tpam_tally2.so deny=5 onerr=fail" >> /etc/pam.d/$file.$$
		}
		[ "$foundaccount" = "1" -a $(echo $line | cut -f3 -d" ") = "common-account" ] && {
			foundaccount=2
			echo -e "account  required\tpam_tally2.so" >> /etc/pam.d/$file.$$
		}
		echo "$line" >> /etc/pam.d/$file.$$
	done < /etc/pam.d/$file
	# just as a savety
	[ "$foundauth" = "1" ] && \
		echo -e "auth\t  required\t pam_tally2.so deny=5 onerr=fail" >> /etc/pam.d/$file.$$
	[ "$foundaccount" = "1" ] && \
		echo -e "account  required\t pam_tally2.so" >> /etc/pam.d/$file.$$
	cc_replace /etc/pam.d/$file.$$ /etc/pam.d/$file
	cc_echo "pam_tally2.so configured for service $file"
done

cc_exit 0