jonathancammack / rpms / openssh

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