#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: Test timed faillog via ssh
## roles: [domaincontroller_master]
## tags: [basic, univention]
## packages: [univention-directory-manager-tools]
## exposure: dangerous
## versions:
##  1.0-0: skip
##  2.4-0: fixed

LOCKTIME=20

# shellcheck source=../../lib/ucr.sh
. "$TESTLIBPATH/ucr.sh" || exit 137
# shellcheck source=../../lib/user.sh
. "$TESTLIBPATH/user.sh" || exit 137
# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137

RETVAL=100
NAME=$(user_randomname)

ucr set \
	auth/faillog=yes \
	auth/faillog/lock_global=no \
	auth/faillog/limit=6 \
	auth/faillog/unlock_time="${LOCKTIME}" \
	sshd/challengeresponse=yes \
	sshd/passwordauthentication=no

invoke-rc.d ssh restart

tdir=$(mktemp -d)
trap "rm -rf '$tdir' ; udm mail/domain remove --dn 'cn=$domainname,$ldap_base' ; user_remove '$NAME' ; ucr_restore ; invoke-rc.d ssh restart" EXIT
fake_passwd="$tdir/fake_passwd"
echo "foobar1234" >"$fake_passwd"

ssh_login () {
	univention-ssh -timeout 10 "$1" -o NumberOfPasswordPrompts=3 "$NAME@$hostname.$domainname" /usr/sbin/ucr get hostname
}

udm mail/domain create --set name="$domainname"
user_create "$NAME" \
	--set password="$(<$tests_domainadmin_pwdfile)" \
	--set primaryGroup="$(get_domain_admins_dn)"

attempts=10
i=0
while ((i < attempts)) && ! /usr/lib/univention-pam/ldap-group-to-file.py; do
	((i+=1))
	sleep 1
done
if ((i==attempts)); then
	warning "ldap-group-to-file.py failed $i times"
fi

info "Lock after tally"
ssh_login "$fake_passwd" # 3
ssh_login "$fake_passwd" # 6
ssh_login "$fake_passwd" # 9
ssh_hostname="$(ssh_login "$tests_domainadmin_pwdfile")"
if [ "$ssh_hostname" = "$hostname" ]
then
	fail_test 1 "ssh login was successful, but the user should be locked"
fi

info "Wait for timeout ${LOCKTIME}"
sleep "${LOCKTIME}"

ssh_hostname="$(ssh_login "$tests_domainadmin_pwdfile")"
if [ "$ssh_hostname" != "$hostname" ]
then
	fail_test 1 "ssh login wasn't successful"
fi

exit $RETVAL
# vim: set ft=sh :
