rcolebaugh / rpms / openssh

Forked from rpms/openssh 2 years ago
Clone
9070b3
diff -up openssh-8.6p1/configure.ac.pkcs11-uri openssh-8.6p1/configure.ac
9070b3
--- openssh-8.6p1/configure.ac.pkcs11-uri	2021-05-06 11:35:55.101653187 +0200
9070b3
+++ openssh-8.6p1/configure.ac	2021-05-06 11:35:55.111653265 +0200
9070b3
@@ -1974,12 +1974,14 @@ AC_LINK_IFELSE(
9070b3
 	[AC_DEFINE([HAVE_ISBLANK], [1], [Define if you have isblank(3C).])
9070b3
 ])
9070b3
 
9070b3
+SCARD_MSG="yes"
9070b3
 disable_pkcs11=
9070b3
 AC_ARG_ENABLE([pkcs11],
9070b3
 	[  --disable-pkcs11        disable PKCS#11 support code [no]],
9070b3
 	[
9070b3
 		if test "x$enableval" = "xno" ; then
9070b3
 			disable_pkcs11=1
9070b3
+			SCARD_MSG="no"
9070b3
 		fi
9070b3
 	]
9070b3
 )
9070b3
@@ -2008,6 +2010,40 @@ AC_SEARCH_LIBS([dlopen], [dl])
9070b3
 AC_CHECK_FUNCS([dlopen])
9070b3
 AC_CHECK_DECL([RTLD_NOW], [], [], [#include <dlfcn.h>])
9070b3
 
9070b3
+# Check whether we have a p11-kit, we got default provider on command line
9070b3
+DEFAULT_PKCS11_PROVIDER_MSG="no"
9070b3
+AC_ARG_WITH([default-pkcs11-provider],
9070b3
+	[  --with-default-pkcs11-provider[[=PATH]]   Use default pkcs11 provider (p11-kit detected by default)],
9070b3
+	[ if test "x$withval" != "xno" && test "x$disable_pkcs11" = "x"; then
9070b3
+		if test "x$withval" = "xyes" ; then
9070b3
+			AC_PATH_TOOL([PKGCONFIG], [pkg-config], [no])
9070b3
+			if test "x$PKGCONFIG" != "xno"; then
9070b3
+				AC_MSG_CHECKING([if $PKGCONFIG knows about p11-kit])
9070b3
+				if "$PKGCONFIG" "p11-kit-1"; then
9070b3
+					AC_MSG_RESULT([yes])
9070b3
+					use_pkgconfig_for_p11kit=yes
9070b3
+				else
9070b3
+					AC_MSG_RESULT([no])
9070b3
+				fi
9070b3
+			fi
9070b3
+		else
9070b3
+			PKCS11_PATH="${withval}"
9070b3
+		fi
9070b3
+		if test "x$use_pkgconfig_for_p11kit" = "xyes"; then
9070b3
+			PKCS11_PATH=`$PKGCONFIG --variable=proxy_module p11-kit-1`
9070b3
+		fi
9070b3
+		AC_CHECK_FILE("$PKCS11_PATH",
9070b3
+			[ AC_DEFINE_UNQUOTED([PKCS11_DEFAULT_PROVIDER], ["$PKCS11_PATH"], [Path to default PKCS#11 provider (p11-kit proxy)])
9070b3
+			  DEFAULT_PKCS11_PROVIDER_MSG="$PKCS11_PATH"
9070b3
+			],
9070b3
+			[ AC_MSG_ERROR([Requested PKCS11 provided not found]) ]
9070b3
+		)
9070b3
+	else
9070b3
+		AC_MSG_WARN([Needs PKCS11 support to enable default pkcs11 provider])
9070b3
+	fi ]
9070b3
+)
9070b3
+
9070b3
+
9070b3
 # IRIX has a const char return value for gai_strerror()
9070b3
 AC_CHECK_FUNCS([gai_strerror], [
9070b3
 	AC_DEFINE([HAVE_GAI_STRERROR])
9070b3
@@ -5564,6 +5600,7 @@ echo "                  BSD Auth support
9070b3
 echo "              Random number source: $RAND_MSG"
9070b3
 echo "             Privsep sandbox style: $SANDBOX_STYLE"
9070b3
 echo "                   PKCS#11 support: $enable_pkcs11"
9070b3
+echo "          Default PKCS#11 provider: $DEFAULT_PKCS11_PROVIDER_MSG"
9070b3
 echo "                  U2F/FIDO support: $enable_sk"
9070b3
 
9070b3
 echo ""
9070b3
diff -up openssh-8.6p1/Makefile.in.pkcs11-uri openssh-8.6p1/Makefile.in
9070b3
--- openssh-8.6p1/Makefile.in.pkcs11-uri	2021-05-06 11:35:55.054652818 +0200
9070b3
+++ openssh-8.6p1/Makefile.in	2021-05-06 11:58:16.895135904 +0200
9070b3
@@ -103,7 +103,7 @@ LIBSSH_OBJS=${LIBOPENSSH_OBJS} \
9070b3
 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-ecdsa.o ssh-ecdsa-sk.o \
9070b3
 	ssh-ed25519-sk.o ssh-rsa.o dh.o \
9070b3
 	msg.o progressmeter.o dns.o entropy.o gss-genr.o umac.o umac128.o \
9070b3
-	ssh-pkcs11.o smult_curve25519_ref.o \
9070b3
+	ssh-pkcs11.o ssh-pkcs11-uri.o smult_curve25519_ref.o \
9070b3
 	poly1305.o chacha.o cipher-chachapoly.o cipher-chachapoly-libcrypto.o \
9070b3
 	ssh-ed25519.o digest-openssl.o digest-libc.o \
9070b3
 	hmac.o sc25519.o ge25519.o fe25519.o ed25519.o verify.o hash.o \
9070b3
@@ -300,6 +300,8 @@ clean:	regressclean
9070b3
 	rm -f regress/unittests/sshsig/test_sshsig$(EXEEXT)
9070b3
 	rm -f regress/unittests/utf8/*.o
9070b3
 	rm -f regress/unittests/utf8/test_utf8$(EXEEXT)
9070b3
+	rm -f regress/unittests/pkcs11/*.o
9070b3
+	rm -f regress/unittests/pkcs11/test_pkcs11$(EXEEXT)
9070b3
 	rm -f regress/misc/sk-dummy/*.o
9070b3
 	rm -f regress/misc/sk-dummy/*.lo
9070b3
 	rm -f regress/misc/sk-dummy/sk-dummy.so
9070b3
@@ -337,6 +339,8 @@ distclean:	regressclean
9070b3
 	rm -f regress/unittests/sshsig/test_sshsig
9070b3
 	rm -f regress/unittests/utf8/*.o
9070b3
 	rm -f regress/unittests/utf8/test_utf8
9070b3
+	rm -f regress/unittests/pkcs11/*.o
9070b3
+	rm -f regress/unittests/pkcs11/test_pkcs11
9070b3
 	(cd openbsd-compat && $(MAKE) distclean)
9070b3
 	if test -d pkg ; then \
9070b3
 		rm -fr pkg ; \
9070b3
@@ -511,6 +515,7 @@ regress-prep:
9070b3
 	$(MKDIR_P) `pwd`/regress/unittests/sshkey
9070b3
 	$(MKDIR_P) `pwd`/regress/unittests/sshsig
9070b3
 	$(MKDIR_P) `pwd`/regress/unittests/utf8
9070b3
+	$(MKDIR_P) `pwd`/regress/unittests/pkcs11
9070b3
 	$(MKDIR_P) `pwd`/regress/misc/sk-dummy
9070b3
 	[ -f `pwd`/regress/Makefile ] || \
9070b3
 	    ln -s `cd $(srcdir) && pwd`/regress/Makefile `pwd`/regress/Makefile
9070b3
@@ -674,6 +679,16 @@ regress/unittests/utf8/test_utf8$(EXEEXT
9070b3
 	    regress/unittests/test_helper/libtest_helper.a \
9070b3
 	    -lssh -lopenbsd-compat -lssh -lopenbsd-compat $(LIBS)
9070b3
 
9070b3
+UNITTESTS_TEST_PKCS11_OBJS=\
9070b3
+	regress/unittests/pkcs11/tests.o
9070b3
+
9070b3
+regress/unittests/pkcs11/test_pkcs11$(EXEEXT): \
9070b3
+    ${UNITTESTS_TEST_PKCS11_OBJS} \
9070b3
+    regress/unittests/test_helper/libtest_helper.a libssh.a
9070b3
+	$(LD) -o $@ $(LDFLAGS) $(UNITTESTS_TEST_PKCS11_OBJS) \
9070b3
+	    regress/unittests/test_helper/libtest_helper.a \
9070b3
+	    -lssh -lopenbsd-compat -lssh -lopenbsd-compat $(LIBS)
9070b3
+
9070b3
 # These all need to be compiled -fPIC, so they are treated differently.
9070b3
 SK_DUMMY_OBJS=\
9070b3
 	regress/misc/sk-dummy/sk-dummy.lo \
9070b3
@@ -711,7 +726,8 @@ regress-unit-binaries: regress-prep $(RE
9070b3
 	regress/unittests/sshbuf/test_sshbuf$(EXEEXT) \
9070b3
 	regress/unittests/sshkey/test_sshkey$(EXEEXT) \
9070b3
 	regress/unittests/sshsig/test_sshsig$(EXEEXT) \
9070b3
-	regress/unittests/utf8/test_utf8$(EXEEXT)
9070b3
+	regress/unittests/utf8/test_utf8$(EXEEXT) \
9070b3
+	regress/unittests/pkcs11/test_pkcs11$(EXEEXT) \
9070b3
 
9070b3
 tests:	file-tests t-exec interop-tests unit
9070b3
 	echo all tests passed
9070b3
diff -up openssh-8.6p1/regress/agent-pkcs11.sh.pkcs11-uri openssh-8.6p1/regress/agent-pkcs11.sh
9070b3
--- openssh-8.6p1/regress/agent-pkcs11.sh.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/regress/agent-pkcs11.sh	2021-05-06 11:35:55.112653273 +0200
9070b3
@@ -113,7 +113,7 @@ else
9070b3
 	done
9070b3
 
9070b3
 	trace "remove pkcs11 keys"
9070b3
-	echo ${TEST_SSH_PIN} | notty ${SSHADD} -e ${TEST_SSH_PKCS11} > /dev/null 2>&1
9070b3
+	${SSHADD} -e ${TEST_SSH_PKCS11} > /dev/null 2>&1
9070b3
 	r=$?
9070b3
 	if [ $r -ne 0 ]; then
9070b3
 		fail "ssh-add -e failed: exit code $r"
9070b3
diff -up openssh-8.6p1/regress/Makefile.pkcs11-uri openssh-8.6p1/regress/Makefile
9070b3
--- openssh-8.6p1/regress/Makefile.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/regress/Makefile	2021-05-06 11:59:24.465658383 +0200
9070b3
@@ -119,7 +119,8 @@ CLEANFILES=	*.core actual agent-key.* au
9070b3
 		known_hosts known_hosts-cert known_hosts.* krl-* ls.copy \
9070b3
 		modpipe netcat no_identity_config \
9070b3
 		pidfile putty.rsa2 ready regress.log remote_pid \
9070b3
-		revoked-* rsa rsa-agent rsa-agent.pub rsa.pub rsa_ssh2_cr.prv \
9070b3
+		revoked-* rsa rsa-agent rsa-agent.pub rsa-agent-cert.pub \
9070b3
+		rsa.pub rsa_ssh2_cr.prv pkcs11*.crt pkcs11*.key pkcs11.info \
9070b3
 		rsa_ssh2_crnl.prv scp-ssh-wrapper.exe \
9070b3
 		scp-ssh-wrapper.scp setuid-allowed sftp-server.log \
9070b3
 		sftp-server.sh sftp.log ssh-log-wrapper.sh ssh.log \
9070b3
@@ -249,6 +250,7 @@ unit:
9070b3
 		V="" ; \
9070b3
 		test "x${USE_VALGRIND}" = "x" || \
9070b3
 		    V=${.CURDIR}/valgrind-unit.sh ; \
9070b3
+		 $$V ${.OBJDIR}/unittests/pkcs11/test_pkcs11 ; \
9070b3
 		 $$V ${.OBJDIR}/unittests/sshbuf/test_sshbuf ; \
9070b3
 		 $$V ${.OBJDIR}/unittests/sshkey/test_sshkey \
9070b3
 			-d ${.CURDIR}/unittests/sshkey/testdata ; \
9070b3
diff -up openssh-8.6p1/regress/pkcs11.sh.pkcs11-uri openssh-8.6p1/regress/pkcs11.sh
9070b3
--- openssh-8.6p1/regress/pkcs11.sh.pkcs11-uri	2021-05-06 11:35:55.112653273 +0200
9070b3
+++ openssh-8.6p1/regress/pkcs11.sh	2021-05-06 11:35:55.112653273 +0200
9070b3
@@ -0,0 +1,349 @@
9070b3
+#
9070b3
+#  Copyright (c) 2017 Red Hat
9070b3
+#
9070b3
+#  Authors: Jakub Jelen <jjelen@redhat.com>
9070b3
+#
9070b3
+#  Permission to use, copy, modify, and distribute this software for any
9070b3
+#  purpose with or without fee is hereby granted, provided that the above
9070b3
+#  copyright notice and this permission notice appear in all copies.
9070b3
+#
9070b3
+#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9070b3
+#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9070b3
+#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
9070b3
+#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
9070b3
+#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
9070b3
+#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
9070b3
+#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
9070b3
+
9070b3
+tid="pkcs11 tests with soft token"
9070b3
+
9070b3
+try_token_libs() {
9070b3
+	for _lib in "$@" ; do
9070b3
+		if test -f "$_lib" ; then
9070b3
+			verbose "Using token library $_lib"
9070b3
+			TEST_SSH_PKCS11="$_lib"
9070b3
+			return
9070b3
+		fi
9070b3
+	done
9070b3
+	echo "skipped: Unable to find PKCS#11 token library"
9070b3
+	exit 0
9070b3
+}
9070b3
+
9070b3
+try_token_libs \
9070b3
+	/usr/local/lib/softhsm/libsofthsm2.so \
9070b3
+	/usr/lib64/pkcs11/libsofthsm2.so \
9070b3
+	/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so
9070b3
+
9070b3
+TEST_SSH_PIN=1234
9070b3
+TEST_SSH_SOPIN=12345678
9070b3
+if [ "x$TEST_SSH_SSHPKCS11HELPER" != "x" ]; then
9070b3
+	SSH_PKCS11_HELPER="${TEST_SSH_SSHPKCS11HELPER}"
9070b3
+	export SSH_PKCS11_HELPER
9070b3
+fi
9070b3
+
9070b3
+test -f "$TEST_SSH_PKCS11" || fatal "$TEST_SSH_PKCS11 does not exist"
9070b3
+
9070b3
+# setup environment for softhsm token
9070b3
+DIR=$OBJ/SOFTHSM
9070b3
+rm -rf $DIR
9070b3
+TOKEN=$DIR/tokendir
9070b3
+mkdir -p $TOKEN
9070b3
+SOFTHSM2_CONF=$DIR/softhsm2.conf
9070b3
+export SOFTHSM2_CONF
9070b3
+cat > $SOFTHSM2_CONF << EOF
9070b3
+# SoftHSM v2 configuration file
9070b3
+directories.tokendir = ${TOKEN}
9070b3
+objectstore.backend = file
9070b3
+# ERROR, WARNING, INFO, DEBUG
9070b3
+log.level = DEBUG
9070b3
+# If CKF_REMOVABLE_DEVICE flag should be set
9070b3
+slots.removable = false
9070b3
+EOF
9070b3
+out=$(softhsm2-util --init-token --free --label token-slot-0 --pin "$TEST_SSH_PIN" --so-pin "$TEST_SSH_SOPIN")
9070b3
+slot=$(echo -- $out | sed 's/.* //')
9070b3
+
9070b3
+# prevent ssh-agent from calling ssh-askpass
9070b3
+SSH_ASKPASS=/usr/bin/true
9070b3
+export SSH_ASKPASS
9070b3
+unset DISPLAY
9070b3
+# We need interactive access to test PKCS# since it prompts for PIN
9070b3
+sed -i 's/.*BatchMode.*//g' $OBJ/ssh_proxy
9070b3
+
9070b3
+# start command w/o tty, so ssh accepts pin from stdin (from agent-pkcs11.sh)
9070b3
+notty() {
9070b3
+	perl -e 'use POSIX; POSIX::setsid();
9070b3
+	    if (fork) { wait; exit($? >> 8); } else { exec(@ARGV) }' "$@"
9070b3
+}
9070b3
+
9070b3
+trace "generating keys"
9070b3
+ID1="02"
9070b3
+ID2="04"
9070b3
+RSA=${DIR}/RSA
9070b3
+EC=${DIR}/EC
9070b3
+openssl genpkey -algorithm rsa > $RSA
9070b3
+openssl pkcs8 -nocrypt -in $RSA |\
9070b3
+    softhsm2-util --slot "$slot" --label "SSH RSA Key $ID1" --id $ID1 \
9070b3
+	--pin "$TEST_SSH_PIN" --import /dev/stdin
9070b3
+openssl genpkey \
9070b3
+    -genparam \
9070b3
+    -algorithm ec \
9070b3
+    -pkeyopt ec_paramgen_curve:prime256v1 |\
9070b3
+    openssl genpkey \
9070b3
+    -paramfile /dev/stdin > $EC
9070b3
+openssl pkcs8 -nocrypt -in $EC |\
9070b3
+    softhsm2-util --slot "$slot" --label "SSH ECDSA Key $ID2" --id $ID2 \
9070b3
+	--pin "$TEST_SSH_PIN" --import /dev/stdin
9070b3
+
9070b3
+trace "List the keys in the ssh-keygen with PKCS#11 URIs"
9070b3
+${SSHKEYGEN} -D ${TEST_SSH_PKCS11} > $OBJ/token_keys
9070b3
+if [ $? -ne 0 ]; then
9070b3
+	fail "FAIL: keygen fails to enumerate keys on PKCS#11 token"
9070b3
+fi
9070b3
+grep "pkcs11:" $OBJ/token_keys > /dev/null
9070b3
+if [ $? -ne 0 ]; then
9070b3
+	fail "FAIL: The keys from ssh-keygen do not contain PKCS#11 URI as a comment"
9070b3
+fi
9070b3
+
9070b3
+# Set the ECDSA key to authorized keys
9070b3
+grep "ECDSA" $OBJ/token_keys > $OBJ/authorized_keys_$USER
9070b3
+
9070b3
+trace "Simple connect with ssh (without PKCS#11 URI)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -I ${TEST_SSH_PKCS11} \
9070b3
+    -F $OBJ/ssh_proxy somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with pkcs11 failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "Connect with PKCS#11 URI"
9070b3
+trace "  (ECDSA key should succeed)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+    -i "pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "  (RSA key should fail)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+     -i "pkcs11:id=%${ID1}?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI succeeded (should fail)"
9070b3
+fi
9070b3
+
9070b3
+trace "Connect with PKCS#11 URI including PIN should not prompt"
9070b3
+trace "  (ECDSA key should succeed)"
9070b3
+${SSH} -F $OBJ/ssh_proxy -i \
9070b3
+    "pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}&pin-value=${TEST_SSH_PIN}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "  (RSA key should fail)"
9070b3
+${SSH} -F $OBJ/ssh_proxy -i \
9070b3
+    "pkcs11:id=%${ID1}?module-path=${TEST_SSH_PKCS11}&pin-value=${TEST_SSH_PIN}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI succeeded (should fail)"
9070b3
+fi
9070b3
+
9070b3
+trace "Connect with various filtering options in PKCS#11 URI"
9070b3
+trace "  (by object label, ECDSA should succeed)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+    -i "pkcs11:object=SSH%20ECDSA%20Key%2004?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "  (by object label, RSA key should fail)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+     -i "pkcs11:object=SSH%20RSA%20Key%2002?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI succeeded (should fail)"
9070b3
+fi
9070b3
+
9070b3
+trace "  (by token label, ECDSA key should succeed)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+    -i "pkcs11:id=%${ID2};token=token-slot-0?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "  (by wrong token label, should fail)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+     -i "pkcs11:token=token-slot-99?module-path=${TEST_SSH_PKCS11}" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI succeeded (should fail)"
9070b3
+fi
9070b3
+
9070b3
+
9070b3
+
9070b3
+
9070b3
+trace "Test PKCS#11 URI specification in configuration files"
9070b3
+echo "IdentityFile \"pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}\"" \
9070b3
+    >> $OBJ/ssh_proxy
9070b3
+trace "  (ECDSA key should succeed)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI in config failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+# Set the RSA key as authorized
9070b3
+grep "RSA" $OBJ/token_keys > $OBJ/authorized_keys_$USER
9070b3
+
9070b3
+trace "  (RSA key should fail)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI in config succeeded (should fail)"
9070b3
+fi
9070b3
+sed -i -e "/IdentityFile/d" $OBJ/ssh_proxy
9070b3
+
9070b3
+trace "Test PKCS#11 URI specification in configuration files with bogus spaces"
9070b3
+echo "IdentityFile \"    pkcs11:?module-path=${TEST_SSH_PKCS11}    \"" \
9070b3
+    >> $OBJ/ssh_proxy
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI with bogus spaces in config failed" \
9070b3
+	    "(exit code $r)"
9070b3
+fi
9070b3
+sed -i -e "/IdentityFile/d" $OBJ/ssh_proxy
9070b3
+
9070b3
+
9070b3
+trace "Combination of PKCS11Provider and PKCS11URI on commandline"
9070b3
+trace "  (RSA key should succeed)"
9070b3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
9070b3
+    -i "pkcs11:id=%${ID1}" -I ${TEST_SSH_PKCS11} somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -ne 5 ]; then
9070b3
+	fail "FAIL: ssh connect with PKCS#11 URI and provider combination" \
9070b3
+	    "failed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+trace "Regress: Missing provider in PKCS11URI option"
9070b3
+${SSH} -F $OBJ/ssh_proxy \
9070b3
+    -o IdentityFile=\"pkcs11:token=segfault\" somehost exit 5
9070b3
+r=$?
9070b3
+if [ $r -eq 139 ]; then
9070b3
+	fail "FAIL: ssh connect with missing provider_id from configuration option" \
9070b3
+	    "crashed (exit code $r)"
9070b3
+fi
9070b3
+
9070b3
+
9070b3
+trace "SSH Agent can work with PKCS#11 URI"
9070b3
+trace "start the agent"
9070b3
+eval `${SSHAGENT} -s` >  /dev/null
9070b3
+
9070b3
+r=$?
9070b3
+if [ $r -ne 0 ]; then
9070b3
+	fail "could not start ssh-agent: exit code $r"
9070b3
+else
9070b3
+	trace "add whole provider to agent"
9070b3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
9070b3
+	    "pkcs11:?module-path=${TEST_SSH_PKCS11}" #> /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add failed with whole provider: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " pkcs11 list via agent (all keys)"
9070b3
+	${SSHADD} -l > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add -l failed with whole provider: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " pkcs11 connect via agent (all keys)"
9070b3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+	r=$?
9070b3
+	if [ $r -ne 5 ]; then
9070b3
+		fail "FAIL: ssh connect failed with whole provider (exit code $r)"
9070b3
+	fi
9070b3
+
9070b3
+	trace " remove pkcs11 keys (all keys)"
9070b3
+	${SSHADD} -d "pkcs11:?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add -d failed with whole provider: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace "add only RSA key to the agent"
9070b3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
9070b3
+	    "pkcs11:id=%${ID1}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL ssh-add failed with RSA key: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " pkcs11 connect via agent (RSA key)"
9070b3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+	r=$?
9070b3
+	if [ $r -ne 5 ]; then
9070b3
+		fail "FAIL: ssh connect failed with RSA key (exit code $r)"
9070b3
+	fi
9070b3
+
9070b3
+	trace " remove RSA pkcs11 key"
9070b3
+	${SSHADD} -d "pkcs11:id=%${ID1}?module-path=${TEST_SSH_PKCS11}" \
9070b3
+	    > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add -d failed with RSA key: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace "add only ECDSA key to the agent"
9070b3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
9070b3
+	    "pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add failed with second key: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " pkcs11 connect via agent (ECDSA key should fail)"
9070b3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+	r=$?
9070b3
+	if [ $r -eq 5 ]; then
9070b3
+		fail "FAIL: ssh connect passed with ECDSA key (should fail)"
9070b3
+	fi
9070b3
+
9070b3
+	trace "add also the RSA key to the agent"
9070b3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
9070b3
+	    "pkcs11:id=%${ID1}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "FAIL: ssh-add failed with first key: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " remove ECDSA pkcs11 key"
9070b3
+	${SSHADD} -d "pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}" \
9070b3
+	    > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -ne 0 ]; then
9070b3
+		fail "ssh-add -d failed with ECDSA key: exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace " remove already-removed pkcs11 key should fail"
9070b3
+	${SSHADD} -d "pkcs11:id=%${ID2}?module-path=${TEST_SSH_PKCS11}" \
9070b3
+	    > /dev/null 2>&1
9070b3
+	r=$?
9070b3
+	if [ $r -eq 0 ]; then
9070b3
+		fail "FAIL: ssh-add -d passed with non-existing key (should fail)"
9070b3
+	fi
9070b3
+
9070b3
+	trace " pkcs11 connect via agent (the RSA key should be still usable)"
9070b3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
9070b3
+	r=$?
9070b3
+	if [ $r -ne 5 ]; then
9070b3
+		fail "ssh connect failed with RSA key (after removing ECDSA): exit code $r"
9070b3
+	fi
9070b3
+
9070b3
+	trace "kill agent"
9070b3
+	${SSHAGENT} -k > /dev/null
9070b3
+fi
9070b3
diff -up openssh-8.6p1/regress/unittests/Makefile.pkcs11-uri openssh-8.6p1/regress/unittests/Makefile
9070b3
--- openssh-8.6p1/regress/unittests/Makefile.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/regress/unittests/Makefile	2021-05-06 11:35:55.112653273 +0200
9070b3
@@ -2,6 +2,6 @@
9070b3
 
9070b3
 REGRESS_FAIL_EARLY?=	yes
9070b3
 SUBDIR=	test_helper sshbuf sshkey bitmap kex hostkeys utf8 match conversion
9070b3
-SUBDIR+=authopt misc sshsig
9070b3
+SUBDIR+=authopt misc sshsig pkcs11
9070b3
 
9070b3
 .include <bsd.subdir.mk>
9070b3
diff -up openssh-8.6p1/regress/unittests/pkcs11/tests.c.pkcs11-uri openssh-8.6p1/regress/unittests/pkcs11/tests.c
9070b3
--- openssh-8.6p1/regress/unittests/pkcs11/tests.c.pkcs11-uri	2021-05-06 11:35:55.112653273 +0200
9070b3
+++ openssh-8.6p1/regress/unittests/pkcs11/tests.c	2021-05-06 11:35:55.112653273 +0200
9070b3
@@ -0,0 +1,337 @@
9070b3
+/*
9070b3
+ * Copyright (c) 2017 Red Hat
9070b3
+ *
9070b3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
9070b3
+ *
9070b3
+ * Permission to use, copy, modify, and distribute this software for any
9070b3
+ * purpose with or without fee is hereby granted, provided that the above
9070b3
+ * copyright notice and this permission notice appear in all copies.
9070b3
+ *
9070b3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9070b3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9070b3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
9070b3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
9070b3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
9070b3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
9070b3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
9070b3
+ */
9070b3
+
9070b3
+#include "includes.h"
9070b3
+
9070b3
+#include <locale.h>
9070b3
+#include <string.h>
9070b3
+
9070b3
+#include "../test_helper/test_helper.h"
9070b3
+
9070b3
+#include "sshbuf.h"
9070b3
+#include "ssh-pkcs11-uri.h"
9070b3
+
9070b3
+#define EMPTY_URI compose_uri(NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL)
9070b3
+
9070b3
+/* prototypes are not public -- specify them here internally for tests */
9070b3
+struct sshbuf *percent_encode(const char *, size_t, char *);
9070b3
+int percent_decode(char *, char **);
9070b3
+
9070b3
+void
9070b3
+compare_uri(struct pkcs11_uri *a, struct pkcs11_uri *b)
9070b3
+{
9070b3
+	ASSERT_PTR_NE(a, NULL);
9070b3
+	ASSERT_PTR_NE(b, NULL);
9070b3
+	ASSERT_SIZE_T_EQ(a->id_len, b->id_len);
9070b3
+	ASSERT_MEM_EQ(a->id, b->id, a->id_len);
9070b3
+	if (b->object != NULL)
9070b3
+		ASSERT_STRING_EQ(a->object, b->object);
9070b3
+	else /* both should be null */
9070b3
+		ASSERT_PTR_EQ(a->object, b->object);
9070b3
+	if (b->module_path != NULL)
9070b3
+		ASSERT_STRING_EQ(a->module_path, b->module_path);
9070b3
+	else /* both should be null */
9070b3
+		ASSERT_PTR_EQ(a->module_path, b->module_path);
9070b3
+	if (b->token != NULL)
9070b3
+		ASSERT_STRING_EQ(a->token, b->token);
9070b3
+	else /* both should be null */
9070b3
+		ASSERT_PTR_EQ(a->token, b->token);
9070b3
+	if (b->manuf != NULL)
9070b3
+		ASSERT_STRING_EQ(a->manuf, b->manuf);
9070b3
+	else /* both should be null */
9070b3
+		ASSERT_PTR_EQ(a->manuf, b->manuf);
9070b3
+	if (b->lib_manuf != NULL)
9070b3
+		ASSERT_STRING_EQ(a->lib_manuf, b->lib_manuf);
9070b3
+	else /* both should be null */
9070b3
+		ASSERT_PTR_EQ(a->lib_manuf, b->lib_manuf);
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+check_parse_rv(char *uri, struct pkcs11_uri *expect, int expect_rv)
9070b3
+{
9070b3
+	char *buf = NULL, *str;
9070b3
+	struct pkcs11_uri *pkcs11uri = NULL;
9070b3
+	int rv;
9070b3
+
9070b3
+	if (expect_rv == 0)
9070b3
+		str = "Valid";
9070b3
+	else
9070b3
+		str = "Invalid";
9070b3
+	asprintf(&buf, "%s PKCS#11 URI parsing: %s", str, uri);
9070b3
+	TEST_START(buf);
9070b3
+	free(buf);
9070b3
+	pkcs11uri = pkcs11_uri_init();
9070b3
+	rv = pkcs11_uri_parse(uri, pkcs11uri);
9070b3
+	ASSERT_INT_EQ(rv, expect_rv);
9070b3
+	if (rv == 0) /* in case of failure result is undefined */
9070b3
+		compare_uri(pkcs11uri, expect);
9070b3
+	pkcs11_uri_cleanup(pkcs11uri);
9070b3
+	free(expect);
9070b3
+	TEST_DONE();
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+check_parse(char *uri, struct pkcs11_uri *expect)
9070b3
+{
9070b3
+	check_parse_rv(uri, expect, 0);
9070b3
+}
9070b3
+
9070b3
+struct pkcs11_uri *
9070b3
+compose_uri(unsigned char *id, size_t id_len, char *token, char *lib_manuf,
9070b3
+    char *manuf, char *module_path, char *object, char *pin)
9070b3
+{
9070b3
+	struct pkcs11_uri *uri = pkcs11_uri_init();
9070b3
+	if (id_len > 0) {
9070b3
+		uri->id_len = id_len;
9070b3
+		uri->id = id;
9070b3
+	}
9070b3
+	uri->module_path = module_path;
9070b3
+	uri->token = token;
9070b3
+	uri->lib_manuf = lib_manuf;
9070b3
+	uri->manuf = manuf;
9070b3
+	uri->object = object;
9070b3
+	uri->pin = pin;
9070b3
+	return uri;
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_parse_valid(void)
9070b3
+{
9070b3
+	/* path arguments */
9070b3
+	check_parse("pkcs11:id=%01",
9070b3
+	    compose_uri("\x01", 1, NULL, NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_parse("pkcs11:id=%00%01",
9070b3
+	    compose_uri("\x00\x01", 2, NULL, NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_parse("pkcs11:token=SSH%20Keys",
9070b3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_parse("pkcs11:library-manufacturer=OpenSC",
9070b3
+	    compose_uri(NULL, 0, NULL, "OpenSC", NULL, NULL, NULL, NULL));
9070b3
+	check_parse("pkcs11:manufacturer=piv_II",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, NULL, NULL));
9070b3
+	check_parse("pkcs11:object=SIGN%20Key",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, "SIGN Key", NULL));
9070b3
+	/* query arguments */
9070b3
+	check_parse("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
9070b3
+	check_parse("pkcs11:?pin-value=123456",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, NULL, "123456"));
9070b3
+
9070b3
+	/* combinations */
9070b3
+	/* ID SHOULD be percent encoded */
9070b3
+	check_parse("pkcs11:token=SSH%20Key;id=0",
9070b3
+	    compose_uri("0", 1, "SSH Key", NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_parse(
9070b3
+	    "pkcs11:manufacturer=CAC?module-path=/usr/lib64/p11-kit-proxy.so",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, "CAC",
9070b3
+	    "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
9070b3
+	check_parse(
9070b3
+	    "pkcs11:object=RSA%20Key?module-path=/usr/lib64/pkcs11/opencryptoki.so",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL,
9070b3
+	    "/usr/lib64/pkcs11/opencryptoki.so", "RSA Key", NULL));
9070b3
+	check_parse("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so&pin-value=123456",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, "123456"));
9070b3
+
9070b3
+	/* empty path component matches everything */
9070b3
+	check_parse("pkcs11:", EMPTY_URI);
9070b3
+
9070b3
+	/* empty string is a valid to match against (and different from NULL) */
9070b3
+	check_parse("pkcs11:token=",
9070b3
+	    compose_uri(NULL, 0, "", NULL, NULL, NULL, NULL, NULL));
9070b3
+	/* Percent character needs to be percent-encoded */
9070b3
+	check_parse("pkcs11:token=%25",
9070b3
+	     compose_uri(NULL, 0, "%", NULL, NULL, NULL, NULL, NULL));
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_parse_invalid(void)
9070b3
+{
9070b3
+	/* Invalid percent encoding */
9070b3
+	check_parse_rv("pkcs11:id=%0", EMPTY_URI, -1);
9070b3
+	/* Invalid percent encoding */
9070b3
+	check_parse_rv("pkcs11:id=%ZZ", EMPTY_URI, -1);
9070b3
+	/* Space MUST be percent encoded -- XXX not enforced yet */
9070b3
+	check_parse("pkcs11:token=SSH Keys",
9070b3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
9070b3
+	/* MUST NOT contain duplicate attributes of the same name */
9070b3
+	check_parse_rv("pkcs11:id=%01;id=%02", EMPTY_URI, -1);
9070b3
+	/* MUST NOT contain duplicate attributes of the same name */
9070b3
+	check_parse_rv("pkcs11:?pin-value=111111&pin-value=123456", EMPTY_URI, -1);
9070b3
+	/* Unrecognized attribute in path are ignored with log message */
9070b3
+	check_parse("pkcs11:key_name=SSH", EMPTY_URI);
9070b3
+	/* Unrecognized attribute in query SHOULD be ignored */
9070b3
+	check_parse("pkcs11:?key_name=SSH", EMPTY_URI);
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+check_gen(char *expect, struct pkcs11_uri *uri)
9070b3
+{
9070b3
+	char *buf = NULL, *uri_str;
9070b3
+
9070b3
+	asprintf(&buf, "Valid PKCS#11 URI generation: %s", expect);
9070b3
+	TEST_START(buf);
9070b3
+	free(buf);
9070b3
+	uri_str = pkcs11_uri_get(uri);
9070b3
+	ASSERT_PTR_NE(uri_str, NULL);
9070b3
+	ASSERT_STRING_EQ(uri_str, expect);
9070b3
+	free(uri_str);
9070b3
+	TEST_DONE();
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_generate_valid(void)
9070b3
+{
9070b3
+	/* path arguments */
9070b3
+	check_gen("pkcs11:id=%01",
9070b3
+	    compose_uri("\x01", 1, NULL, NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_gen("pkcs11:id=%00%01",
9070b3
+	    compose_uri("\x00\x01", 2, NULL, NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_gen("pkcs11:token=SSH%20Keys", /* space must be percent encoded */
9070b3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
9070b3
+	/* library-manufacturer is not implmented now */
9070b3
+	/*check_gen("pkcs11:library-manufacturer=OpenSC",
9070b3
+	    compose_uri(NULL, 0, NULL, "OpenSC", NULL, NULL, NULL, NULL));*/
9070b3
+	check_gen("pkcs11:manufacturer=piv_II",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, NULL, NULL));
9070b3
+	check_gen("pkcs11:object=RSA%20Key",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, "RSA Key", NULL));
9070b3
+	/* query arguments */
9070b3
+	check_gen("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
9070b3
+
9070b3
+	/* combinations */
9070b3
+	check_gen("pkcs11:id=%02;token=SSH%20Keys",
9070b3
+	    compose_uri("\x02", 1, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
9070b3
+	check_gen("pkcs11:id=%EE%02?module-path=/usr/lib64/p11-kit-proxy.so",
9070b3
+	    compose_uri("\xEE\x02", 2, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
9070b3
+	check_gen("pkcs11:object=Encryption%20Key;manufacturer=piv_II",
9070b3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, "Encryption Key", NULL));
9070b3
+
9070b3
+	/* empty path component matches everything */
9070b3
+	check_gen("pkcs11:", EMPTY_URI);
9070b3
+
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+check_encode(char *source, size_t len, char *allow_list, char *expect)
9070b3
+{
9070b3
+	char *buf = NULL;
9070b3
+	struct sshbuf *b;
9070b3
+
9070b3
+	asprintf(&buf, "percent_encode: expected %s", expect);
9070b3
+	TEST_START(buf);
9070b3
+	free(buf);
9070b3
+
9070b3
+	b = percent_encode(source, len, allow_list);
9070b3
+	ASSERT_STRING_EQ(sshbuf_ptr(b), expect);
9070b3
+	sshbuf_free(b);
9070b3
+	TEST_DONE();
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_percent_encode_multibyte(void)
9070b3
+{
9070b3
+	/* SHOULD be encoded as octets according to the UTF-8 character encoding */
9070b3
+
9070b3
+	/* multi-byte characters are "for free" */
9070b3
+	check_encode("$", 1, "", "%24");
9070b3
+	check_encode("¢", 2, "", "%C2%A2");
9070b3
+	check_encode("€", 3, "", "%E2%82%AC");
9070b3
+	check_encode("𐍈", 4, "", "%F0%90%8D%88");
9070b3
+
9070b3
+	/* CK_UTF8CHAR is unsigned char (1 byte) */
9070b3
+	/* labels SHOULD be normalized to NFC [UAX15] */
9070b3
+
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_percent_encode(void)
9070b3
+{
9070b3
+	/* Without allow list encodes everything (for CKA_ID) */
9070b3
+	check_encode("A*", 2, "", "%41%2A");
9070b3
+	check_encode("\x00", 1, "", "%00");
9070b3
+	check_encode("\x7F", 1, "", "%7F");
9070b3
+	check_encode("\x80", 1, "", "%80");
9070b3
+	check_encode("\xff", 1, "", "%FF");
9070b3
+
9070b3
+	/* Default allow list encodes anything but safe letters */
9070b3
+	check_encode("test" "\x00" "0alpha", 11, PKCS11_URI_WHITELIST,
9070b3
+	    "test%000alpha");
9070b3
+	check_encode(" ", 1, PKCS11_URI_WHITELIST,
9070b3
+	    "%20"); /* Space MUST be percent encoded */
9070b3
+	check_encode("/", 1, PKCS11_URI_WHITELIST,
9070b3
+	    "%2F"); /* '/' delimiter MUST be percent encoded (in the path) */
9070b3
+	check_encode("?", 1, PKCS11_URI_WHITELIST,
9070b3
+	    "%3F"); /* delimiter '?' MUST be percent encoded (in the path) */
9070b3
+	check_encode("#", 1, PKCS11_URI_WHITELIST,
9070b3
+	    "%23"); /* '#' MUST be always percent encoded */
9070b3
+	check_encode("key=value;separator?query&#anch", 35, PKCS11_URI_WHITELIST,
9070b3
+	    "key%3Dvalue%3Bseparator%3Fquery%26amp%3B%23anch");
9070b3
+
9070b3
+	/* Components in query can have '/' unencoded (useful for paths) */
9070b3
+	check_encode("/path/to.file", 13, PKCS11_URI_WHITELIST "/",
9070b3
+	    "/path/to.file");
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+check_decode(char *source, char *expect, int expect_len)
9070b3
+{
9070b3
+	char *buf = NULL, *out = NULL;
9070b3
+	int rv;
9070b3
+
9070b3
+	asprintf(&buf, "percent_decode: %s", source);
9070b3
+	TEST_START(buf);
9070b3
+	free(buf);
9070b3
+
9070b3
+	rv = percent_decode(source, &out;;
9070b3
+	ASSERT_INT_EQ(rv, expect_len);
9070b3
+	if (rv >= 0)
9070b3
+		ASSERT_MEM_EQ(out, expect, expect_len);
9070b3
+	free(out);
9070b3
+	TEST_DONE();
9070b3
+}
9070b3
+
9070b3
+static void
9070b3
+test_percent_decode(void)
9070b3
+{
9070b3
+	/* simple valid cases */
9070b3
+	check_decode("%00", "\x00", 1);
9070b3
+	check_decode("%FF", "\xFF", 1);
9070b3
+
9070b3
+	/* normal strings shold be kept intact */
9070b3
+	check_decode("strings are left", "strings are left", 16);
9070b3
+	check_decode("10%25 of trees", "10% of trees", 12);
9070b3
+
9070b3
+	/* make sure no more than 2 bytes are parsed */
9070b3
+	check_decode("%222", "\x22" "2", 2);
9070b3
+
9070b3
+	/* invalid expects failure */
9070b3
+	check_decode("%0", "", -1);
9070b3
+	check_decode("%Z", "", -1);
9070b3
+	check_decode("%FG", "", -1);
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+tests(void)
9070b3
+{
9070b3
+	test_percent_encode();
9070b3
+	test_percent_encode_multibyte();
9070b3
+	test_percent_decode();
9070b3
+	test_parse_valid();
9070b3
+	test_parse_invalid();
9070b3
+	test_generate_valid();
9070b3
+}
9070b3
diff -up openssh-8.6p1/ssh-add.c.pkcs11-uri openssh-8.6p1/ssh-add.c
9070b3
--- openssh-8.6p1/ssh-add.c.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-add.c	2021-05-06 11:35:55.112653273 +0200
9070b3
@@ -68,6 +68,7 @@
9070b3
 #include "digest.h"
9070b3
 #include "ssh-sk.h"
9070b3
 #include "sk-api.h"
9070b3
+#include "ssh-pkcs11-uri.h"
9070b3
 
9070b3
 /* argv0 */
9070b3
 extern char *__progname;
9070b3
@@ -229,6 +230,32 @@ delete_all(int agent_fd, int qflag)
9070b3
 	return ret;
9070b3
 }
9070b3
 
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+static int update_card(int, int, const char *, int, char *);
9070b3
+
9070b3
+int
9070b3
+update_pkcs11_uri(int agent_fd, int adding, const char *pkcs11_uri, int qflag)
9070b3
+{
9070b3
+	char *pin = NULL;
9070b3
+	struct pkcs11_uri *uri;
9070b3
+
9070b3
+	/* dry-run parse to make sure the URI is valid and to report errors */
9070b3
+	uri = pkcs11_uri_init();
9070b3
+	if (pkcs11_uri_parse((char *) pkcs11_uri, uri) != 0)
9070b3
+		fatal("Failed to parse PKCS#11 URI");
9070b3
+	if (uri->pin != NULL) {
9070b3
+		pin = strdup(uri->pin);
9070b3
+		if (pin == NULL) {
9070b3
+			fatal("Failed to dupplicate string");
9070b3
+		}
9070b3
+		/* pin is freed in the update_card() */
9070b3
+	}
9070b3
+	pkcs11_uri_cleanup(uri);
9070b3
+
9070b3
+	return update_card(agent_fd, adding, pkcs11_uri, qflag, pin);
9070b3
+}
9070b3
+#endif
9070b3
+
9070b3
 static int
9070b3
 add_file(int agent_fd, const char *filename, int key_only, int qflag,
9070b3
     const char *skprovider)
9070b3
@@ -445,12 +472,11 @@ add_file(int agent_fd, const char *filen
9070b3
 }
9070b3
 
9070b3
 static int
9070b3
-update_card(int agent_fd, int add, const char *id, int qflag)
9070b3
+update_card(int agent_fd, int add, const char *id, int qflag, char *pin)
9070b3
 {
9070b3
-	char *pin = NULL;
9070b3
 	int r, ret = -1;
9070b3
 
9070b3
-	if (add) {
9070b3
+	if (add && pin == NULL) {
9070b3
 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
9070b3
 		    RP_ALLOW_STDIN)) == NULL)
9070b3
 			return -1;
9070b3
@@ -630,6 +656,13 @@ static int
9070b3
 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag,
9070b3
     const char *skprovider)
9070b3
 {
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+	if (strlen(file) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+	    strncmp(file, PKCS11_URI_SCHEME,
9070b3
+	    strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+		return update_pkcs11_uri(agent_fd, !deleting, file, qflag);
9070b3
+	}
9070b3
+#endif
9070b3
 	if (deleting) {
9070b3
 		if (delete_file(agent_fd, file, key_only, qflag) == -1)
9070b3
 			return -1;
9070b3
@@ -813,7 +846,7 @@ main(int argc, char **argv)
9070b3
 	}
9070b3
 	if (pkcs11provider != NULL) {
9070b3
 		if (update_card(agent_fd, !deleting, pkcs11provider,
9070b3
-		    qflag) == -1)
9070b3
+		    qflag, NULL) == -1)
9070b3
 			ret = 1;
9070b3
 		goto done;
9070b3
 	}
9070b3
diff -up openssh-8.6p1/ssh-agent.c.pkcs11-uri openssh-8.6p1/ssh-agent.c
9070b3
--- openssh-8.6p1/ssh-agent.c.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-agent.c	2021-05-06 11:35:55.113653281 +0200
9070b3
@@ -847,10 +847,72 @@ no_identities(SocketEntry *e)
9070b3
 }
9070b3
 
9070b3
 #ifdef ENABLE_PKCS11
9070b3
+static char *
9070b3
+sanitize_pkcs11_provider(const char *provider)
9070b3
+{
9070b3
+	struct pkcs11_uri *uri = NULL;
9070b3
+	char *sane_uri, *module_path = NULL; /* default path */
9070b3
+	char canonical_provider[PATH_MAX];
9070b3
+
9070b3
+	if (provider == NULL)
9070b3
+		return NULL;
9070b3
+
9070b3
+	if (strlen(provider) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+	    strncmp(provider, PKCS11_URI_SCHEME,
9070b3
+	    strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+		/* PKCS#11 URI */
9070b3
+		uri = pkcs11_uri_init();
9070b3
+		if (uri == NULL) {
9070b3
+			error("Failed to init PKCS#11 URI");
9070b3
+			return NULL;
9070b3
+		}
9070b3
+
9070b3
+		if (pkcs11_uri_parse(provider, uri) != 0) {
9070b3
+			error("Failed to parse PKCS#11 URI");
9070b3
+			return NULL;
9070b3
+		}
9070b3
+		/* validate also provider from URI */
9070b3
+		if (uri->module_path)
9070b3
+			module_path = strdup(uri->module_path);
9070b3
+	} else
9070b3
+		module_path = strdup(provider); /* simple path */
9070b3
+
9070b3
+	if (module_path != NULL) { /* do not validate default NULL path in URI */
9070b3
+		if (realpath(module_path, canonical_provider) == NULL) {
9070b3
+			verbose("failed PKCS#11 provider \"%.100s\": realpath: %s",
9070b3
+			    module_path, strerror(errno));
9070b3
+			free(module_path);
9070b3
+			pkcs11_uri_cleanup(uri);
9070b3
+			return NULL;
9070b3
+		}
9070b3
+		free(module_path);
9070b3
+		if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
9070b3
+			verbose("refusing PKCS#11 provider \"%.100s\": "
9070b3
+			    "not allowed", canonical_provider);
9070b3
+			pkcs11_uri_cleanup(uri);
9070b3
+			return NULL;
9070b3
+		}
9070b3
+
9070b3
+		/* copy verified and sanitized provider path back to the uri */
9070b3
+		if (uri) {
9070b3
+			free(uri->module_path);
9070b3
+			uri->module_path = xstrdup(canonical_provider);
9070b3
+		}
9070b3
+	}
9070b3
+
9070b3
+	if (uri) {
9070b3
+		sane_uri = pkcs11_uri_get(uri);
9070b3
+		pkcs11_uri_cleanup(uri);
9070b3
+		return sane_uri;
9070b3
+	} else {
9070b3
+		return xstrdup(canonical_provider); /* simple path */
9070b3
+	}
9070b3
+}
9070b3
+
9070b3
 static void
9070b3
 process_add_smartcard_key(SocketEntry *e)
9070b3
 {
9070b3
-	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
9070b3
+	char *provider = NULL, *pin = NULL, *sane_uri = NULL;
9070b3
 	char **comments = NULL;
9070b3
 	int r, i, count = 0, success = 0, confirm = 0;
9070b3
 	u_int seconds = 0;
9070b3
@@ -869,33 +931,28 @@ process_add_smartcard_key(SocketEntry *e
9070b3
 		error_f("failed to parse constraints");
9070b3
 		goto send;
9070b3
 	}
9070b3
-	if (realpath(provider, canonical_provider) == NULL) {
9070b3
-		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
9070b3
-		    provider, strerror(errno));
9070b3
-		goto send;
9070b3
-	}
9070b3
-	if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
9070b3
-		verbose("refusing PKCS#11 add of \"%.100s\": "
9070b3
-		    "provider not allowed", canonical_provider);
9070b3
+
9070b3
+	sane_uri = sanitize_pkcs11_provider(provider);
9070b3
+	if (sane_uri == NULL)
9070b3
 		goto send;
9070b3
-	}
9070b3
-	debug_f("add %.100s", canonical_provider);
9070b3
+
9070b3
 	if (lifetime && !death)
9070b3
 		death = monotime() + lifetime;
9070b3
 
9070b3
-	count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
9070b3
+	debug_f("add %.100s", sane_uri);
9070b3
+	count = pkcs11_add_provider(sane_uri, pin, &keys, &comments);
9070b3
 	for (i = 0; i < count; i++) {
9070b3
 		k = keys[i];
9070b3
 		if (lookup_identity(k) == NULL) {
9070b3
 			id = xcalloc(1, sizeof(Identity));
9070b3
 			id->key = k;
9070b3
 			keys[i] = NULL; /* transferred */
9070b3
-			id->provider = xstrdup(canonical_provider);
9070b3
+			id->provider = xstrdup(sane_uri);
9070b3
 			if (*comments[i] != '\0') {
9070b3
 				id->comment = comments[i];
9070b3
 				comments[i] = NULL; /* transferred */
9070b3
 			} else {
9070b3
-				id->comment = xstrdup(canonical_provider);
9070b3
+				id->comment = xstrdup(sane_uri);
9070b3
 			}
9070b3
 			id->death = death;
9070b3
 			id->confirm = confirm;
9070b3
@@ -910,6 +967,7 @@ process_add_smartcard_key(SocketEntry *e
9070b3
 send:
9070b3
 	free(pin);
9070b3
 	free(provider);
9070b3
+	free(sane_uri);
9070b3
 	free(keys);
9070b3
 	free(comments);
9070b3
 	send_status(e, success);
9070b3
@@ -918,7 +976,7 @@ send:
9070b3
 static void
9070b3
 process_remove_smartcard_key(SocketEntry *e)
9070b3
 {
9070b3
-	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
9070b3
+	char *provider = NULL, *pin = NULL, *sane_uri = NULL;
9070b3
 	int r, success = 0;
9070b3
 	Identity *id, *nxt;
9070b3
 
9070b3
@@ -930,30 +988,29 @@ process_remove_smartcard_key(SocketEntry
9070b3
 	}
9070b3
 	free(pin);
9070b3
 
9070b3
-	if (realpath(provider, canonical_provider) == NULL) {
9070b3
-		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
9070b3
-		    provider, strerror(errno));
9070b3
+	sane_uri = sanitize_pkcs11_provider(provider);
9070b3
+	if (sane_uri == NULL)
9070b3
 		goto send;
9070b3
-	}
9070b3
 
9070b3
-	debug_f("remove %.100s", canonical_provider);
9070b3
+	debug_f("remove %.100s", sane_uri);
9070b3
 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
9070b3
 		nxt = TAILQ_NEXT(id, next);
9070b3
 		/* Skip file--based keys */
9070b3
 		if (id->provider == NULL)
9070b3
 			continue;
9070b3
-		if (!strcmp(canonical_provider, id->provider)) {
9070b3
+		if (!strcmp(sane_uri, id->provider)) {
9070b3
 			TAILQ_REMOVE(&idtab->idlist, id, next);
9070b3
 			free_identity(id);
9070b3
 			idtab->nentries--;
9070b3
 		}
9070b3
 	}
9070b3
-	if (pkcs11_del_provider(canonical_provider) == 0)
9070b3
+	if (pkcs11_del_provider(sane_uri) == 0)
9070b3
 		success = 1;
9070b3
 	else
9070b3
 		error_f("pkcs11_del_provider failed");
9070b3
 send:
9070b3
 	free(provider);
9070b3
+	free(sane_uri);
9070b3
 	send_status(e, success);
9070b3
 }
9070b3
 #endif /* ENABLE_PKCS11 */
9070b3
diff -up openssh-8.6p1/ssh_config.5.pkcs11-uri openssh-8.6p1/ssh_config.5
9070b3
--- openssh-8.6p1/ssh_config.5.pkcs11-uri	2021-05-06 11:35:55.061652873 +0200
9070b3
+++ openssh-8.6p1/ssh_config.5	2021-05-06 11:35:55.116653304 +0200
9070b3
@@ -1063,6 +1063,21 @@ may also be used in conjunction with
9070b3
 .Cm CertificateFile
9070b3
 in order to provide any certificate also needed for authentication with
9070b3
 the identity.
9070b3
+.Pp
9070b3
+The authentication identity can be also specified in a form of PKCS#11 URI
9070b3
+starting with a string
9070b3
+.Cm pkcs11: .
9070b3
+There is supported a subset of the PKCS#11 URI as defined
9070b3
+in RFC 7512 (implemented path arguments
9070b3
+.Cm id ,
9070b3
+.Cm manufacturer ,
9070b3
+.Cm object ,
9070b3
+.Cm token
9070b3
+and query arguments
9070b3
+.Cm module-path
9070b3
+and
9070b3
+.Cm pin-value
9070b3
+). The URI can not be in quotes.
9070b3
 .It Cm IgnoreUnknown
9070b3
 Specifies a pattern-list of unknown options to be ignored if they are
9070b3
 encountered in configuration parsing.
9070b3
diff -up openssh-8.6p1/ssh.c.pkcs11-uri openssh-8.6p1/ssh.c
9070b3
--- openssh-8.6p1/ssh.c.pkcs11-uri	2021-05-06 11:35:55.060652865 +0200
9070b3
+++ openssh-8.6p1/ssh.c	2021-05-06 12:00:07.129988275 +0200
9070b3
@@ -843,6 +843,14 @@ main(int ac, char **av)
9070b3
 			options.gss_deleg_creds = 1;
9070b3
 			break;
9070b3
 		case 'i':
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+			if (strlen(optarg) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+			    strncmp(optarg, PKCS11_URI_SCHEME,
9070b3
+			    strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+				add_identity_file(&options, NULL, optarg, 1);
9070b3
+				break;
9070b3
+			}
9070b3
+#endif
9070b3
 			p = tilde_expand_filename(optarg, getuid());
9070b3
 			if (stat(p, &st) == -1)
9070b3
 				fprintf(stderr, "Warning: Identity file %s "
9070b3
@@ -1695,6 +1703,7 @@ main(int ac, char **av)
9070b3
 #ifdef ENABLE_PKCS11
9070b3
 	(void)pkcs11_del_provider(options.pkcs11_provider);
9070b3
 #endif
9070b3
+	pkcs11_terminate();
9070b3
 
9070b3
  skip_connect:
9070b3
 	exit_status = ssh_session2(ssh, cinfo);
9070b3
@@ -2211,6 +2220,45 @@ ssh_session2(struct ssh *ssh, const stru
9070b3
 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
9070b3
 }
9070b3
 
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+static void
9070b3
+load_pkcs11_identity(char *pkcs11_uri, char *identity_files[],
9070b3
+    struct sshkey *identity_keys[], int *n_ids)
9070b3
+{
9070b3
+	int nkeys, i;
9070b3
+	struct sshkey **keys;
9070b3
+	struct pkcs11_uri *uri;
9070b3
+
9070b3
+	debug("identity file '%s' from pkcs#11", pkcs11_uri);
9070b3
+	uri = pkcs11_uri_init();
9070b3
+	if (uri == NULL)
9070b3
+		fatal("Failed to init PKCS#11 URI");
9070b3
+
9070b3
+	if (pkcs11_uri_parse(pkcs11_uri, uri) != 0)
9070b3
+	fatal("Failed to parse PKCS#11 URI %s", pkcs11_uri);
9070b3
+
9070b3
+	/* we need to merge URI and provider together */
9070b3
+	if (options.pkcs11_provider != NULL && uri->module_path == NULL)
9070b3
+		uri->module_path = strdup(options.pkcs11_provider);
9070b3
+
9070b3
+	if (options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
9070b3
+	    (nkeys = pkcs11_add_provider_by_uri(uri, NULL, &keys, NULL)) > 0) {
9070b3
+		for (i = 0; i < nkeys; i++) {
9070b3
+			if (*n_ids >= SSH_MAX_IDENTITY_FILES) {
9070b3
+				sshkey_free(keys[i]);
9070b3
+				continue;
9070b3
+			}
9070b3
+			identity_keys[*n_ids] = keys[i];
9070b3
+			identity_files[*n_ids] = pkcs11_uri_get(uri);
9070b3
+			(*n_ids)++;
9070b3
+		}
9070b3
+		free(keys);
9070b3
+	}
9070b3
+
9070b3
+	pkcs11_uri_cleanup(uri);
9070b3
+}
9070b3
+#endif /* ENABLE_PKCS11 */
9070b3
+
9070b3
 /* Loads all IdentityFile and CertificateFile keys */
9070b3
 static void
9070b3
 load_public_identity_files(const struct ssh_conn_info *cinfo)
9070b3
@@ -2225,11 +2273,6 @@ load_public_identity_files(const struct
9070b3
 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
9070b3
 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
9070b3
 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
9070b3
-#ifdef ENABLE_PKCS11
9070b3
-	struct sshkey **keys = NULL;
9070b3
-	char **comments = NULL;
9070b3
-	int nkeys;
9070b3
-#endif /* PKCS11 */
9070b3
 
9070b3
 	n_ids = n_certs = 0;
9070b3
 	memset(identity_files, 0, sizeof(identity_files));
9070b3
@@ -2242,33 +2285,46 @@ load_public_identity_files(const struct
9070b3
 	    sizeof(certificate_file_userprovided));
9070b3
 
9070b3
 #ifdef ENABLE_PKCS11
9070b3
-	if (options.pkcs11_provider != NULL &&
9070b3
-	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
9070b3
-	    (pkcs11_init(!options.batch_mode) == 0) &&
9070b3
-	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
9070b3
-	    &keys, &comments)) > 0) {
9070b3
-		for (i = 0; i < nkeys; i++) {
9070b3
-			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
9070b3
-				sshkey_free(keys[i]);
9070b3
-				free(comments[i]);
9070b3
-				continue;
9070b3
-			}
9070b3
-			identity_keys[n_ids] = keys[i];
9070b3
-			identity_files[n_ids] = comments[i]; /* transferred */
9070b3
-			n_ids++;
9070b3
-		}
9070b3
-		free(keys);
9070b3
-		free(comments);
9070b3
+	/* handle fallback from PKCS11Provider option */
9070b3
+	pkcs11_init(!options.batch_mode);
9070b3
+
9070b3
+	if (options.pkcs11_provider != NULL) {
9070b3
+		struct pkcs11_uri *uri;
9070b3
+
9070b3
+		uri = pkcs11_uri_init();
9070b3
+		if (uri == NULL)
9070b3
+			fatal("Failed to init PKCS#11 URI");
9070b3
+
9070b3
+		/* Construct simple PKCS#11 URI to simplify access */
9070b3
+		uri->module_path = strdup(options.pkcs11_provider);
9070b3
+
9070b3
+		/* Add it as any other IdentityFile */
9070b3
+		cp = pkcs11_uri_get(uri);
9070b3
+		add_identity_file(&options, NULL, cp, 1);
9070b3
+		free(cp);
9070b3
+
9070b3
+		pkcs11_uri_cleanup(uri);
9070b3
 	}
9070b3
 #endif /* ENABLE_PKCS11 */
9070b3
 	for (i = 0; i < options.num_identity_files; i++) {
9070b3
+		char *name = options.identity_files[i];
9070b3
 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
9070b3
-		    strcasecmp(options.identity_files[i], "none") == 0) {
9070b3
+		    strcasecmp(name, "none") == 0) {
9070b3
 			free(options.identity_files[i]);
9070b3
 			options.identity_files[i] = NULL;
9070b3
 			continue;
9070b3
 		}
9070b3
-		cp = tilde_expand_filename(options.identity_files[i], getuid());
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+		if (strlen(name) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+		    strncmp(name, PKCS11_URI_SCHEME,
9070b3
+		    strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+			load_pkcs11_identity(name, identity_files,
9070b3
+			    identity_keys, &n_ids);
9070b3
+			free(options.identity_files[i]);
9070b3
+			continue;
9070b3
+		}
9070b3
+#endif /* ENABLE_PKCS11 */
9070b3
+		cp = tilde_expand_filename(name, getuid());
9070b3
 		filename = default_client_percent_dollar_expand(cp, cinfo);
9070b3
 		free(cp);
9070b3
 		check_load(sshkey_load_public(filename, &public, NULL),
9070b3
diff -up openssh-8.6p1/ssh-keygen.c.pkcs11-uri openssh-8.6p1/ssh-keygen.c
9070b3
--- openssh-8.6p1/ssh-keygen.c.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-keygen.c	2021-05-06 11:35:55.114653289 +0200
9070b3
@@ -860,8 +860,11 @@ do_download(struct passwd *pw)
9070b3
 			free(fp);
9070b3
 		} else {
9070b3
 			(void) sshkey_write(keys[i], stdout); /* XXX check */
9070b3
-			fprintf(stdout, "%s%s\n",
9070b3
-			    *(comments[i]) == '\0' ? "" : " ", comments[i]);
9070b3
+			if (*(comments[i]) != '\0') {
9070b3
+				fprintf(stdout, " %s", comments[i]);
9070b3
+			}
9070b3
+			(void) pkcs11_uri_write(keys[i], stdout);
9070b3
+			fprintf(stdout, "\n");
9070b3
 		}
9070b3
 		free(comments[i]);
9070b3
 		sshkey_free(keys[i]);
9070b3
diff -up openssh-8.6p1/ssh-pkcs11-client.c.pkcs11-uri openssh-8.6p1/ssh-pkcs11-client.c
9070b3
--- openssh-8.6p1/ssh-pkcs11-client.c.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-pkcs11-client.c	2021-05-06 11:35:55.114653289 +0200
9070b3
@@ -323,6 +323,8 @@ pkcs11_add_provider(char *name, char *pi
9070b3
 	u_int nkeys, i;
9070b3
 	struct sshbuf *msg;
9070b3
 
9070b3
+	debug_f("called, name = %s", name);
9070b3
+
9070b3
 	if (fd < 0 && pkcs11_start_helper() < 0)
9070b3
 		return (-1);
9070b3
 
9070b3
@@ -342,6 +344,7 @@ pkcs11_add_provider(char *name, char *pi
9070b3
 		*keysp = xcalloc(nkeys, sizeof(struct sshkey *));
9070b3
 		if (labelsp)
9070b3
 			*labelsp = xcalloc(nkeys, sizeof(char *));
9070b3
+		debug_f("nkeys = %u", nkeys);
9070b3
 		for (i = 0; i < nkeys; i++) {
9070b3
 			/* XXX clean up properly instead of fatal() */
9070b3
 			if ((r = sshbuf_get_string(msg, &blob, &blen)) != 0 ||
9070b3
diff -up openssh-8.6p1/ssh-pkcs11.c.pkcs11-uri openssh-8.6p1/ssh-pkcs11.c
9070b3
--- openssh-8.6p1/ssh-pkcs11.c.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-pkcs11.c	2021-05-06 11:35:55.115653297 +0200
9070b3
@@ -55,8 +55,8 @@ struct pkcs11_slotinfo {
9070b3
 	int			logged_in;
9070b3
 };
9070b3
 
9070b3
-struct pkcs11_provider {
9070b3
-	char			*name;
9070b3
+struct pkcs11_module {
9070b3
+	char			*module_path;
9070b3
 	void			*handle;
9070b3
 	CK_FUNCTION_LIST	*function_list;
9070b3
 	CK_INFO			info;
9070b3
@@ -65,6 +65,13 @@ struct pkcs11_provider {
9070b3
 	struct pkcs11_slotinfo	*slotinfo;
9070b3
 	int			valid;
9070b3
 	int			refcount;
9070b3
+};
9070b3
+
9070b3
+struct pkcs11_provider {
9070b3
+	char			*name;
9070b3
+	struct pkcs11_module	*module; /* can be shared between various providers */
9070b3
+	int			refcount;
9070b3
+	int			valid;
9070b3
 	TAILQ_ENTRY(pkcs11_provider) next;
9070b3
 };
9070b3
 
9070b3
@@ -75,6 +82,7 @@ struct pkcs11_key {
9070b3
 	CK_ULONG		slotidx;
9070b3
 	char			*keyid;
9070b3
 	int			keyid_len;
9070b3
+	char			*label;
9070b3
 };
9070b3
 
9070b3
 int pkcs11_interactive = 0;
9070b3
@@ -106,26 +114,61 @@ pkcs11_init(int interactive)
9070b3
  * this is called when a provider gets unregistered.
9070b3
  */
9070b3
 static void
9070b3
-pkcs11_provider_finalize(struct pkcs11_provider *p)
9070b3
+pkcs11_module_finalize(struct pkcs11_module *m)
9070b3
 {
9070b3
 	CK_RV rv;
9070b3
 	CK_ULONG i;
9070b3
 
9070b3
-	debug_f("provider \"%s\" refcount %d valid %d",
9070b3
-	    p->name, p->refcount, p->valid);
9070b3
-	if (!p->valid)
9070b3
+	debug_f("%p refcount %d valid %d", m, m->refcount, m->valid);
9070b3
+	if (!m->valid)
9070b3
 		return;
9070b3
-	for (i = 0; i < p->nslots; i++) {
9070b3
-		if (p->slotinfo[i].session &&
9070b3
-		    (rv = p->function_list->C_CloseSession(
9070b3
-		    p->slotinfo[i].session)) != CKR_OK)
9070b3
+	for (i = 0; i < m->nslots; i++) {
9070b3
+		if (m->slotinfo[i].session &&
9070b3
+		    (rv = m->function_list->C_CloseSession(
9070b3
+		    m->slotinfo[i].session)) != CKR_OK)
9070b3
 			error("C_CloseSession failed: %lu", rv);
9070b3
 	}
9070b3
-	if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
9070b3
+	if ((rv = m->function_list->C_Finalize(NULL)) != CKR_OK)
9070b3
 		error("C_Finalize failed: %lu", rv);
9070b3
+	m->valid = 0;
9070b3
+	m->function_list = NULL;
9070b3
+	dlclose(m->handle);
9070b3
+}
9070b3
+
9070b3
+/*
9070b3
+ * remove a reference to the pkcs11 module.
9070b3
+ * called when a provider is unregistered.
9070b3
+ */
9070b3
+static void
9070b3
+pkcs11_module_unref(struct pkcs11_module *m)
9070b3
+{
9070b3
+	debug_f("%p refcount %d", m, m->refcount);
9070b3
+	if (--m->refcount <= 0) {
9070b3
+		pkcs11_module_finalize(m);
9070b3
+		if (m->valid)
9070b3
+			error_f("%p still valid", m);
9070b3
+		free(m->slotlist);
9070b3
+		free(m->slotinfo);
9070b3
+		free(m->module_path);
9070b3
+		free(m);
9070b3
+	}
9070b3
+}
9070b3
+
9070b3
+/*
9070b3
+ * finalize a provider shared library, it's no longer usable.
9070b3
+ * however, there might still be keys referencing this provider,
9070b3
+ * so the actual freeing of memory is handled by pkcs11_provider_unref().
9070b3
+ * this is called when a provider gets unregistered.
9070b3
+ */
9070b3
+static void
9070b3
+pkcs11_provider_finalize(struct pkcs11_provider *p)
9070b3
+{
9070b3
+	debug_f("%p refcount %d valid %d", p, p->refcount, p->valid);
9070b3
+	if (!p->valid)
9070b3
+		return;
9070b3
+	pkcs11_module_unref(p->module);
9070b3
+	p->module = NULL;
9070b3
 	p->valid = 0;
9070b3
-	p->function_list = NULL;
9070b3
-	dlclose(p->handle);
9070b3
 }
9070b3
 
9070b3
 /*
9070b3
@@ -137,11 +180,9 @@ pkcs11_provider_unref(struct pkcs11_prov
9070b3
 {
9070b3
 	debug_f("provider \"%s\" refcount %d", p->name, p->refcount);
9070b3
 	if (--p->refcount <= 0) {
9070b3
-		if (p->valid)
9070b3
-			error_f("provider \"%s\" still valid", p->name);
9070b3
 		free(p->name);
9070b3
-		free(p->slotlist);
9070b3
-		free(p->slotinfo);
9070b3
+		if (p->module)
9070b3
+			pkcs11_module_unref(p->module);
9070b3
 		free(p);
9070b3
 	}
9070b3
 }
9070b3
@@ -159,6 +200,20 @@ pkcs11_terminate(void)
9070b3
 	}
9070b3
 }
9070b3
 
9070b3
+/* lookup provider by module path */
9070b3
+static struct pkcs11_module *
9070b3
+pkcs11_provider_lookup_module(char *module_path)
9070b3
+{
9070b3
+	struct pkcs11_provider *p;
9070b3
+
9070b3
+	TAILQ_FOREACH(p, &pkcs11_providers, next) {
9070b3
+		debug("check %p %s (%s)", p, p->name, p->module->module_path);
9070b3
+		if (!strcmp(module_path, p->module->module_path))
9070b3
+			return (p->module);
9070b3
+	}
9070b3
+	return (NULL);
9070b3
+}
9070b3
+
9070b3
 /* lookup provider by name */
9070b3
 static struct pkcs11_provider *
9070b3
 pkcs11_provider_lookup(char *provider_id)
9070b3
@@ -173,19 +228,55 @@ pkcs11_provider_lookup(char *provider_id
9070b3
 	return (NULL);
9070b3
 }
9070b3
 
9070b3
+int pkcs11_del_provider_by_uri(struct pkcs11_uri *);
9070b3
+
9070b3
 /* unregister provider by name */
9070b3
 int
9070b3
 pkcs11_del_provider(char *provider_id)
9070b3
 {
9070b3
+	int rv;
9070b3
+	struct pkcs11_uri *uri;
9070b3
+
9070b3
+	debug_f("called, provider_id = %s", provider_id);
9070b3
+
9070b3
+      if (provider_id == NULL)
9070b3
+          return 0;
9070b3
+
9070b3
+	uri = pkcs11_uri_init();
9070b3
+	if (uri == NULL)
9070b3
+		fatal("Failed to init PKCS#11 URI");
9070b3
+
9070b3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
9070b3
+			fatal("Failed to parse PKCS#11 URI");
9070b3
+	} else {
9070b3
+		uri->module_path = strdup(provider_id);
9070b3
+	}
9070b3
+
9070b3
+	rv = pkcs11_del_provider_by_uri(uri);
9070b3
+	pkcs11_uri_cleanup(uri);
9070b3
+	return rv;
9070b3
+}
9070b3
+
9070b3
+/* unregister provider by PKCS#11 URI */
9070b3
+int
9070b3
+pkcs11_del_provider_by_uri(struct pkcs11_uri *uri)
9070b3
+{
9070b3
 	struct pkcs11_provider *p;
9070b3
+	int rv = -1;
9070b3
+	char *provider_uri = pkcs11_uri_get(uri);
9070b3
 
9070b3
-	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
9070b3
+	debug3_f("called with provider %s", provider_uri);
9070b3
+
9070b3
+	if ((p = pkcs11_provider_lookup(provider_uri)) != NULL) {
9070b3
 		TAILQ_REMOVE(&pkcs11_providers, p, next);
9070b3
 		pkcs11_provider_finalize(p);
9070b3
 		pkcs11_provider_unref(p);
9070b3
-		return (0);
9070b3
+		rv = 0;
9070b3
 	}
9070b3
-	return (-1);
9070b3
+	free(provider_uri);
9070b3
+	return rv;
9070b3
 }
9070b3
 
9070b3
 static RSA_METHOD *rsa_method;
9070b3
@@ -195,6 +283,55 @@ static EC_KEY_METHOD *ec_key_method;
9070b3
 static int ec_key_idx = 0;
9070b3
 #endif
9070b3
 
9070b3
+/*
9070b3
+ * This can't be in the ssh-pkcs11-uri, becase we can not depend on
9070b3
+ * PKCS#11 structures in ssh-agent (using client-helper communication)
9070b3
+ */
9070b3
+int
9070b3
+pkcs11_uri_write(const struct sshkey *key, FILE *f)
9070b3
+{
9070b3
+	char *p = NULL;
9070b3
+	struct pkcs11_uri uri;
9070b3
+	struct pkcs11_key *k11;
9070b3
+
9070b3
+	/* sanity - is it a RSA key with associated app_data? */
9070b3
+	switch (key->type) {
9070b3
+	case KEY_RSA:
9070b3
+		k11 = RSA_get_ex_data(key->rsa, rsa_idx);
9070b3
+		break;
9070b3
+#ifdef HAVE_EC_KEY_METHOD_NEW
9070b3
+	case KEY_ECDSA:
9070b3
+		k11 = EC_KEY_get_ex_data(key->ecdsa, ec_key_idx);
9070b3
+		break;
9070b3
+#endif
9070b3
+	default:
9070b3
+		error("Unknown key type %d", key->type);
9070b3
+		return -1;
9070b3
+	}
9070b3
+	if (k11 == NULL) {
9070b3
+		error("Failed to get ex_data for key type %d", key->type);
9070b3
+		return (-1);
9070b3
+	}
9070b3
+
9070b3
+	/* omit type -- we are looking for private-public or private-certificate pairs */
9070b3
+	uri.id = k11->keyid;
9070b3
+	uri.id_len = k11->keyid_len;
9070b3
+	uri.token = k11->provider->module->slotinfo[k11->slotidx].token.label;
9070b3
+	uri.object = k11->label;
9070b3
+	uri.module_path = k11->provider->module->module_path;
9070b3
+	uri.lib_manuf = k11->provider->module->info.manufacturerID;
9070b3
+	uri.manuf = k11->provider->module->slotinfo[k11->slotidx].token.manufacturerID;
9070b3
+
9070b3
+	p = pkcs11_uri_get(&uri);
9070b3
+	/* do not cleanup -- we do not allocate here, only reference */
9070b3
+	if (p == NULL)
9070b3
+		return -1;
9070b3
+
9070b3
+	fprintf(f, " %s", p);
9070b3
+	free(p);
9070b3
+	return 0;
9070b3
+}
9070b3
+
9070b3
 /* release a wrapped object */
9070b3
 static void
9070b3
 pkcs11_k11_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
9070b3
@@ -208,6 +345,7 @@ pkcs11_k11_free(void *parent, void *ptr,
9070b3
 	if (k11->provider)
9070b3
 		pkcs11_provider_unref(k11->provider);
9070b3
 	free(k11->keyid);
9070b3
+	free(k11->label);
9070b3
 	free(k11);
9070b3
 }
9070b3
 
9070b3
@@ -222,8 +360,8 @@ pkcs11_find(struct pkcs11_provider *p, C
9070b3
 	CK_RV			rv;
9070b3
 	int			ret = -1;
9070b3
 
9070b3
-	f = p->function_list;
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
 	if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
9070b3
 		error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
9070b3
 		return (-1);
9070b3
@@ -262,12 +400,12 @@ pkcs11_login_slot(struct pkcs11_provider
9070b3
 	else {
9070b3
 		snprintf(prompt, sizeof(prompt), "Enter PIN for '%s': ",
9070b3
 		    si->token.label);
9070b3
-		if ((pin = read_passphrase(prompt, RP_ALLOW_EOF)) == NULL) {
9070b3
+		if ((pin = read_passphrase(prompt, RP_ALLOW_EOF|RP_ALLOW_STDIN)) == NULL) {
9070b3
 			debug_f("no pin specified");
9070b3
 			return (-1);	/* bail out */
9070b3
 		}
9070b3
 	}
9070b3
-	rv = provider->function_list->C_Login(si->session, type, (u_char *)pin,
9070b3
+	rv = provider->module->function_list->C_Login(si->session, type, (u_char *)pin,
9070b3
 	    (pin != NULL) ? strlen(pin) : 0);
9070b3
 	if (pin != NULL)
9070b3
 		freezero(pin, strlen(pin));
9070b3
@@ -297,13 +435,14 @@ pkcs11_login_slot(struct pkcs11_provider
9070b3
 static int
9070b3
 pkcs11_login(struct pkcs11_key *k11, CK_USER_TYPE type)
9070b3
 {
9070b3
-	if (k11 == NULL || k11->provider == NULL || !k11->provider->valid) {
9070b3
+	if (k11 == NULL || k11->provider == NULL || !k11->provider->valid ||
9070b3
+	    k11->provider->module == NULL || !k11->provider->module->valid) {
9070b3
 		error("no pkcs11 (valid) provider found");
9070b3
 		return (-1);
9070b3
 	}
9070b3
 
9070b3
 	return pkcs11_login_slot(k11->provider,
9070b3
-	    &k11->provider->slotinfo[k11->slotidx], type);
9070b3
+	    &k11->provider->module->slotinfo[k11->slotidx], type);
9070b3
 }
9070b3
 
9070b3
 
9070b3
@@ -319,13 +458,14 @@ pkcs11_check_obj_bool_attrib(struct pkcs
9070b3
 
9070b3
 	*val = 0;
9070b3
 
9070b3
-	if (!k11->provider || !k11->provider->valid) {
9070b3
+	if (!k11->provider || !k11->provider->valid ||
9070b3
+	    !k11->provider->module || !k11->provider->module->valid) {
9070b3
 		error("no pkcs11 (valid) provider found");
9070b3
 		return (-1);
9070b3
 	}
9070b3
 
9070b3
-	f = k11->provider->function_list;
9070b3
-	si = &k11->provider->slotinfo[k11->slotidx];
9070b3
+	f = k11->provider->module->function_list;
9070b3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
9070b3
 
9070b3
 	attr.type = type;
9070b3
 	attr.pValue = &flag;
9070b3
@@ -356,13 +496,14 @@ pkcs11_get_key(struct pkcs11_key *k11, C
9070b3
 	int			 always_auth = 0;
9070b3
 	int			 did_login = 0;
9070b3
 
9070b3
-	if (!k11->provider || !k11->provider->valid) {
9070b3
+	if (!k11->provider || !k11->provider->valid ||
9070b3
+	    !k11->provider->module || !k11->provider->module->valid) {
9070b3
 		error("no pkcs11 (valid) provider found");
9070b3
 		return (-1);
9070b3
 	}
9070b3
 
9070b3
-	f = k11->provider->function_list;
9070b3
-	si = &k11->provider->slotinfo[k11->slotidx];
9070b3
+	f = k11->provider->module->function_list;
9070b3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
9070b3
 
9070b3
 	if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
9070b3
 		if (pkcs11_login(k11, CKU_USER) < 0) {
9070b3
@@ -439,8 +580,8 @@ pkcs11_rsa_private_encrypt(int flen, con
9070b3
 		return (-1);
9070b3
 	}
9070b3
 
9070b3
-	f = k11->provider->function_list;
9070b3
-	si = &k11->provider->slotinfo[k11->slotidx];
9070b3
+	f = k11->provider->module->function_list;
9070b3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
9070b3
 	tlen = RSA_size(rsa);
9070b3
 
9070b3
 	/* XXX handle CKR_BUFFER_TOO_SMALL */
9070b3
@@ -484,7 +625,7 @@ pkcs11_rsa_start_wrapper(void)
9070b3
 /* redirect private key operations for rsa key to pkcs11 token */
9070b3
 static int
9070b3
 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
9070b3
-    CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
9070b3
+    CK_ATTRIBUTE *keyid_attrib, CK_ATTRIBUTE *label_attrib, RSA *rsa)
9070b3
 {
9070b3
 	struct pkcs11_key	*k11;
9070b3
 
9070b3
@@ -502,6 +643,12 @@ pkcs11_rsa_wrap(struct pkcs11_provider *
9070b3
 		memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
9070b3
 	}
9070b3
 
9070b3
+	if (label_attrib->ulValueLen > 0 ) {
9070b3
+		k11->label = xmalloc(label_attrib->ulValueLen+1);
9070b3
+		memcpy(k11->label, label_attrib->pValue, label_attrib->ulValueLen);
9070b3
+		k11->label[label_attrib->ulValueLen] = 0;
9070b3
+	}
9070b3
+
9070b3
 	RSA_set_method(rsa, rsa_method);
9070b3
 	RSA_set_ex_data(rsa, rsa_idx, k11);
9070b3
 	return (0);
9070b3
@@ -532,8 +679,8 @@ ecdsa_do_sign(const unsigned char *dgst,
9070b3
 		return (NULL);
9070b3
 	}
9070b3
 
9070b3
-	f = k11->provider->function_list;
9070b3
-	si = &k11->provider->slotinfo[k11->slotidx];
9070b3
+	f = k11->provider->module->function_list;
9070b3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
9070b3
 
9070b3
 	siglen = ECDSA_size(ec);
9070b3
 	sig = xmalloc(siglen);
9070b3
@@ -598,7 +745,7 @@ pkcs11_ecdsa_start_wrapper(void)
9070b3
 
9070b3
 static int
9070b3
 pkcs11_ecdsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
9070b3
-    CK_ATTRIBUTE *keyid_attrib, EC_KEY *ec)
9070b3
+    CK_ATTRIBUTE *keyid_attrib, CK_ATTRIBUTE *label_attrib, EC_KEY *ec)
9070b3
 {
9070b3
 	struct pkcs11_key	*k11;
9070b3
 
9070b3
@@ -614,6 +761,12 @@ pkcs11_ecdsa_wrap(struct pkcs11_provider
9070b3
 	k11->keyid = xmalloc(k11->keyid_len);
9070b3
 	memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
9070b3
 
9070b3
+	if (label_attrib->ulValueLen > 0 ) {
9070b3
+		k11->label = xmalloc(label_attrib->ulValueLen+1);
9070b3
+		memcpy(k11->label, label_attrib->pValue, label_attrib->ulValueLen);
9070b3
+		k11->label[label_attrib->ulValueLen] = 0;
9070b3
+	}
9070b3
+
9070b3
 	EC_KEY_set_method(ec, ec_key_method);
9070b3
 	EC_KEY_set_ex_data(ec, ec_key_idx, k11);
9070b3
 
9070b3
@@ -650,8 +803,8 @@ pkcs11_open_session(struct pkcs11_provid
9070b3
 	CK_SESSION_HANDLE	session;
9070b3
 	int			login_required, ret;
9070b3
 
9070b3
-	f = p->function_list;
9070b3
-	si = &p->slotinfo[slotidx];
9070b3
+	f = p->module->function_list;
9070b3
+	si = &p->module->slotinfo[slotidx];
9070b3
 
9070b3
 	login_required = si->token.flags & CKF_LOGIN_REQUIRED;
9070b3
 
9070b3
@@ -661,9 +814,9 @@ pkcs11_open_session(struct pkcs11_provid
9070b3
 		error("pin required");
9070b3
 		return (-SSH_PKCS11_ERR_PIN_REQUIRED);
9070b3
 	}
9070b3
-	if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
9070b3
+	if ((rv = f->C_OpenSession(p->module->slotlist[slotidx], CKF_RW_SESSION|
9070b3
 	    CKF_SERIAL_SESSION, NULL, NULL, &session)) != CKR_OK) {
9070b3
-		error("C_OpenSession failed: %lu", rv);
9070b3
+		error("C_OpenSession failed for slot %lu: %lu", slotidx, rv);
9070b3
 		return (-1);
9070b3
 	}
9070b3
 	if (login_required && pin != NULL && strlen(pin) != 0) {
9070b3
@@ -699,7 +852,8 @@ static struct sshkey *
9070b3
 pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
9070b3
     CK_OBJECT_HANDLE *obj)
9070b3
 {
9070b3
-	CK_ATTRIBUTE		 key_attr[3];
9070b3
+	CK_ATTRIBUTE		 key_attr[4];
9070b3
+	int			 nattr = 4;
9070b3
 	CK_SESSION_HANDLE	 session;
9070b3
 	CK_FUNCTION_LIST	*f = NULL;
9070b3
 	CK_RV			 rv;
9070b3
@@ -713,14 +867,15 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 
9070b3
 	memset(&key_attr, 0, sizeof(key_attr));
9070b3
 	key_attr[0].type = CKA_ID;
9070b3
-	key_attr[1].type = CKA_EC_POINT;
9070b3
-	key_attr[2].type = CKA_EC_PARAMS;
9070b3
+	key_attr[1].type = CKA_LABEL;
9070b3
+	key_attr[2].type = CKA_EC_POINT;
9070b3
+	key_attr[3].type = CKA_EC_PARAMS;
9070b3
 
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
-	f = p->function_list;
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
 
9070b3
 	/* figure out size of the attributes */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		return (NULL);
9070b3
@@ -731,19 +886,19 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 	 * ensure that none of the others are zero length.
9070b3
 	 * XXX assumes CKA_ID is always first.
9070b3
 	 */
9070b3
-	if (key_attr[1].ulValueLen == 0 ||
9070b3
-	    key_attr[2].ulValueLen == 0) {
9070b3
+	if (key_attr[2].ulValueLen == 0 ||
9070b3
+	    key_attr[3].ulValueLen == 0) {
9070b3
 		error("invalid attribute length");
9070b3
 		return (NULL);
9070b3
 	}
9070b3
 
9070b3
 	/* allocate buffers for attributes */
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		if (key_attr[i].ulValueLen > 0)
9070b3
 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
9070b3
 
9070b3
 	/* retrieve ID, public point and curve parameters of EC key */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		goto fail;
9070b3
@@ -755,8 +910,8 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 		goto fail;
9070b3
 	}
9070b3
 
9070b3
-	attrp = key_attr[2].pValue;
9070b3
-	group = d2i_ECPKParameters(NULL, &attrp, key_attr[2].ulValueLen);
9070b3
+	attrp = key_attr[3].pValue;
9070b3
+	group = d2i_ECPKParameters(NULL, &attrp, key_attr[3].ulValueLen);
9070b3
 	if (group == NULL) {
9070b3
 		ossl_error("d2i_ECPKParameters failed");
9070b3
 		goto fail;
9070b3
@@ -767,13 +922,13 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 		goto fail;
9070b3
 	}
9070b3
 
9070b3
-	if (key_attr[1].ulValueLen <= 2) {
9070b3
+	if (key_attr[2].ulValueLen <= 2) {
9070b3
 		error("CKA_EC_POINT too small");
9070b3
 		goto fail;
9070b3
 	}
9070b3
 
9070b3
-	attrp = key_attr[1].pValue;
9070b3
-	octet = d2i_ASN1_OCTET_STRING(NULL, &attrp, key_attr[1].ulValueLen);
9070b3
+	attrp = key_attr[2].pValue;
9070b3
+	octet = d2i_ASN1_OCTET_STRING(NULL, &attrp, key_attr[2].ulValueLen);
9070b3
 	if (octet == NULL) {
9070b3
 		ossl_error("d2i_ASN1_OCTET_STRING failed");
9070b3
 		goto fail;
9070b3
@@ -790,7 +945,7 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 		goto fail;
9070b3
 	}
9070b3
 
9070b3
-	if (pkcs11_ecdsa_wrap(p, slotidx, &key_attr[0], ec))
9070b3
+	if (pkcs11_ecdsa_wrap(p, slotidx, &key_attr[0], &key_attr[1], ec))
9070b3
 		goto fail;
9070b3
 
9070b3
 	key = sshkey_new(KEY_UNSPEC);
9070b3
@@ -806,7 +961,7 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_
9070b3
 	ec = NULL;	/* now owned by key */
9070b3
 
9070b3
 fail:
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		free(key_attr[i].pValue);
9070b3
 	if (ec)
9070b3
 		EC_KEY_free(ec);
9070b3
@@ -823,7 +978,8 @@ static struct sshkey *
9070b3
 pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
9070b3
     CK_OBJECT_HANDLE *obj)
9070b3
 {
9070b3
-	CK_ATTRIBUTE		 key_attr[3];
9070b3
+	CK_ATTRIBUTE		 key_attr[4];
9070b3
+	int			 nattr = 4;
9070b3
 	CK_SESSION_HANDLE	 session;
9070b3
 	CK_FUNCTION_LIST	*f = NULL;
9070b3
 	CK_RV			 rv;
9070b3
@@ -834,14 +990,15 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_pr
9070b3
 
9070b3
 	memset(&key_attr, 0, sizeof(key_attr));
9070b3
 	key_attr[0].type = CKA_ID;
9070b3
-	key_attr[1].type = CKA_MODULUS;
9070b3
-	key_attr[2].type = CKA_PUBLIC_EXPONENT;
9070b3
+	key_attr[1].type = CKA_LABEL;
9070b3
+	key_attr[2].type = CKA_MODULUS;
9070b3
+	key_attr[3].type = CKA_PUBLIC_EXPONENT;
9070b3
 
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
-	f = p->function_list;
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
 
9070b3
 	/* figure out size of the attributes */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		return (NULL);
9070b3
@@ -852,19 +1009,19 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_pr
9070b3
 	 * ensure that none of the others are zero length.
9070b3
 	 * XXX assumes CKA_ID is always first.
9070b3
 	 */
9070b3
-	if (key_attr[1].ulValueLen == 0 ||
9070b3
-	    key_attr[2].ulValueLen == 0) {
9070b3
+	if (key_attr[2].ulValueLen == 0 ||
9070b3
+	    key_attr[3].ulValueLen == 0) {
9070b3
 		error("invalid attribute length");
9070b3
 		return (NULL);
9070b3
 	}
9070b3
 
9070b3
 	/* allocate buffers for attributes */
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		if (key_attr[i].ulValueLen > 0)
9070b3
 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
9070b3
 
9070b3
 	/* retrieve ID, modulus and public exponent of RSA key */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		goto fail;
9070b3
@@ -876,8 +1033,8 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_pr
9070b3
 		goto fail;
9070b3
 	}
9070b3
 
9070b3
-	rsa_n = BN_bin2bn(key_attr[1].pValue, key_attr[1].ulValueLen, NULL);
9070b3
-	rsa_e = BN_bin2bn(key_attr[2].pValue, key_attr[2].ulValueLen, NULL);
9070b3
+	rsa_n = BN_bin2bn(key_attr[2].pValue, key_attr[2].ulValueLen, NULL);
9070b3
+	rsa_e = BN_bin2bn(key_attr[3].pValue, key_attr[3].ulValueLen, NULL);
9070b3
 	if (rsa_n == NULL || rsa_e == NULL) {
9070b3
 		error("BN_bin2bn failed");
9070b3
 		goto fail;
9070b3
@@ -886,7 +1043,7 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_pr
9070b3
 		fatal_f("set key");
9070b3
 	rsa_n = rsa_e = NULL; /* transferred */
9070b3
 
9070b3
-	if (pkcs11_rsa_wrap(p, slotidx, &key_attr[0], rsa))
9070b3
+	if (pkcs11_rsa_wrap(p, slotidx, &key_attr[0], &key_attr[1], rsa))
9070b3
 		goto fail;
9070b3
 
9070b3
 	key = sshkey_new(KEY_UNSPEC);
9070b3
@@ -901,7 +1058,7 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_pr
9070b3
 	rsa = NULL;	/* now owned by key */
9070b3
 
9070b3
 fail:
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		free(key_attr[i].pValue);
9070b3
 	RSA_free(rsa);
9070b3
 
9070b3
@@ -912,7 +1069,8 @@ static int
9070b3
 pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
9070b3
     CK_OBJECT_HANDLE *obj, struct sshkey **keyp, char **labelp)
9070b3
 {
9070b3
-	CK_ATTRIBUTE		 cert_attr[3];
9070b3
+	CK_ATTRIBUTE		 cert_attr[4];
9070b3
+	int			 nattr = 4;
9070b3
 	CK_SESSION_HANDLE	 session;
9070b3
 	CK_FUNCTION_LIST	*f = NULL;
9070b3
 	CK_RV			 rv;
9070b3
@@ -936,14 +1094,15 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 
9070b3
 	memset(&cert_attr, 0, sizeof(cert_attr));
9070b3
 	cert_attr[0].type = CKA_ID;
9070b3
-	cert_attr[1].type = CKA_SUBJECT;
9070b3
-	cert_attr[2].type = CKA_VALUE;
9070b3
+	cert_attr[1].type = CKA_LABEL;
9070b3
+	cert_attr[2].type = CKA_SUBJECT;
9070b3
+	cert_attr[3].type = CKA_VALUE;
9070b3
 
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
-	f = p->function_list;
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
 
9070b3
 	/* figure out size of the attributes */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, cert_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		return -1;
9070b3
@@ -955,18 +1114,19 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 	 * XXX assumes CKA_ID is always first.
9070b3
 	 */
9070b3
 	if (cert_attr[1].ulValueLen == 0 ||
9070b3
-	    cert_attr[2].ulValueLen == 0) {
9070b3
+	    cert_attr[2].ulValueLen == 0 ||
9070b3
+	    cert_attr[3].ulValueLen == 0) {
9070b3
 		error("invalid attribute length");
9070b3
 		return -1;
9070b3
 	}
9070b3
 
9070b3
 	/* allocate buffers for attributes */
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		if (cert_attr[i].ulValueLen > 0)
9070b3
 			cert_attr[i].pValue = xcalloc(1, cert_attr[i].ulValueLen);
9070b3
 
9070b3
 	/* retrieve ID, subject and value of certificate */
9070b3
-	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
9070b3
+	rv = f->C_GetAttributeValue(session, *obj, cert_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_GetAttributeValue failed: %lu", rv);
9070b3
 		goto out;
9070b3
@@ -980,8 +1140,8 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 		subject = xstrdup("invalid subject");
9070b3
 	X509_NAME_free(x509_name);
9070b3
 
9070b3
-	cp = cert_attr[2].pValue;
9070b3
-	if ((x509 = d2i_X509(NULL, &cp, cert_attr[2].ulValueLen)) == NULL) {
9070b3
+	cp = cert_attr[3].pValue;
9070b3
+	if ((x509 = d2i_X509(NULL, &cp, cert_attr[3].ulValueLen)) == NULL) {
9070b3
 		error("d2i_x509 failed");
9070b3
 		goto out;
9070b3
 	}
9070b3
@@ -1001,7 +1161,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 			goto out;
9070b3
 		}
9070b3
 
9070b3
-		if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], rsa))
9070b3
+		if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], &cert_attr[1], rsa))
9070b3
 			goto out;
9070b3
 
9070b3
 		key = sshkey_new(KEY_UNSPEC);
9070b3
@@ -1031,7 +1191,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 			goto out;
9070b3
 		}
9070b3
 
9070b3
-		if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], ec))
9070b3
+		if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], &cert_attr[1], ec))
9070b3
 			goto out;
9070b3
 
9070b3
 		key = sshkey_new(KEY_UNSPEC);
9070b3
@@ -1051,7 +1211,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_p
9070b3
 		goto out;
9070b3
 	}
9070b3
  out:
9070b3
-	for (i = 0; i < 3; i++)
9070b3
+	for (i = 0; i < nattr; i++)
9070b3
 		free(cert_attr[i].pValue);
9070b3
 	X509_free(x509);
9070b3
 	RSA_free(rsa);
9070b3
@@ -1102,11 +1262,12 @@ note_key(struct pkcs11_provider *p, CK_U
9070b3
  */
9070b3
 static int
9070b3
 pkcs11_fetch_certs(struct pkcs11_provider *p, CK_ULONG slotidx,
9070b3
-    struct sshkey ***keysp, char ***labelsp, int *nkeys)
9070b3
+    struct sshkey ***keysp, char ***labelsp, int *nkeys, struct pkcs11_uri *uri)
9070b3
 {
9070b3
 	struct sshkey		*key = NULL;
9070b3
 	CK_OBJECT_CLASS		 key_class;
9070b3
-	CK_ATTRIBUTE		 key_attr[1];
9070b3
+	CK_ATTRIBUTE		 key_attr[3];
9070b3
+	int			 nattr = 1;
9070b3
 	CK_SESSION_HANDLE	 session;
9070b3
 	CK_FUNCTION_LIST	*f = NULL;
9070b3
 	CK_RV			 rv;
9070b3
@@ -1123,10 +1284,23 @@ pkcs11_fetch_certs(struct pkcs11_provide
9070b3
 	key_attr[0].pValue = &key_class;
9070b3
 	key_attr[0].ulValueLen = sizeof(key_class);
9070b3
 
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
-	f = p->function_list;
9070b3
+	if (uri->id != NULL) {
9070b3
+		key_attr[nattr].type = CKA_ID;
9070b3
+		key_attr[nattr].pValue = uri->id;
9070b3
+		key_attr[nattr].ulValueLen = uri->id_len;
9070b3
+		nattr++;
9070b3
+	}
9070b3
+	if (uri->object != NULL) {
9070b3
+		key_attr[nattr].type = CKA_LABEL;
9070b3
+		key_attr[nattr].pValue = uri->object;
9070b3
+		key_attr[nattr].ulValueLen = strlen(uri->object);
9070b3
+		nattr++;
9070b3
+	}
9070b3
+
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
 
9070b3
-	rv = f->C_FindObjectsInit(session, key_attr, 1);
9070b3
+	rv = f->C_FindObjectsInit(session, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_FindObjectsInit failed: %lu", rv);
9070b3
 		goto fail;
9070b3
@@ -1207,11 +1381,12 @@ fail:
9070b3
  */
9070b3
 static int
9070b3
 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
9070b3
-    struct sshkey ***keysp, char ***labelsp, int *nkeys)
9070b3
+    struct sshkey ***keysp, char ***labelsp, int *nkeys, struct pkcs11_uri *uri)
9070b3
 {
9070b3
 	struct sshkey		*key = NULL;
9070b3
 	CK_OBJECT_CLASS		 key_class;
9070b3
-	CK_ATTRIBUTE		 key_attr[2];
9070b3
+	CK_ATTRIBUTE		 key_attr[3];
9070b3
+	int			 nattr = 1;
9070b3
 	CK_SESSION_HANDLE	 session;
9070b3
 	CK_FUNCTION_LIST	*f = NULL;
9070b3
 	CK_RV			 rv;
9070b3
@@ -1227,10 +1402,23 @@ pkcs11_fetch_keys(struct pkcs11_provider
9070b3
 	key_attr[0].pValue = &key_class;
9070b3
 	key_attr[0].ulValueLen = sizeof(key_class);
9070b3
 
9070b3
-	session = p->slotinfo[slotidx].session;
9070b3
-	f = p->function_list;
9070b3
+	if (uri->id != NULL) {
9070b3
+		key_attr[nattr].type = CKA_ID;
9070b3
+		key_attr[nattr].pValue = uri->id;
9070b3
+		key_attr[nattr].ulValueLen = uri->id_len;
9070b3
+		nattr++;
9070b3
+	}
9070b3
+	if (uri->object != NULL) {
9070b3
+		key_attr[nattr].type = CKA_LABEL;
9070b3
+		key_attr[nattr].pValue = uri->object;
9070b3
+		key_attr[nattr].ulValueLen = strlen(uri->object);
9070b3
+		nattr++;
9070b3
+	}
9070b3
 
9070b3
-	rv = f->C_FindObjectsInit(session, key_attr, 1);
9070b3
+	session = p->module->slotinfo[slotidx].session;
9070b3
+	f = p->module->function_list;
9070b3
+
9070b3
+	rv = f->C_FindObjectsInit(session, key_attr, nattr);
9070b3
 	if (rv != CKR_OK) {
9070b3
 		error("C_FindObjectsInit failed: %lu", rv);
9070b3
 		goto fail;
9070b3
@@ -1499,16 +1690,10 @@ pkcs11_ecdsa_generate_private_key(struct
9070b3
 }
9070b3
 #endif /* WITH_PKCS11_KEYGEN */
9070b3
 
9070b3
-/*
9070b3
- * register a new provider, fails if provider already exists. if
9070b3
- * keyp is provided, fetch keys.
9070b3
- */
9070b3
 static int
9070b3
-pkcs11_register_provider(char *provider_id, char *pin,
9070b3
-    struct sshkey ***keyp, char ***labelsp,
9070b3
-    struct pkcs11_provider **providerp, CK_ULONG user)
9070b3
+pkcs11_initialize_provider(struct pkcs11_uri *uri, struct pkcs11_provider **providerp)
9070b3
 {
9070b3
-	int nkeys, need_finalize = 0;
9070b3
+	int need_finalize = 0;
9070b3
 	int ret = -1;
9070b3
 	struct pkcs11_provider *p = NULL;
9070b3
 	void *handle = NULL;
9070b3
@@ -1517,164 +1699,298 @@ pkcs11_register_provider(char *provider_
9070b3
 	CK_FUNCTION_LIST *f = NULL;
9070b3
 	CK_TOKEN_INFO *token;
9070b3
 	CK_ULONG i;
9070b3
+	char *provider_module = NULL;
9070b3
+	struct pkcs11_module *m = NULL;
9070b3
 
9070b3
-	if (providerp == NULL)
9070b3
+	/* if no provider specified, fallback to p11-kit */
9070b3
+	if (uri->module_path == NULL) {
9070b3
+#ifdef PKCS11_DEFAULT_PROVIDER
9070b3
+		provider_module = strdup(PKCS11_DEFAULT_PROVIDER);
9070b3
+#else
9070b3
+		error_f("No module path provided");
9070b3
 		goto fail;
9070b3
-	*providerp = NULL;
9070b3
+#endif
9070b3
+	} else {
9070b3
+		provider_module = strdup(uri->module_path);
9070b3
+	}
9070b3
 
9070b3
-	if (keyp != NULL)
9070b3
-		*keyp = NULL;
9070b3
-	if (labelsp != NULL)
9070b3
-		*labelsp = NULL;
9070b3
+	p = xcalloc(1, sizeof(*p));
9070b3
+	p->name = pkcs11_uri_get(uri);
9070b3
 
9070b3
-	if (pkcs11_provider_lookup(provider_id) != NULL) {
9070b3
-		debug_f("provider already registered: %s", provider_id);
9070b3
-		goto fail;
9070b3
+	if ((m = pkcs11_provider_lookup_module(provider_module)) != NULL
9070b3
+	   && m->valid) {
9070b3
+		debug_f("provider module already initialized: %s", provider_module);
9070b3
+		free(provider_module);
9070b3
+		/* Skip the initialization of PKCS#11 module */
9070b3
+		m->refcount++;
9070b3
+		p->module = m;
9070b3
+		p->valid = 1;
9070b3
+		TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
9070b3
+		p->refcount++;	/* add to provider list */
9070b3
+		*providerp = p;
9070b3
+		return 0;
9070b3
+	} else {
9070b3
+		m = xcalloc(1, sizeof(*m));
9070b3
+		p->module = m;
9070b3
+		m->refcount++;
9070b3
 	}
9070b3
+
9070b3
 	/* open shared pkcs11-library */
9070b3
-	if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
9070b3
-		error("dlopen %s failed: %s", provider_id, dlerror());
9070b3
+	if ((handle = dlopen(provider_module, RTLD_NOW)) == NULL) {
9070b3
+		error("dlopen %s failed: %s", provider_module, dlerror());
9070b3
 		goto fail;
9070b3
 	}
9070b3
 	if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
9070b3
 		error("dlsym(C_GetFunctionList) failed: %s", dlerror());
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	p = xcalloc(1, sizeof(*p));
9070b3
-	p->name = xstrdup(provider_id);
9070b3
-	p->handle = handle;
9070b3
+
9070b3
+	p->module->handle = handle;
9070b3
 	/* setup the pkcs11 callbacks */
9070b3
 	if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
9070b3
 		error("C_GetFunctionList for provider %s failed: %lu",
9070b3
-		    provider_id, rv);
9070b3
+		    provider_module, rv);
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	p->function_list = f;
9070b3
+	m->function_list = f;
9070b3
 	if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
9070b3
 		error("C_Initialize for provider %s failed: %lu",
9070b3
-		    provider_id, rv);
9070b3
+		    provider_module, rv);
9070b3
 		goto fail;
9070b3
 	}
9070b3
 	need_finalize = 1;
9070b3
-	if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
9070b3
+	if ((rv = f->C_GetInfo(&m->info)) != CKR_OK) {
9070b3
 		error("C_GetInfo for provider %s failed: %lu",
9070b3
-		    provider_id, rv);
9070b3
+		    provider_module, rv);
9070b3
+		goto fail;
9070b3
+	}
9070b3
+	rmspace(m->info.manufacturerID, sizeof(m->info.manufacturerID));
9070b3
+	if (uri->lib_manuf != NULL &&
9070b3
+	    strcmp(uri->lib_manuf, m->info.manufacturerID)) {
9070b3
+		debug_f("Skipping provider %s not matching library_manufacturer",
9070b3
+		    m->info.manufacturerID);
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
9070b3
-	rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
9070b3
+	rmspace(m->info.libraryDescription, sizeof(m->info.libraryDescription));
9070b3
 	debug("provider %s: manufacturerID <%s> cryptokiVersion %d.%d"
9070b3
 	    " libraryDescription <%s> libraryVersion %d.%d",
9070b3
-	    provider_id,
9070b3
-	    p->info.manufacturerID,
9070b3
-	    p->info.cryptokiVersion.major,
9070b3
-	    p->info.cryptokiVersion.minor,
9070b3
-	    p->info.libraryDescription,
9070b3
-	    p->info.libraryVersion.major,
9070b3
-	    p->info.libraryVersion.minor);
9070b3
-	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
9070b3
+	    provider_module,
9070b3
+	    m->info.manufacturerID,
9070b3
+	    m->info.cryptokiVersion.major,
9070b3
+	    m->info.cryptokiVersion.minor,
9070b3
+	    m->info.libraryDescription,
9070b3
+	    m->info.libraryVersion.major,
9070b3
+	    m->info.libraryVersion.minor);
9070b3
+
9070b3
+	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &m->nslots)) != CKR_OK) {
9070b3
 		error("C_GetSlotList failed: %lu", rv);
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	if (p->nslots == 0) {
9070b3
-		debug_f("provider %s returned no slots", provider_id);
9070b3
+	if (m->nslots == 0) {
9070b3
+		debug_f("provider %s returned no slots", provider_module);
9070b3
 		ret = -SSH_PKCS11_ERR_NO_SLOTS;
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
9070b3
-	if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
9070b3
+	m->slotlist = xcalloc(m->nslots, sizeof(CK_SLOT_ID));
9070b3
+	if ((rv = f->C_GetSlotList(CK_TRUE, m->slotlist, &m->nslots))
9070b3
 	    != CKR_OK) {
9070b3
 		error("C_GetSlotList for provider %s failed: %lu",
9070b3
-		    provider_id, rv);
9070b3
+		    provider_module, rv);
9070b3
 		goto fail;
9070b3
 	}
9070b3
-	p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
9070b3
 	p->valid = 1;
9070b3
-	nkeys = 0;
9070b3
-	for (i = 0; i < p->nslots; i++) {
9070b3
-		token = &p->slotinfo[i].token;
9070b3
-		if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
9070b3
+	m->slotinfo = xcalloc(m->nslots, sizeof(struct pkcs11_slotinfo));
9070b3
+	m->valid = 1;
9070b3
+	for (i = 0; i < m->nslots; i++) {
9070b3
+		token = &m->slotinfo[i].token;
9070b3
+		if ((rv = f->C_GetTokenInfo(m->slotlist[i], token))
9070b3
 		    != CKR_OK) {
9070b3
 			error("C_GetTokenInfo for provider %s slot %lu "
9070b3
-			    "failed: %lu", provider_id, (u_long)i, rv);
9070b3
-			continue;
9070b3
-		}
9070b3
-		if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
9070b3
-			debug2_f("ignoring uninitialised token in "
9070b3
-			    "provider %s slot %lu", provider_id, (u_long)i);
9070b3
+			    "failed: %lu", provider_module, (u_long)i, rv);
9070b3
+			token->flags = 0;
9070b3
 			continue;
9070b3
 		}
9070b3
 		rmspace(token->label, sizeof(token->label));
9070b3
 		rmspace(token->manufacturerID, sizeof(token->manufacturerID));
9070b3
 		rmspace(token->model, sizeof(token->model));
9070b3
 		rmspace(token->serialNumber, sizeof(token->serialNumber));
9070b3
+	}
9070b3
+	m->module_path = provider_module;
9070b3
+	provider_module = NULL;
9070b3
+
9070b3
+	/* insert unconditionally -- remove if there will be no keys later */
9070b3
+	TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
9070b3
+	p->refcount++;	/* add to provider list */
9070b3
+	*providerp = p;
9070b3
+	return 0;
9070b3
+
9070b3
+fail:
9070b3
+	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
9070b3
+		error("C_Finalize for provider %s failed: %lu",
9070b3
+		    provider_module, rv);
9070b3
+	free(provider_module);
9070b3
+	if (m) {
9070b3
+		free(m->slotlist);
9070b3
+		free(m);
9070b3
+	}
9070b3
+	if (p) {
9070b3
+		free(p->name);
9070b3
+		free(p);
9070b3
+	}
9070b3
+	if (handle)
9070b3
+		dlclose(handle);
9070b3
+	return ret;
9070b3
+}
9070b3
+
9070b3
+/*
9070b3
+ * register a new provider, fails if provider already exists. if
9070b3
+ * keyp is provided, fetch keys.
9070b3
+ */
9070b3
+static int
9070b3
+pkcs11_register_provider_by_uri(struct pkcs11_uri *uri, char *pin,
9070b3
+    struct sshkey ***keyp, char ***labelsp, struct pkcs11_provider **providerp,
9070b3
+    CK_ULONG user)
9070b3
+{
9070b3
+	int nkeys;
9070b3
+	int ret = -1;
9070b3
+	struct pkcs11_provider *p = NULL;
9070b3
+	CK_ULONG i;
9070b3
+	CK_TOKEN_INFO *token;
9070b3
+	char *provider_uri = NULL;
9070b3
+
9070b3
+	if (providerp == NULL)
9070b3
+		goto fail;
9070b3
+	*providerp = NULL;
9070b3
+
9070b3
+	if (keyp != NULL)
9070b3
+		*keyp = NULL;
9070b3
+
9070b3
+	if ((ret = pkcs11_initialize_provider(uri, &p)) != 0) {
9070b3
+		goto fail;
9070b3
+	}
9070b3
+
9070b3
+	provider_uri = pkcs11_uri_get(uri);
9070b3
+	if (pin == NULL && uri->pin != NULL) {
9070b3
+		pin = uri->pin;
9070b3
+	}
9070b3
+	nkeys = 0;
9070b3
+	for (i = 0; i < p->module->nslots; i++) {
9070b3
+		token = &p->module->slotinfo[i].token;
9070b3
+		if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
9070b3
+			debug2_f("ignoring uninitialised token in "
9070b3
+			    "provider %s slot %lu", provider_uri, (u_long)i);
9070b3
+			continue;
9070b3
+		}
9070b3
+		if (uri->token != NULL &&
9070b3
+		    strcmp(token->label, uri->token) != 0) {
9070b3
+			debug2_f("ignoring token not matching label (%s) "
9070b3
+			    "specified by PKCS#11 URI in slot %lu",
9070b3
+			    token->label, (unsigned long)i);
9070b3
+			continue;
9070b3
+		}
9070b3
+		if (uri->manuf != NULL &&
9070b3
+		    strcmp(token->manufacturerID, uri->manuf) != 0) {
9070b3
+			debug2_f("ignoring token not matching requrested "
9070b3
+			    "manufacturerID (%s) specified by PKCS#11 URI in "
9070b3
+			    "slot %lu", token->manufacturerID, (unsigned long)i);
9070b3
+			continue;
9070b3
+		}
9070b3
 		debug("provider %s slot %lu: label <%s> manufacturerID <%s> "
9070b3
 		    "model <%s> serial <%s> flags 0x%lx",
9070b3
-		    provider_id, (unsigned long)i,
9070b3
+		    provider_uri, (unsigned long)i,
9070b3
 		    token->label, token->manufacturerID, token->model,
9070b3
 		    token->serialNumber, token->flags);
9070b3
 		/*
9070b3
-		 * open session, login with pin and retrieve public
9070b3
-		 * keys (if keyp is provided)
9070b3
+		 * open session if not yet openend, login with pin and
9070b3
+		 * retrieve public keys (if keyp is provided)
9070b3
 		 */
9070b3
-		if ((ret = pkcs11_open_session(p, i, pin, user)) != 0 ||
9070b3
+		if ((p->module->slotinfo[i].session != 0 ||
9070b3
+		    (ret = pkcs11_open_session(p, i, pin, user)) != 0) && /* ??? */
9070b3
 		    keyp == NULL)
9070b3
 			continue;
9070b3
-		pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
9070b3
-		pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
9070b3
-		if (nkeys == 0 && !p->slotinfo[i].logged_in &&
9070b3
+		pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+		pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+		if (nkeys == 0 && !p->module->slotinfo[i].logged_in &&
9070b3
 		    pkcs11_interactive) {
9070b3
 			/*
9070b3
 			 * Some tokens require login before they will
9070b3
 			 * expose keys.
9070b3
 			 */
9070b3
-			if (pkcs11_login_slot(p, &p->slotinfo[i],
9070b3
+			debug3_f("Trying to login as there were no keys found");
9070b3
+			if (pkcs11_login_slot(p, &p->module->slotinfo[i],
9070b3
 			    CKU_USER) < 0) {
9070b3
 				error("login failed");
9070b3
 				continue;
9070b3
 			}
9070b3
-			pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
9070b3
-			pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
9070b3
+			pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+			pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+		}
9070b3
+		if (nkeys == 0 && uri->object != NULL) {
9070b3
+			debug3_f("No keys found. Retrying without label (%s) ",
9070b3
+			    uri->object);
9070b3
+			/* Try once more without the label filter */
9070b3
+			char *label = uri->object;
9070b3
+			uri->object = NULL; /* XXX clone uri? */
9070b3
+			pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+			pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys, uri);
9070b3
+			uri->object = label;
9070b3
 		}
9070b3
 	}
9070b3
+	pin = NULL; /* Will be cleaned up with URI */
9070b3
 
9070b3
 	/* now owned by caller */
9070b3
 	*providerp = p;
9070b3
 
9070b3
-	TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
9070b3
-	p->refcount++;	/* add to provider list */
9070b3
-
9070b3
+	free(provider_uri);
9070b3
 	return (nkeys);
9070b3
 fail:
9070b3
-	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
9070b3
-		error("C_Finalize for provider %s failed: %lu",
9070b3
-		    provider_id, rv);
9070b3
 	if (p) {
9070b3
-		free(p->name);
9070b3
-		free(p->slotlist);
9070b3
-		free(p->slotinfo);
9070b3
-		free(p);
9070b3
+ 		TAILQ_REMOVE(&pkcs11_providers, p, next);
9070b3
+		pkcs11_provider_unref(p);
9070b3
 	}
9070b3
-	if (handle)
9070b3
-		dlclose(handle);
9070b3
 	if (ret > 0)
9070b3
 		ret = -1;
9070b3
 	return (ret);
9070b3
 }
9070b3
 
9070b3
-/*
9070b3
- * register a new provider and get number of keys hold by the token,
9070b3
- * fails if provider already exists
9070b3
- */
9070b3
+static int
9070b3
+pkcs11_register_provider(char *provider_id, char *pin, struct sshkey ***keyp,
9070b3
+    char ***labelsp, struct pkcs11_provider **providerp, CK_ULONG user)
9070b3
+{
9070b3
+	struct pkcs11_uri *uri = NULL;
9070b3
+	int r;
9070b3
+
9070b3
+	debug_f("called, provider_id = %s", provider_id);
9070b3
+
9070b3
+	uri = pkcs11_uri_init();
9070b3
+	if (uri == NULL)
9070b3
+		fatal("failed to init PKCS#11 URI");
9070b3
+
9070b3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
9070b3
+			fatal("Failed to parse PKCS#11 URI");
9070b3
+	} else {
9070b3
+		uri->module_path = strdup(provider_id);
9070b3
+	}
9070b3
+
9070b3
+	r = pkcs11_register_provider_by_uri(uri, pin, keyp, labelsp, providerp, user);
9070b3
+	pkcs11_uri_cleanup(uri);
9070b3
+
9070b3
+	return r;
9070b3
+}
9070b3
+
9070b3
 int
9070b3
-pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp,
9070b3
-    char ***labelsp)
9070b3
+pkcs11_add_provider_by_uri(struct pkcs11_uri *uri, char *pin,
9070b3
+    struct sshkey ***keyp, char ***labelsp)
9070b3
 {
9070b3
 	struct pkcs11_provider *p = NULL;
9070b3
 	int nkeys;
9070b3
+	char *provider_uri = pkcs11_uri_get(uri);
9070b3
+
9070b3
+	debug_f("called, provider_uri = %s", provider_uri);
9070b3
 
9070b3
-	nkeys = pkcs11_register_provider(provider_id, pin, keyp, labelsp,
9070b3
-	    &p, CKU_USER);
9070b3
+	nkeys = pkcs11_register_provider_by_uri(uri, pin, keyp, labelsp, &p, CKU_USER);
9070b3
 
9070b3
 	/* no keys found or some other error, de-register provider */
9070b3
 	if (nkeys <= 0 && p != NULL) {
9070b3
@@ -1683,7 +1999,37 @@ pkcs11_add_provider(char *provider_id, c
9070b3
 		pkcs11_provider_unref(p);
9070b3
 	}
9070b3
 	if (nkeys == 0)
9070b3
-		debug_f("provider %s returned no keys", provider_id);
9070b3
+		debug_f("provider %s returned no keys", provider_uri);
9070b3
+
9070b3
+	free(provider_uri);
9070b3
+	return nkeys;
9070b3
+}
9070b3
+
9070b3
+/*
9070b3
+ * register a new provider and get number of keys hold by the token,
9070b3
+ * fails if provider already exists
9070b3
+ */
9070b3
+int
9070b3
+pkcs11_add_provider(char *provider_id, char *pin,
9070b3
+    struct sshkey ***keyp, char ***labelsp)
9070b3
+{
9070b3
+	struct pkcs11_uri *uri;
9070b3
+	int nkeys;
9070b3
+
9070b3
+	uri = pkcs11_uri_init();
9070b3
+	if (uri == NULL)
9070b3
+		fatal("Failed to init PKCS#11 URI");
9070b3
+
9070b3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
9070b3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
9070b3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
9070b3
+			fatal("Failed to parse PKCS#11 URI");
9070b3
+	} else {
9070b3
+		uri->module_path = strdup(provider_id);
9070b3
+	}
9070b3
+
9070b3
+	nkeys = pkcs11_add_provider_by_uri(uri, pin, keyp, labelsp);
9070b3
+	pkcs11_uri_cleanup(uri);
9070b3
 
9070b3
 	return (nkeys);
9070b3
 }
9070b3
diff -up openssh-8.6p1/ssh-pkcs11.h.pkcs11-uri openssh-8.6p1/ssh-pkcs11.h
9070b3
--- openssh-8.6p1/ssh-pkcs11.h.pkcs11-uri	2021-04-16 05:55:25.000000000 +0200
9070b3
+++ openssh-8.6p1/ssh-pkcs11.h	2021-05-06 11:35:55.115653297 +0200
9070b3
@@ -22,10 +22,14 @@
9070b3
 #define	SSH_PKCS11_ERR_PIN_REQUIRED		4
9070b3
 #define	SSH_PKCS11_ERR_PIN_LOCKED		5
9070b3
 
9070b3
+#include "ssh-pkcs11-uri.h"
9070b3
+
9070b3
 int	pkcs11_init(int);
9070b3
 void	pkcs11_terminate(void);
9070b3
 int	pkcs11_add_provider(char *, char *, struct sshkey ***, char ***);
9070b3
+int	pkcs11_add_provider_by_uri(struct pkcs11_uri *, char *, struct sshkey ***, char ***);
9070b3
 int	pkcs11_del_provider(char *);
9070b3
+int	pkcs11_uri_write(const struct sshkey *, FILE *);
9070b3
 #ifdef WITH_PKCS11_KEYGEN
9070b3
 struct sshkey *
9070b3
 	pkcs11_gakp(char *, char *, unsigned int, char *, unsigned int,
9070b3
diff -up openssh-8.6p1/ssh-pkcs11-uri.c.pkcs11-uri openssh-8.6p1/ssh-pkcs11-uri.c
9070b3
--- openssh-8.6p1/ssh-pkcs11-uri.c.pkcs11-uri	2021-05-06 11:35:55.114653289 +0200
9070b3
+++ openssh-8.6p1/ssh-pkcs11-uri.c	2021-05-06 11:35:55.114653289 +0200
9070b3
@@ -0,0 +1,419 @@
9070b3
+/*
9070b3
+ * Copyright (c) 2017 Red Hat
9070b3
+ *
9070b3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
9070b3
+ *
9070b3
+ * Permission to use, copy, modify, and distribute this software for any
9070b3
+ * purpose with or without fee is hereby granted, provided that the above
9070b3
+ * copyright notice and this permission notice appear in all copies.
9070b3
+ *
9070b3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9070b3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9070b3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
9070b3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
9070b3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
9070b3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
9070b3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
9070b3
+ */
9070b3
+
9070b3
+#include "includes.h"
9070b3
+
9070b3
+#ifdef ENABLE_PKCS11
9070b3
+
9070b3
+#include <stdio.h>
9070b3
+#include <string.h>
9070b3
+
9070b3
+#include "sshkey.h"
9070b3
+#include "sshbuf.h"
9070b3
+#include "log.h"
9070b3
+
9070b3
+#define CRYPTOKI_COMPAT
9070b3
+#include "pkcs11.h"
9070b3
+
9070b3
+#include "ssh-pkcs11-uri.h"
9070b3
+
9070b3
+#define PKCS11_URI_PATH_SEPARATOR ";"
9070b3
+#define PKCS11_URI_QUERY_SEPARATOR "&"
9070b3
+#define PKCS11_URI_VALUE_SEPARATOR "="
9070b3
+#define PKCS11_URI_ID "id"
9070b3
+#define PKCS11_URI_TOKEN "token"
9070b3
+#define PKCS11_URI_OBJECT "object"
9070b3
+#define PKCS11_URI_LIB_MANUF "library-manufacturer"
9070b3
+#define PKCS11_URI_MANUF "manufacturer"
9070b3
+#define PKCS11_URI_MODULE_PATH "module-path"
9070b3
+#define PKCS11_URI_PIN_VALUE "pin-value"
9070b3
+
9070b3
+/* Keyword tokens. */
9070b3
+typedef enum {
9070b3
+	pId, pToken, pObject, pLibraryManufacturer, pManufacturer, pModulePath,
9070b3
+	pPinValue, pBadOption
9070b3
+} pkcs11uriOpCodes;
9070b3
+
9070b3
+/* Textual representation of the tokens. */
9070b3
+static struct {
9070b3
+	const char *name;
9070b3
+	pkcs11uriOpCodes opcode;
9070b3
+} keywords[] = {
9070b3
+	{ PKCS11_URI_ID, pId },
9070b3
+	{ PKCS11_URI_TOKEN, pToken },
9070b3
+	{ PKCS11_URI_OBJECT, pObject },
9070b3
+	{ PKCS11_URI_LIB_MANUF, pLibraryManufacturer },
9070b3
+	{ PKCS11_URI_MANUF, pManufacturer },
9070b3
+	{ PKCS11_URI_MODULE_PATH, pModulePath },
9070b3
+	{ PKCS11_URI_PIN_VALUE, pPinValue },
9070b3
+	{ NULL, pBadOption }
9070b3
+};
9070b3
+
9070b3
+static pkcs11uriOpCodes
9070b3
+parse_token(const char *cp)
9070b3
+{
9070b3
+	u_int i;
9070b3
+
9070b3
+	for (i = 0; keywords[i].name; i++)
9070b3
+		if (strncasecmp(cp, keywords[i].name,
9070b3
+		    strlen(keywords[i].name)) == 0)
9070b3
+			return keywords[i].opcode;
9070b3
+
9070b3
+	return pBadOption;
9070b3
+}
9070b3
+
9070b3
+int
9070b3
+percent_decode(char *data, char **outp)
9070b3
+{
9070b3
+	char tmp[3];
9070b3
+	char *out, *tmp_end;
9070b3
+	char *p = data;
9070b3
+	long value;
9070b3
+	size_t outlen = 0;
9070b3
+
9070b3
+	out = malloc(strlen(data)+1); /* upper bound */
9070b3
+	if (out == NULL)
9070b3
+		return -1;
9070b3
+	while (*p != '\0') {
9070b3
+		switch (*p) {
9070b3
+		case '%':
9070b3
+			p++;
9070b3
+			if (*p == '\0')
9070b3
+				goto fail;
9070b3
+			tmp[0] = *p++;
9070b3
+			if (*p == '\0')
9070b3
+				goto fail;
9070b3
+			tmp[1] = *p++;
9070b3
+			tmp[2] = '\0';
9070b3
+			tmp_end = NULL;
9070b3
+			value = strtol(tmp, &tmp_end, 16);
9070b3
+			if (tmp_end != tmp+2)
9070b3
+				goto fail;
9070b3
+			else
9070b3
+				out[outlen++] = (char) value;
9070b3
+			break;
9070b3
+		default:
9070b3
+			out[outlen++] = *p++;
9070b3
+			break;
9070b3
+		}
9070b3
+	}
9070b3
+
9070b3
+	/* zero terminate */
9070b3
+	out[outlen] = '\0';
9070b3
+	*outp = out;
9070b3
+	return outlen;
9070b3
+fail:
9070b3
+	free(out);
9070b3
+	return -1;
9070b3
+}
9070b3
+
9070b3
+struct sshbuf *
9070b3
+percent_encode(const char *data, size_t length, const char *allow_list)
9070b3
+{
9070b3
+	struct sshbuf *b = NULL;
9070b3
+	char tmp[4], *cp;
9070b3
+	size_t i;
9070b3
+
9070b3
+	if ((b = sshbuf_new()) == NULL)
9070b3
+		return NULL;
9070b3
+	for (i = 0; i < length; i++) {
9070b3
+		cp = strchr(allow_list, data[i]);
9070b3
+		/* if c is specified as '\0' pointer to terminator is returned !! */
9070b3
+		if (cp != NULL && *cp != '\0') {
9070b3
+			if (sshbuf_put(b, &data[i], 1) != 0)
9070b3
+				goto err;
9070b3
+		} else
9070b3
+			if (snprintf(tmp, 4, "%%%02X", (unsigned char) data[i]) < 3
9070b3
+			    || sshbuf_put(b, tmp, 3) != 0)
9070b3
+				goto err;
9070b3
+	}
9070b3
+	if (sshbuf_put(b, "\0", 1) == 0)
9070b3
+		return b;
9070b3
+err:
9070b3
+	sshbuf_free(b);
9070b3
+	return NULL;
9070b3
+}
9070b3
+
9070b3
+char *
9070b3
+pkcs11_uri_append(char *part, const char *separator, const char *key,
9070b3
+    struct sshbuf *value)
9070b3
+{
9070b3
+	char *new_part;
9070b3
+	size_t size = 0;
9070b3
+
9070b3
+	if (value == NULL)
9070b3
+		return NULL;
9070b3
+
9070b3
+	size = asprintf(&new_part,
9070b3
+	    "%s%s%s"  PKCS11_URI_VALUE_SEPARATOR "%s",
9070b3
+	    (part != NULL ? part : ""),
9070b3
+	    (part != NULL ? separator : ""),
9070b3
+	    key, sshbuf_ptr(value));
9070b3
+	sshbuf_free(value);
9070b3
+	free(part);
9070b3
+
9070b3
+	if (size <= 0)
9070b3
+		return NULL;
9070b3
+	return new_part;
9070b3
+}
9070b3
+
9070b3
+char *
9070b3
+pkcs11_uri_get(struct pkcs11_uri *uri)
9070b3
+{
9070b3
+	size_t size = 0;
9070b3
+	char *p = NULL, *path = NULL, *query = NULL;
9070b3
+
9070b3
+	/* compose a percent-encoded ID */
9070b3
+	if (uri->id_len > 0) {
9070b3
+		struct sshbuf *key_id = percent_encode(uri->id, uri->id_len, "");
9070b3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
9070b3
+		    PKCS11_URI_ID, key_id);
9070b3
+		if (path == NULL)
9070b3
+			goto err;
9070b3
+	}
9070b3
+
9070b3
+	/* Write object label */
9070b3
+	if (uri->object) {
9070b3
+		struct sshbuf *label = percent_encode(uri->object, strlen(uri->object),
9070b3
+		    PKCS11_URI_WHITELIST);
9070b3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
9070b3
+		    PKCS11_URI_OBJECT, label);
9070b3
+		if (path == NULL)
9070b3
+			goto err;
9070b3
+	}
9070b3
+
9070b3
+	/* Write token label */
9070b3
+	if (uri->token) {
9070b3
+		struct sshbuf *label = percent_encode(uri->token, strlen(uri->token),
9070b3
+		    PKCS11_URI_WHITELIST);
9070b3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
9070b3
+		    PKCS11_URI_TOKEN, label);
9070b3
+		if (path == NULL)
9070b3
+			goto err;
9070b3
+	}
9070b3
+
9070b3
+	/* Write manufacturer */
9070b3
+	if (uri->manuf) {
9070b3
+		struct sshbuf *manuf = percent_encode(uri->manuf,
9070b3
+		    strlen(uri->manuf), PKCS11_URI_WHITELIST);
9070b3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
9070b3
+		    PKCS11_URI_MANUF, manuf);
9070b3
+		if (path == NULL)
9070b3
+			goto err;
9070b3
+	}
9070b3
+
9070b3
+	/* Write module_path */
9070b3
+	if (uri->module_path) {
9070b3
+		struct sshbuf *module = percent_encode(uri->module_path,
9070b3
+		    strlen(uri->module_path), PKCS11_URI_WHITELIST "/");
9070b3
+		query = pkcs11_uri_append(query, PKCS11_URI_QUERY_SEPARATOR,
9070b3
+		    PKCS11_URI_MODULE_PATH, module);
9070b3
+		if (query == NULL)
9070b3
+			goto err;
9070b3
+	}
9070b3
+
9070b3
+	size = asprintf(&p, PKCS11_URI_SCHEME "%s%s%s",
9070b3
+	    path != NULL ? path : "",
9070b3
+	    query != NULL ? "?" : "",
9070b3
+	    query != NULL ? query : "");
9070b3
+err:
9070b3
+	free(query);
9070b3
+	free(path);
9070b3
+	if (size <= 0)
9070b3
+		return NULL;
9070b3
+	return p;
9070b3
+}
9070b3
+
9070b3
+struct pkcs11_uri *
9070b3
+pkcs11_uri_init()
9070b3
+{
9070b3
+	struct pkcs11_uri *d = calloc(1, sizeof(struct pkcs11_uri));
9070b3
+	return d;
9070b3
+}
9070b3
+
9070b3
+void
9070b3
+pkcs11_uri_cleanup(struct pkcs11_uri *pkcs11)
9070b3
+{
9070b3
+	if (pkcs11 == NULL) {
9070b3
+		return;
9070b3
+	}
9070b3
+
9070b3
+	free(pkcs11->id);
9070b3
+	free(pkcs11->module_path);
9070b3
+	free(pkcs11->token);
9070b3
+	free(pkcs11->object);
9070b3
+	free(pkcs11->lib_manuf);
9070b3
+	free(pkcs11->manuf);
9070b3
+	if (pkcs11->pin)
9070b3
+		freezero(pkcs11->pin, strlen(pkcs11->pin));
9070b3
+	free(pkcs11);
9070b3
+}
9070b3
+
9070b3
+int
9070b3
+pkcs11_uri_parse(const char *uri, struct pkcs11_uri *pkcs11)
9070b3
+{
9070b3
+	char *saveptr1, *saveptr2, *str1, *str2, *tok;
9070b3
+	int rv = 0, len;
9070b3
+	char *p = NULL;
9070b3
+
9070b3
+	size_t scheme_len = strlen(PKCS11_URI_SCHEME);
9070b3
+	if (strlen(uri) < scheme_len || /* empty URI matches everything */
9070b3
+	    strncmp(uri, PKCS11_URI_SCHEME, scheme_len) != 0) {
9070b3
+		error_f("The '%s' does not look like PKCS#11 URI", uri);
9070b3
+		return -1;
9070b3
+	}
9070b3
+
9070b3
+	if (pkcs11 == NULL) {
9070b3
+		error_f("Bad arguments. The pkcs11 can't be null");
9070b3
+		return -1;
9070b3
+	}
9070b3
+
9070b3
+	/* skip URI schema name */
9070b3
+	p = strdup(uri);
9070b3
+	str1 = p;
9070b3
+
9070b3
+	/* everything before ? */
9070b3
+	tok = strtok_r(str1, "?", &saveptr1);
9070b3
+	if (tok == NULL) {
9070b3
+		error_f("pk11-path expected, got EOF");
9070b3
+		rv = -1;
9070b3
+		goto out;
9070b3
+	}
9070b3
+
9070b3
+	/* skip URI schema name:
9070b3
+	 * the scheme ensures that there is at least something before "?"
9070b3
+	 * allowing empty pk11-path. Resulting token at worst pointing to
9070b3
+	 * \0 byte */
9070b3
+	tok = tok + scheme_len;
9070b3
+
9070b3
+	/* parse pk11-path */
9070b3
+	for (str2 = tok; ; str2 = NULL) {
9070b3
+		char **charptr, *arg = NULL;
9070b3
+		pkcs11uriOpCodes opcode;
9070b3
+		tok = strtok_r(str2, PKCS11_URI_PATH_SEPARATOR, &saveptr2);
9070b3
+		if (tok == NULL)
9070b3
+			break;
9070b3
+		opcode = parse_token(tok);
9070b3
+		if (opcode != pBadOption)
9070b3
+			arg = tok + strlen(keywords[opcode].name) + 1; /* separator "=" */
9070b3
+
9070b3
+		switch (opcode) {
9070b3
+		case pId:
9070b3
+			/* CKA_ID */
9070b3
+			if (pkcs11->id != NULL) {
9070b3
+				verbose_f("The id already set in the PKCS#11 URI");
9070b3
+				rv = -1;
9070b3
+				goto out;
9070b3
+			}
9070b3
+			len = percent_decode(arg, &pkcs11->id);
9070b3
+			if (len <= 0) {
9070b3
+				verbose_f("Failed to percent-decode CKA_ID: %s", arg);
9070b3
+				rv = -1;
9070b3
+				goto out;
9070b3
+			} else
9070b3
+				pkcs11->id_len = len;
9070b3
+			debug3_f("Setting CKA_ID = %s from PKCS#11 URI", arg);
9070b3
+			break;
9070b3
+		case pToken:
9070b3
+			/* CK_TOKEN_INFO -> label */
9070b3
+			charptr = &pkcs11->token;
9070b3
+ parse_string:
9070b3
+			if (*charptr != NULL) {
9070b3
+				verbose_f("The %s already set in the PKCS#11 URI",
9070b3
+				    keywords[opcode].name);
9070b3
+				rv = -1;
9070b3
+				goto out;
9070b3
+			}
9070b3
+			percent_decode(arg, charptr);
9070b3
+			debug3_f("Setting %s = %s from PKCS#11 URI",
9070b3
+			    keywords[opcode].name, *charptr);
9070b3
+			break;
9070b3
+
9070b3
+		case pObject:
9070b3
+			/* CK_TOKEN_INFO -> manufacturerID */
9070b3
+			charptr = &pkcs11->object;
9070b3
+			goto parse_string;
9070b3
+
9070b3
+		case pManufacturer:
9070b3
+			/* CK_TOKEN_INFO -> manufacturerID */
9070b3
+			charptr = &pkcs11->manuf;
9070b3
+			goto parse_string;
9070b3
+
9070b3
+		case pLibraryManufacturer:
9070b3
+			/* CK_INFO -> manufacturerID */
9070b3
+			charptr = &pkcs11->lib_manuf;
9070b3
+			goto parse_string;
9070b3
+
9070b3
+		default:
9070b3
+			/* Unrecognized attribute in the URI path SHOULD be error */
9070b3
+			verbose_f("Unknown part of path in PKCS#11 URI: %s", tok);
9070b3
+		}
9070b3
+	}
9070b3
+
9070b3
+	tok = strtok_r(NULL, "?", &saveptr1);
9070b3
+	if (tok == NULL) {
9070b3
+		goto out;
9070b3
+	}
9070b3
+	/* parse pk11-query (optional) */
9070b3
+	for (str2 = tok; ; str2 = NULL) {
9070b3
+		char *arg;
9070b3
+		pkcs11uriOpCodes opcode;
9070b3
+		tok = strtok_r(str2, PKCS11_URI_QUERY_SEPARATOR, &saveptr2);
9070b3
+		if (tok == NULL)
9070b3
+			break;
9070b3
+		opcode = parse_token(tok);
9070b3
+		if (opcode != pBadOption)
9070b3
+			arg = tok + strlen(keywords[opcode].name) + 1; /* separator "=" */
9070b3
+
9070b3
+		switch (opcode) {
9070b3
+		case pModulePath:
9070b3
+			/* module-path is PKCS11Provider */
9070b3
+			if (pkcs11->module_path != NULL) {
9070b3
+				verbose_f("Multiple module-path attributes are"
9070b3
+				    "not supported the PKCS#11 URI");
9070b3
+				rv = -1;
9070b3
+				goto out;
9070b3
+			}
9070b3
+			percent_decode(arg, &pkcs11->module_path);
9070b3
+			debug3_f("Setting PKCS11Provider = %s from PKCS#11 URI",
9070b3
+			    pkcs11->module_path);
9070b3
+			break;
9070b3
+
9070b3
+		case pPinValue:
9070b3
+			/* pin-value */
9070b3
+			if (pkcs11->pin != NULL) {
9070b3
+				verbose_f("Multiple pin-value attributes are"
9070b3
+				    "not supported the PKCS#11 URI");
9070b3
+				rv = -1;
9070b3
+				goto out;
9070b3
+			}
9070b3
+			percent_decode(arg, &pkcs11->pin);
9070b3
+			debug3_f("Setting PIN from PKCS#11 URI");
9070b3
+			break;
9070b3
+
9070b3
+		default:
9070b3
+			/* Unrecognized attribute in the URI query SHOULD be ignored */
9070b3
+			verbose_f("Unknown part of query in PKCS#11 URI: %s", tok);
9070b3
+		}
9070b3
+	}
9070b3
+out:
9070b3
+	free(p);
9070b3
+	return rv;
9070b3
+}
9070b3
+
9070b3
+#endif /* ENABLE_PKCS11 */
9070b3
diff -up openssh-8.6p1/ssh-pkcs11-uri.h.pkcs11-uri openssh-8.6p1/ssh-pkcs11-uri.h
9070b3
--- openssh-8.6p1/ssh-pkcs11-uri.h.pkcs11-uri	2021-05-06 11:35:55.114653289 +0200
9070b3
+++ openssh-8.6p1/ssh-pkcs11-uri.h	2021-05-06 11:35:55.114653289 +0200
9070b3
@@ -0,0 +1,42 @@
9070b3
+/*
9070b3
+ * Copyright (c) 2017 Red Hat
9070b3
+ *
9070b3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
9070b3
+ *
9070b3
+ * Permission to use, copy, modify, and distribute this software for any
9070b3
+ * purpose with or without fee is hereby granted, provided that the above
9070b3
+ * copyright notice and this permission notice appear in all copies.
9070b3
+ *
9070b3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9070b3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9070b3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
9070b3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
9070b3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
9070b3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
9070b3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
9070b3
+ */
9070b3
+
9070b3
+#define PKCS11_URI_SCHEME "pkcs11:"
9070b3
+#define PKCS11_URI_WHITELIST	"abcdefghijklmnopqrstuvwxyz" \
9070b3
+				"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
9070b3
+				"0123456789_-.()"
9070b3
+
9070b3
+struct pkcs11_uri {
9070b3
+	/* path */
9070b3
+	char *id;
9070b3
+	size_t id_len;
9070b3
+	char *token;
9070b3
+	char *object;
9070b3
+	char *lib_manuf;
9070b3
+	char *manuf;
9070b3
+	/* query */
9070b3
+	char *module_path;
9070b3
+	char *pin; /* Only parsed, but not printed */
9070b3
+};
9070b3
+
9070b3
+struct	 pkcs11_uri *pkcs11_uri_init();
9070b3
+void	 pkcs11_uri_cleanup(struct pkcs11_uri *);
9070b3
+int	 pkcs11_uri_parse(const char *, struct pkcs11_uri *);
9070b3
+struct	 pkcs11_uri *pkcs11_uri_init();
9070b3
+char	*pkcs11_uri_get(struct pkcs11_uri *uri);
9070b3
+