#	$OpenBSD: ssh-pkcs11.sh,v 1.1 2025/10/16 00:01:54 djm Exp $
#	Placed in the Public Domain.

tid="pkcs11 ssh test"

. ../tests/pkcs11-env

SSH_MODULE_LOG="$OBJ/.ssh-module.log"
> "$SSH_MODULE_LOG" || exit $?

p11_find_module || skip "SoftHSM module not found"
p11_find_SOFTHSM2_TOOL || skip "SoftHSM tool not found"
p11_token_conf || skip "fail to configure pkcs#11 token"
. ./pkcs11-func
p11_genkeys || skip "fail to load keys to pkcs#11 token"

( grep -vi IdentityFile $OBJ/ssh_proxy | \
  grep -vi BatchMode
  echo PKCS11Provider $TEST_SSH_PKCS11
  echo IdentitiesOnly yes
) > $OBJ/ssh_proxy.orig

KEY_TYPES="RSA EC"
if $openssl_fips_mode ; then
	openssl_version=`$OPENSSL version`
	case "$openssl_version" in
	*"OpenSSL 0.9"*|\
	*"OpenSSL 1."*)
		# TODO: non-OpenSSL FIPS module?
		verbose "$tag: RSA private encrypt is not allowed in FIPS mode"
		KEY_TYPES="EC"
		;;
	esac
fi

check_all() {
	tag="$1"
	expect_success=$2
	pin="$3"
	for k in $KEY_TYPES; do
		verbose "$tag: $k"

		cp $OBJ/ssh_proxy.orig $OBJ/ssh_proxy
		echo "IdentityFile $SSH_SOFTHSM_DIR/$k.pub" >> $OBJ/ssh_proxy
		cat $SSH_SOFTHSM_DIR/$k.pub > $OBJ/authorized_keys_$USER

		(
		TEST_SSH_PIN=$pin
		rm -f $P11_ASKPASS
		if test -n "$TEST_SSH_PIN" ; then
			cre_ssh_p11_askpass
		else
			P11_ASKPASS=:
		fi

		SSH_ASKPASS_REQUIRE=force \
		SSH_ASKPASS=$P11_ASKPASS \
		$SSH -F $OBJ/ssh_proxy somehost exit 5
		) >/dev/null 2>&1
		r=$?
		if test $r -ne 5 ; then
			$expect_success && \
			fail "ssh connect failed (exit code $r)"
		else
			$expect_success || \
			fail "ssh connect succeeded unexpectedly"
		fi
	done
}

check_all "correct pin" : $TEST_SSH_PIN
check_all "wrong pin" false 0000
check_all "nopin" false ''
