4369a3
diff --git a/Makefile.in b/Makefile.in
4369a3
index 6f001bb3..c9424f1e 100644
4369a3
--- a/Makefile.in
4369a3
+++ b/Makefile.in
4369a3
@@ -93,7 +93,7 @@ LIBSSH_OBJS=${LIBOPENSSH_OBJS} \
4369a3
 	atomicio.o dispatch.o mac.o uuencode.o misc.o utf8.o \
4369a3
 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-ecdsa.o ssh-rsa.o dh.o \
4369a3
 	msg.o progressmeter.o dns.o entropy.o gss-genr.o umac.o umac128.o \
4369a3
-	ssh-pkcs11.o smult_curve25519_ref.o \
4369a3
+	ssh-pkcs11.o ssh-pkcs11-uri.o smult_curve25519_ref.o \
4369a3
 	poly1305.o chacha.o cipher-chachapoly.o \
4369a3
 	ssh-ed25519.o digest-openssl.o digest-libc.o hmac.o \
4369a3
 	sc25519.o ge25519.o fe25519.o ed25519.o verify.o hash.o \
4369a3
@@ -250,6 +250,8 @@ clean:	regressclean
4369a3
 	rm -f regress/unittests/match/test_match$(EXEEXT)
4369a3
 	rm -f regress/unittests/utf8/*.o
4369a3
 	rm -f regress/unittests/utf8/test_utf8$(EXEEXT)
4369a3
+	rm -f regress/unittests/pkcs11/*.o
4369a3
+	rm -f regress/unittests/pkcs11/test_pkcs11$(EXEEXT)
4369a3
 	rm -f regress/misc/kexfuzz/*.o
4369a3
 	rm -f regress/misc/kexfuzz/kexfuzz$(EXEEXT)
4369a3
 	(cd openbsd-compat && $(MAKE) clean)
4369a3
@@ -280,6 +282,8 @@ distclean:	regressclean
4369a3
 	rm -f regress/unittests/match/test_match
4369a3
 	rm -f regress/unittests/utf8/*.o
4369a3
 	rm -f regress/unittests/utf8/test_utf8
4369a3
+	rm -f regress/unittests/pkcs11/*.o
4369a3
+	rm -f regress/unittests/pkcs11/test_pkcs11
4369a3
 	rm -f regress/misc/kexfuzz/*.o
4369a3
 	rm -f regress/misc/kexfuzz/kexfuzz$(EXEEXT)
4369a3
 	(cd openbsd-compat && $(MAKE) distclean)
4369a3
@@ -442,6 +446,7 @@ regress-prep:
4369a3
 	$(MKDIR_P) `pwd`/regress/unittests/kex
4369a3
 	$(MKDIR_P) `pwd`/regress/unittests/match
4369a3
 	$(MKDIR_P) `pwd`/regress/unittests/utf8
4369a3
+	$(MKDIR_P) `pwd`/regress/unittests/pkcs11
4369a3
 	$(MKDIR_P) `pwd`/regress/misc/kexfuzz
4369a3
 	[ -f `pwd`/regress/Makefile ] || \
4369a3
 	    ln -s `cd $(srcdir) && pwd`/regress/Makefile `pwd`/regress/Makefile
4369a3
@@ -565,6 +570,16 @@ regress/unittests/utf8/test_utf8$(EXEEXT): \
4369a3
 	    regress/unittests/test_helper/libtest_helper.a \
4369a3
 	    -lssh -lopenbsd-compat -lssh -lopenbsd-compat $(LIBS)
4369a3
 
4369a3
+UNITTESTS_TEST_PKCS11_OBJS=\
4369a3
+	regress/unittests/pkcs11/tests.o
4369a3
+
4369a3
+regress/unittests/pkcs11/test_pkcs11$(EXEEXT): \
4369a3
+    ${UNITTESTS_TEST_PKCS11_OBJS} \
4369a3
+    regress/unittests/test_helper/libtest_helper.a libssh.a
4369a3
+	$(LD) -o $@ $(LDFLAGS) $(UNITTESTS_TEST_PKCS11_OBJS) \
4369a3
+	    regress/unittests/test_helper/libtest_helper.a \
4369a3
+	    -lssh -lopenbsd-compat -lssh -lopenbsd-compat $(LIBS)
4369a3
+
4369a3
 MISC_KEX_FUZZ_OBJS=\
4369a3
 	regress/misc/kexfuzz/kexfuzz.o
4369a3
 
4369a3
@@ -585,6 +600,7 @@ regress-binaries: regress/modpipe$(EXEEXT) \
4369a3
 	regress/unittests/kex/test_kex$(EXEEXT) \
4369a3
 	regress/unittests/match/test_match$(EXEEXT) \
4369a3
 	regress/unittests/utf8/test_utf8$(EXEEXT) \
4369a3
+	regress/unittests/pkcs11/test_pkcs11$(EXEEXT) \
4369a3
 	regress/misc/kexfuzz/kexfuzz$(EXEEXT)
4369a3
 
4369a3
 tests interop-tests t-exec unit: regress-prep regress-binaries $(TARGETS)
4369a3
diff --git a/authfd.c b/authfd.c
4369a3
index 95348abf..5383df92 100644
4369a3
--- a/authfd.c
4369a3
+++ b/authfd.c
4369a3
@@ -312,6 +312,8 @@ ssh_free_identitylist(struct ssh_identitylist *idl)
4369a3
 		if (idl->comments != NULL)
4369a3
 			free(idl->comments[i]);
4369a3
 	}
4369a3
+	free(idl->keys);
4369a3
+	free(idl->comments);
4369a3
 	free(idl);
4369a3
 }
4369a3
 
4369a3
diff --git a/configure.ac b/configure.ac
4369a3
index 30be6c18..82459746 100644
4369a3
--- a/configure.ac
4369a3
+++ b/configure.ac
4369a3
@@ -1854,12 +1854,14 @@ AC_LINK_IFELSE(
4369a3
 	[AC_DEFINE([HAVE_ISBLANK], [1], [Define if you have isblank(3C).])
4369a3
 ])
4369a3
 
4369a3
+SCARD_MSG="yes"
4369a3
 disable_pkcs11=
4369a3
 AC_ARG_ENABLE([pkcs11],
4369a3
 	[  --disable-pkcs11        disable PKCS#11 support code [no]],
4369a3
 	[
4369a3
 		if test "x$enableval" = "xno" ; then
4369a3
 			disable_pkcs11=1
4369a3
+			SCARD_MSG="no"
4369a3
 		fi
4369a3
 	]
4369a3
 )
4369a3
@@ -1875,6 +1877,40 @@ if test "x$openssl" = "xyes" && test "x$disable_pkcs11" = "x"; then
4369a3
 	)
4369a3
 fi
4369a3
 
4369a3
+# Check whether we have a p11-kit, we got default provider on command line
4369a3
+DEFAULT_PKCS11_PROVIDER_MSG="no"
4369a3
+AC_ARG_WITH([default-pkcs11-provider],
4369a3
+	[  --with-default-pkcs11-provider[[=PATH]]   Use default pkcs11 provider (p11-kit detected by default)],
4369a3
+	[ if test "x$withval" != "xno" && test "x$disable_pkcs11" = "x"; then
4369a3
+		if test "x$withval" = "xyes" ; then
4369a3
+			AC_PATH_TOOL([PKGCONFIG], [pkg-config], [no])
4369a3
+			if test "x$PKGCONFIG" != "xno"; then
4369a3
+				AC_MSG_CHECKING([if $PKGCONFIG knows about p11-kit])
4369a3
+				if "$PKGCONFIG" "p11-kit-1"; then
4369a3
+					AC_MSG_RESULT([yes])
4369a3
+					use_pkgconfig_for_p11kit=yes
4369a3
+				else
4369a3
+					AC_MSG_RESULT([no])
4369a3
+				fi
4369a3
+			fi
4369a3
+		else
4369a3
+			PKCS11_PATH="${withval}"
4369a3
+		fi
4369a3
+		if test "x$use_pkgconfig_for_p11kit" = "xyes"; then
4369a3
+			PKCS11_PATH=`$PKGCONFIG --variable=proxy_module p11-kit-1`
4369a3
+		fi
4369a3
+		AC_CHECK_FILE("$PKCS11_PATH",
4369a3
+			[ AC_DEFINE_UNQUOTED([PKCS11_DEFAULT_PROVIDER], ["$PKCS11_PATH"], [Path to default PKCS#11 provider (p11-kit proxy)])
4369a3
+			  DEFAULT_PKCS11_PROVIDER_MSG="$PKCS11_PATH"
4369a3
+			],
4369a3
+			[ AC_MSG_ERROR([Requested PKCS11 provided not found]) ]
4369a3
+		)
4369a3
+	else
4369a3
+		AC_MSG_WARN([Needs PKCS11 support to enable default pkcs11 provider])
4369a3
+	fi ]
4369a3
+)
4369a3
+
4369a3
+
4369a3
 # IRIX has a const char return value for gai_strerror()
4369a3
 AC_CHECK_FUNCS([gai_strerror], [
4369a3
 	AC_DEFINE([HAVE_GAI_STRERROR])
4369a3
@@ -5256,6 +5292,7 @@ echo "           Translate v4 in v6 hack: $IPV4_IN6_HACK_MSG"
4369a3
 echo "                  BSD Auth support: $BSD_AUTH_MSG"
4369a3
 echo "              Random number source: $RAND_MSG"
4369a3
 echo "             Privsep sandbox style: $SANDBOX_STYLE"
4369a3
+echo "          Default PKCS#11 provider: $DEFAULT_PKCS11_PROVIDER_MSG"
4369a3
 
4369a3
 echo ""
4369a3
 
4369a3
diff --git a/regress/Makefile b/regress/Makefile
4369a3
index 925edf71..94bb25e9 100644
4369a3
--- a/regress/Makefile
4369a3
+++ b/regress/Makefile
4369a3
@@ -109,9 +109,11 @@ CLEANFILES=	*.core actual agent-key.* authorized_keys_${USERNAME} \
4369a3
 		known_hosts known_hosts-cert known_hosts.* krl-* ls.copy \
4369a3
 		modpipe netcat no_identity_config \
4369a3
 		pidfile putty.rsa2 ready regress.log \
4369a3
-		remote_pid revoked-* rsa rsa-agent rsa-agent.pub rsa.pub \
4369a3
+		remote_pid revoked-* rsa rsa-agent rsa-agent.pub \
4369a3
+		rsa-agent-cert.pub rsa.pub \
4369a3
 		rsa1 rsa1-agent rsa1-agent.pub rsa1.pub rsa_ssh2_cr.prv \
4369a3
-		rsa_ssh2_crnl.prv scp-ssh-wrapper.exe \
4369a3
+		pkcs11*.crt pkcs11*.key \
4369a3
+		pkcs11.info rsa_ssh2_crnl.prv scp-ssh-wrapper.exe \
4369a3
 		scp-ssh-wrapper.scp setuid-allowed sftp-server.log \
4369a3
 		sftp-server.sh sftp.log ssh-log-wrapper.sh ssh.log \
4369a3
 		ssh_config ssh_config.* ssh_proxy ssh_proxy_bak \
4369a3
@@ -231,6 +233,7 @@ unit:
4369a3
 		V="" ; \
4369a3
 		test "x${USE_VALGRIND}" = "x" || \
4369a3
 		    V=${.CURDIR}/valgrind-unit.sh ; \
4369a3
+		$$V ${.OBJDIR}/unittests/pkcs11/test_pkcs11 ; \
4369a3
 		$$V ${.OBJDIR}/unittests/sshbuf/test_sshbuf ; \
4369a3
 		$$V ${.OBJDIR}/unittests/sshkey/test_sshkey \
4369a3
 			-d ${.CURDIR}/unittests/sshkey/testdata ; \
4369a3
diff --git a/regress/agent-pkcs11.sh b/regress/agent-pkcs11.sh
4369a3
index 5205d906..5ca49be5 100644
4369a3
--- a/regress/agent-pkcs11.sh
4369a3
+++ b/regress/agent-pkcs11.sh
4369a3
@@ -29,6 +29,13 @@ fi
4369a3
 
4369a3
 test -f "$TEST_SSH_PKCS11" || fatal "$TEST_SSH_PKCS11 does not exist"
4369a3
 
4369a3
+# requires ssh-agent built with correct path to ssh-pkcs11-helper
4369a3
+# otherwise it fails to start the helper
4369a3
+strings ${TEST_SSH_SSHAGENT} | grep "$TEST_SSH_SSHPKCS11HELPER"
4369a3
+if [ $? -ne 0 ]; then
4369a3
+	fatal "Needs to reconfigure with --libexecdir=\`pwd\` or so"
4369a3
+fi
4369a3
+
4369a3
 # setup environment for softhsm2 token
4369a3
 DIR=$OBJ/SOFTHSM
4369a3
 rm -rf $DIR
4369a3
@@ -113,7 +120,7 @@ else
4369a3
 	done
4369a3
 
4369a3
 	trace "remove pkcs11 keys"
4369a3
-	echo ${TEST_SSH_PIN} | notty ${SSHADD} -e ${TEST_SSH_PKCS11} > /dev/null 2>&1
4369a3
+	${SSHADD} -e ${TEST_SSH_PKCS11} > /dev/null 2>&1
4369a3
 	r=$?
4369a3
 	if [ $r -ne 0 ]; then
4369a3
 		fail "ssh-add -e failed: exit code $r"
4369a3
diff --git a/regress/pkcs11.sh b/regress/pkcs11.sh
4369a3
new file mode 100644
4369a3
index 00000000..19fc8169
4369a3
--- /dev/null
4369a3
+++ b/regress/pkcs11.sh
4369a3
@@ -0,0 +1,352 @@
4369a3
+#
4369a3
+#  Copyright (c) 2017 Red Hat
4369a3
+#
4369a3
+#  Authors: Jakub Jelen <jjelen@redhat.com>
4369a3
+#
4369a3
+#  Permission to use, copy, modify, and distribute this software for any
4369a3
+#  purpose with or without fee is hereby granted, provided that the above
4369a3
+#  copyright notice and this permission notice appear in all copies.
4369a3
+#
4369a3
+#  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
4369a3
+#  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
4369a3
+#  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
4369a3
+#  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
4369a3
+#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
4369a3
+#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
4369a3
+#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4369a3
+
4369a3
+tid="pkcs11 tests with soft token"
4369a3
+
4369a3
+try_token_libs() {
4369a3
+	for _lib in "$@" ; do
4369a3
+		if test -f "$_lib" ; then
4369a3
+			verbose "Using token library $_lib"
4369a3
+			TEST_SSH_PKCS11="$_lib"
4369a3
+			return
4369a3
+		fi
4369a3
+	done
4369a3
+	echo "skipped: Unable to find PKCS#11 token library"
4369a3
+	exit 0
4369a3
+}
4369a3
+
4369a3
+try_token_libs \
4369a3
+	/usr/local/lib/softhsm/libsofthsm2.so \
4369a3
+	/usr/lib64/pkcs11/libsofthsm2.so \
4369a3
+	/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so
4369a3
+
4369a3
+TEST_SSH_PIN=1234
4369a3
+TEST_SSH_SOPIN=12345678
4369a3
+if [ "x$TEST_SSH_SSHPKCS11HELPER" != "x" ]; then
4369a3
+	SSH_PKCS11_HELPER="${TEST_SSH_SSHPKCS11HELPER}"
4369a3
+	export SSH_PKCS11_HELPER
4369a3
+fi
4369a3
+
4369a3
+test -f "$TEST_SSH_PKCS11" || fatal "$TEST_SSH_PKCS11 does not exist"
4369a3
+
4369a3
+# requires ssh-agent built with correct path to ssh-pkcs11-helper
4369a3
+# otherwise it fails to start the helper
4369a3
+strings ${TEST_SSH_SSHAGENT} | grep "$TEST_SSH_SSHPKCS11HELPER"
4369a3
+if [ $? -ne 0 ]; then
4369a3
+	fatal "Needs to reconfigure with --libexecdir=\`pwd\` or so"
4369a3
+fi
4369a3
+
4369a3
+# setup environment for softhsm token
4369a3
+DIR=$OBJ/SOFTHSM
4369a3
+rm -rf $DIR
4369a3
+TOKEN=$DIR/tokendir
4369a3
+mkdir -p $TOKEN
4369a3
+SOFTHSM2_CONF=$DIR/softhsm2.conf
4369a3
+export SOFTHSM2_CONF
4369a3
+cat > $SOFTHSM2_CONF << EOF
4369a3
+# SoftHSM v2 configuration file
4369a3
+directories.tokendir = ${TOKEN}
4369a3
+objectstore.backend = file
4369a3
+# ERROR, WARNING, INFO, DEBUG
4369a3
+log.level = DEBUG
4369a3
+# If CKF_REMOVABLE_DEVICE flag should be set
4369a3
+slots.removable = false
4369a3
+EOF
4369a3
+out=$(softhsm2-util --init-token --free --label token-slot-0 --pin "$TEST_SSH_PIN" --so-pin "$TEST_SSH_SOPIN")
4369a3
+slot=$(echo -- $out | sed 's/.* //')
4369a3
+
4369a3
+# prevent ssh-agent from calling ssh-askpass
4369a3
+SSH_ASKPASS=/usr/bin/true
4369a3
+export SSH_ASKPASS
4369a3
+unset DISPLAY
4369a3
+# We need interactive access to test PKCS# since it prompts for PIN
4369a3
+sed -i 's/.*BatchMode.*//g' $OBJ/ssh_proxy
4369a3
+
4369a3
+# start command w/o tty, so ssh accepts pin from stdin (from agent-pkcs11.sh)
4369a3
+notty() {
4369a3
+	perl -e 'use POSIX; POSIX::setsid();
4369a3
+	    if (fork) { wait; exit($? >> 8); } else { exec(@ARGV) }' "$@"
4369a3
+}
4369a3
+
4369a3
+trace "generating keys"
4369a3
+ID1="02"
4369a3
+ID2="04"
4369a3
+RSA=${DIR}/RSA
4369a3
+EC=${DIR}/EC
4369a3
+openssl genpkey -algorithm rsa > $RSA
4369a3
+openssl pkcs8 -nocrypt -in $RSA |\
4369a3
+    softhsm2-util --slot "$slot" --label "SSH RSA Key $ID1" --id $ID1 \
4369a3
+	--pin "$TEST_SSH_PIN" --import /dev/stdin
4369a3
+openssl genpkey \
4369a3
+    -genparam \
4369a3
+    -algorithm ec \
4369a3
+    -pkeyopt ec_paramgen_curve:prime256v1 |\
4369a3
+    openssl genpkey \
4369a3
+    -paramfile /dev/stdin > $EC
4369a3
+openssl pkcs8 -nocrypt -in $EC |\
4369a3
+    softhsm2-util --slot "$slot" --label "SSH ECDSA Key $ID2" --id $ID2 \
4369a3
+	--pin "$TEST_SSH_PIN" --import /dev/stdin
4369a3
+
4369a3
+trace "List the keys in the ssh-keygen with PKCS#11 URIs"
4369a3
+${SSHKEYGEN} -D ${TEST_SSH_PKCS11} > $OBJ/token_keys
4369a3
+if [ $? -ne 0 ]; then
4369a3
+	fail "keygen fails to enumerate keys on PKCS#11 token"
4369a3
+fi
4369a3
+grep "pkcs11:" $OBJ/token_keys > /dev/null
4369a3
+if [ $? -ne 0 ]; then
4369a3
+	fail "The keys from ssh-keygen do not contain PKCS#11 URI as a comment"
4369a3
+fi
4369a3
+tail -n 1 $OBJ/token_keys > $OBJ/authorized_keys_$USER
4369a3
+
4369a3
+trace "Simple connect with ssh (without PKCS#11 URI)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -I ${TEST_SSH_PKCS11} \
4369a3
+    -F $OBJ/ssh_proxy somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with pkcs11 failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "Connect with PKCS#11 URI"
4369a3
+trace "  (second key should succeed)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+    -i "pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (first key should fail)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+     -i "pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI succeeded (should fail)"
4369a3
+fi
4369a3
+
4369a3
+trace "Connect with PKCS#11 URI including PIN should not prompt"
4369a3
+trace "  (second key should succeed)"
4369a3
+${SSH} -F $OBJ/ssh_proxy -i \
4369a3
+    "pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}&pin-value=${TEST_SSH_PIN}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (first key should fail)"
4369a3
+${SSH} -F $OBJ/ssh_proxy -i \
4369a3
+    "pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}&pin-value=${TEST_SSH_PIN}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI succeeded (should fail)"
4369a3
+fi
4369a3
+
4369a3
+trace "Connect with various filtering options in PKCS#11 URI"
4369a3
+trace "  (by object label, second key should succeed)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+    -i "pkcs11:object=SSH%20RSA%20Key%202?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (by object label, first key should fail)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+     -i "pkcs11:object=SSH%20RSA%20Key?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI succeeded (should fail)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (by token label, second key should succeed)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+    -i "pkcs11:id=${ID2};token=SoftToken%20(token)?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (by wrong token label, should fail)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+     -i "pkcs11:token=SoftToken?module-path=${TEST_SSH_PKCS11}" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI succeeded (should fail)"
4369a3
+fi
4369a3
+
4369a3
+
4369a3
+
4369a3
+
4369a3
+trace "Test PKCS#11 URI specification in configuration files"
4369a3
+echo "IdentityFile \"pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}\"" \
4369a3
+    >> $OBJ/ssh_proxy
4369a3
+trace "  (second key should succeed)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI in config failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "  (first key should fail)"
4369a3
+head -n 1 $OBJ/token_keys > $OBJ/authorized_keys_$USER
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI in config succeeded (should fail)"
4369a3
+fi
4369a3
+sed -i -e "/IdentityFile/d" $OBJ/ssh_proxy
4369a3
+
4369a3
+trace "Test PKCS#11 URI specification in configuration files with bogus spaces"
4369a3
+echo "IdentityFile \"    pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}    \"" \
4369a3
+    >> $OBJ/ssh_proxy
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI with bogus spaces in config failed" \
4369a3
+	    "(exit code $r)"
4369a3
+fi
4369a3
+sed -i -e "/IdentityFile/d" $OBJ/ssh_proxy
4369a3
+
4369a3
+
4369a3
+trace "Combination of PKCS11Provider and PKCS11URI on commandline"
4369a3
+trace "  (first key should succeed)"
4369a3
+echo ${TEST_SSH_PIN} | notty ${SSH} -F $OBJ/ssh_proxy \
4369a3
+    -i "pkcs11:id=${ID1}" -I ${TEST_SSH_PKCS11} somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -ne 5 ]; then
4369a3
+	fail "ssh connect with PKCS#11 URI and provider combination" \
4369a3
+	    "failed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+trace "Regress: Missing provider in PKCS11URI option"
4369a3
+${SSH} -F $OBJ/ssh_proxy \
4369a3
+    -o IdentityFile=\"pkcs11:token=segfault\" somehost exit 5
4369a3
+r=$?
4369a3
+if [ $r -eq 139 ]; then
4369a3
+	fail "ssh connect with missing provider_id from configuration option" \
4369a3
+	    "crashed (exit code $r)"
4369a3
+fi
4369a3
+
4369a3
+
4369a3
+trace "SSH Agent can work with PKCS#11 URI"
4369a3
+trace "start the agent"
4369a3
+eval `${SSHAGENT} -s -P "${OBJ}/*"` > /dev/null
4369a3
+
4369a3
+r=$?
4369a3
+if [ $r -ne 0 ]; then
4369a3
+	fail "could not start ssh-agent: exit code $r"
4369a3
+else
4369a3
+	trace "add whole provider to agent"
4369a3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
4369a3
+	    "pkcs11:?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add failed with whole provider: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " pkcs11 list via agent (all keys)"
4369a3
+	${SSHADD} -l > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add -l failed with whole provider: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " pkcs11 connect via agent (all keys)"
4369a3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+	r=$?
4369a3
+	if [ $r -ne 5 ]; then
4369a3
+		fail "ssh connect failed with whole provider (exit code $r)"
4369a3
+	fi
4369a3
+
4369a3
+	trace " remove pkcs11 keys (all keys)"
4369a3
+	${SSHADD} -d "pkcs11:?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add -d failed with whole provider: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace "add only first key to the agent"
4369a3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
4369a3
+	    "pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add failed with first key: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " pkcs11 connect via agent (first key)"
4369a3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+	r=$?
4369a3
+	if [ $r -ne 5 ]; then
4369a3
+		fail "ssh connect failed with first key (exit code $r)"
4369a3
+	fi
4369a3
+
4369a3
+	trace " remove first pkcs11 key"
4369a3
+	${SSHADD} -d "pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}" \
4369a3
+	    > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add -d failed with first key: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace "add only second key to the agent"
4369a3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
4369a3
+	    "pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add failed with second key: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " pkcs11 connect via agent (second key should fail)"
4369a3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+	r=$?
4369a3
+	if [ $r -eq 5 ]; then
4369a3
+		fail "ssh connect passed without key (should fail)"
4369a3
+	fi
4369a3
+
4369a3
+	trace "add also the first key to the agent"
4369a3
+	echo ${TEST_SSH_PIN} | notty ${SSHADD} \
4369a3
+	    "pkcs11:id=${ID1}?module-path=${TEST_SSH_PKCS11}" > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add failed with first key: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " remove second pkcs11 key"
4369a3
+	${SSHADD} -d "pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}" \
4369a3
+	    > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -ne 0 ]; then
4369a3
+		fail "ssh-add -d failed with second key: exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace " remove already-removed pkcs11 key should fail"
4369a3
+	${SSHADD} -d "pkcs11:id=${ID2}?module-path=${TEST_SSH_PKCS11}" \
4369a3
+	    > /dev/null 2>&1
4369a3
+	r=$?
4369a3
+	if [ $r -eq 0 ]; then
4369a3
+		fail "ssh-add -d passed with non-existing key (should fail)"
4369a3
+	fi
4369a3
+
4369a3
+	trace " pkcs11 connect via agent (the first key should be still usable)"
4369a3
+	${SSH} -F $OBJ/ssh_proxy somehost exit 5
4369a3
+	r=$?
4369a3
+	if [ $r -ne 5 ]; then
4369a3
+		fail "ssh connect failed with first key (after removing second): exit code $r"
4369a3
+	fi
4369a3
+
4369a3
+	trace "kill agent"
4369a3
+	${SSHAGENT} -k > /dev/null
4369a3
+fi
4369a3
diff --git a/regress/unittests/Makefile b/regress/unittests/Makefile
4369a3
index e464b085..a0e5a37c 100644
4369a3
--- a/regress/unittests/Makefile
4369a3
+++ b/regress/unittests/Makefile
4369a3
@@ -2,6 +2,6 @@
4369a3
 
4369a3
 REGRESS_FAIL_EARLY?=	yes
4369a3
 SUBDIR=	test_helper sshbuf sshkey bitmap kex hostkeys utf8 match conversion
4369a3
-SUBDIR+=authopt
4369a3
+SUBDIR+=pkcs11 authopt
4369a3
 
4369a3
 .include <bsd.subdir.mk>
4369a3
diff --git a/regress/unittests/pkcs11/tests.c b/regress/unittests/pkcs11/tests.c
4369a3
new file mode 100644
4369a3
index 00000000..b637cb13
4369a3
--- /dev/null
4369a3
+++ b/regress/unittests/pkcs11/tests.c
4369a3
@@ -0,0 +1,337 @@
4369a3
+/*
4369a3
+ * Copyright (c) 2017 Red Hat
4369a3
+ *
4369a3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
4369a3
+ *
4369a3
+ * Permission to use, copy, modify, and distribute this software for any
4369a3
+ * purpose with or without fee is hereby granted, provided that the above
4369a3
+ * copyright notice and this permission notice appear in all copies.
4369a3
+ *
4369a3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
4369a3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
4369a3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
4369a3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
4369a3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
4369a3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
4369a3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4369a3
+ */
4369a3
+
4369a3
+#include "includes.h"
4369a3
+
4369a3
+#include <locale.h>
4369a3
+#include <string.h>
4369a3
+
4369a3
+#include "../test_helper/test_helper.h"
4369a3
+
4369a3
+#include "sshbuf.h"
4369a3
+#include "ssh-pkcs11-uri.h"
4369a3
+
4369a3
+#define EMPTY_URI compose_uri(NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL)
4369a3
+
4369a3
+/* prototypes are not public -- specify them here internally for tests */
4369a3
+struct sshbuf *percent_encode(const char *, size_t, char *);
4369a3
+int percent_decode(char *, char **);
4369a3
+
4369a3
+void
4369a3
+compare_uri(struct pkcs11_uri *a, struct pkcs11_uri *b)
4369a3
+{
4369a3
+	ASSERT_PTR_NE(a, NULL);
4369a3
+	ASSERT_PTR_NE(b, NULL);
4369a3
+	ASSERT_SIZE_T_EQ(a->id_len, b->id_len);
4369a3
+	ASSERT_MEM_EQ(a->id, b->id, a->id_len);
4369a3
+	if (b->object != NULL)
4369a3
+		ASSERT_STRING_EQ(a->object, b->object);
4369a3
+	else /* both should be null */
4369a3
+		ASSERT_PTR_EQ(a->object, b->object);
4369a3
+	if (b->module_path != NULL)
4369a3
+		ASSERT_STRING_EQ(a->module_path, b->module_path);
4369a3
+	else /* both should be null */
4369a3
+		ASSERT_PTR_EQ(a->module_path, b->module_path);
4369a3
+	if (b->token != NULL)
4369a3
+		ASSERT_STRING_EQ(a->token, b->token);
4369a3
+	else /* both should be null */
4369a3
+		ASSERT_PTR_EQ(a->token, b->token);
4369a3
+	if (b->manuf != NULL)
4369a3
+		ASSERT_STRING_EQ(a->manuf, b->manuf);
4369a3
+	else /* both should be null */
4369a3
+		ASSERT_PTR_EQ(a->manuf, b->manuf);
4369a3
+	if (b->lib_manuf != NULL)
4369a3
+		ASSERT_STRING_EQ(a->lib_manuf, b->lib_manuf);
4369a3
+	else /* both should be null */
4369a3
+		ASSERT_PTR_EQ(a->lib_manuf, b->lib_manuf);
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+check_parse_rv(char *uri, struct pkcs11_uri *expect, int expect_rv)
4369a3
+{
4369a3
+	char *buf = NULL, *str;
4369a3
+	struct pkcs11_uri *pkcs11uri = NULL;
4369a3
+	int rv;
4369a3
+
4369a3
+	if (expect_rv == 0)
4369a3
+		str = "Valid";
4369a3
+	else
4369a3
+		str = "Invalid";
4369a3
+	asprintf(&buf, "%s PKCS#11 URI parsing: %s", str, uri);
4369a3
+	TEST_START(buf);
4369a3
+	free(buf);
4369a3
+	pkcs11uri = pkcs11_uri_init();
4369a3
+	rv = pkcs11_uri_parse(uri, pkcs11uri);
4369a3
+	ASSERT_INT_EQ(rv, expect_rv);
4369a3
+	if (rv == 0) /* in case of failure result is undefined */
4369a3
+		compare_uri(pkcs11uri, expect);
4369a3
+	pkcs11_uri_cleanup(pkcs11uri);
4369a3
+	free(expect);
4369a3
+	TEST_DONE();
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+check_parse(char *uri, struct pkcs11_uri *expect)
4369a3
+{
4369a3
+	check_parse_rv(uri, expect, 0);
4369a3
+}
4369a3
+
4369a3
+struct pkcs11_uri *
4369a3
+compose_uri(unsigned char *id, size_t id_len, char *token, char *lib_manuf,
4369a3
+    char *manuf, char *module_path, char *object, char *pin)
4369a3
+{
4369a3
+	struct pkcs11_uri *uri = pkcs11_uri_init();
4369a3
+	if (id_len > 0) {
4369a3
+		uri->id_len = id_len;
4369a3
+		uri->id = id;
4369a3
+	}
4369a3
+	uri->module_path = module_path;
4369a3
+	uri->token = token;
4369a3
+	uri->lib_manuf = lib_manuf;
4369a3
+	uri->manuf = manuf;
4369a3
+	uri->object = object;
4369a3
+	uri->pin = pin;
4369a3
+	return uri;
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_parse_valid(void)
4369a3
+{
4369a3
+	/* path arguments */
4369a3
+	check_parse("pkcs11:id=%01",
4369a3
+	    compose_uri("\x01", 1, NULL, NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_parse("pkcs11:id=%00%01",
4369a3
+	    compose_uri("\x00\x01", 2, NULL, NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_parse("pkcs11:token=SSH%20Keys",
4369a3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_parse("pkcs11:library-manufacturer=OpenSC",
4369a3
+	    compose_uri(NULL, 0, NULL, "OpenSC", NULL, NULL, NULL, NULL));
4369a3
+	check_parse("pkcs11:manufacturer=piv_II",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, NULL, NULL));
4369a3
+	check_parse("pkcs11:object=SIGN%20Key",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, "SIGN Key", NULL));
4369a3
+	/* query arguments */
4369a3
+	check_parse("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
4369a3
+	check_parse("pkcs11:?pin-value=123456",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, NULL, "123456"));
4369a3
+
4369a3
+	/* combinations */
4369a3
+	/* ID SHOULD be percent encoded */
4369a3
+	check_parse("pkcs11:token=SSH%20Key;id=0",
4369a3
+	    compose_uri("0", 1, "SSH Key", NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_parse(
4369a3
+	    "pkcs11:manufacturer=CAC?module-path=/usr/lib64/p11-kit-proxy.so",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, "CAC",
4369a3
+	    "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
4369a3
+	check_parse(
4369a3
+	    "pkcs11:object=RSA%20Key?module-path=/usr/lib64/pkcs11/opencryptoki.so",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL,
4369a3
+	    "/usr/lib64/pkcs11/opencryptoki.so", "RSA Key", NULL));
4369a3
+	check_parse("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so&pin-value=123456",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, "123456"));
4369a3
+
4369a3
+	/* empty path component matches everything */
4369a3
+	check_parse("pkcs11:", EMPTY_URI);
4369a3
+
4369a3
+	/* empty string is a valid to match against (and different from NULL) */
4369a3
+	check_parse("pkcs11:token=",
4369a3
+	    compose_uri(NULL, 0, "", NULL, NULL, NULL, NULL, NULL));
4369a3
+	/* Percent character needs to be percent-encoded */
4369a3
+	check_parse("pkcs11:token=%25",
4369a3
+	     compose_uri(NULL, 0, "%", NULL, NULL, NULL, NULL, NULL));
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_parse_invalid(void)
4369a3
+{
4369a3
+	/* Invalid percent encoding */
4369a3
+	check_parse_rv("pkcs11:id=%0", EMPTY_URI, -1);
4369a3
+	/* Invalid percent encoding */
4369a3
+	check_parse_rv("pkcs11:id=%ZZ", EMPTY_URI, -1);
4369a3
+	/* Space MUST be percent encoded -- XXX not enforced yet */
4369a3
+	check_parse("pkcs11:token=SSH Keys",
4369a3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
4369a3
+	/* MUST NOT contain duplicate attributes of the same name */
4369a3
+	check_parse_rv("pkcs11:id=%01;id=%02", EMPTY_URI, -1);
4369a3
+	/* MUST NOT contain duplicate attributes of the same name */
4369a3
+	check_parse_rv("pkcs11:?pin-value=111111&pin-value=123456", EMPTY_URI, -1);
4369a3
+	/* Unrecognized attribute in path are ignored with log message */
4369a3
+	check_parse("pkcs11:key_name=SSH", EMPTY_URI);
4369a3
+	/* Unrecognized attribute in query SHOULD be ignored */
4369a3
+	check_parse("pkcs11:?key_name=SSH", EMPTY_URI);
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+check_gen(char *expect, struct pkcs11_uri *uri)
4369a3
+{
4369a3
+	char *buf = NULL, *uri_str;
4369a3
+
4369a3
+	asprintf(&buf, "Valid PKCS#11 URI generation: %s", expect);
4369a3
+	TEST_START(buf);
4369a3
+	free(buf);
4369a3
+	uri_str = pkcs11_uri_get(uri);
4369a3
+	ASSERT_PTR_NE(uri_str, NULL);
4369a3
+	ASSERT_STRING_EQ(uri_str, expect);
4369a3
+	free(uri_str);
4369a3
+	TEST_DONE();
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_generate_valid(void)
4369a3
+{
4369a3
+	/* path arguments */
4369a3
+	check_gen("pkcs11:id=%01",
4369a3
+	    compose_uri("\x01", 1, NULL, NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_gen("pkcs11:id=%00%01",
4369a3
+	    compose_uri("\x00\x01", 2, NULL, NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_gen("pkcs11:token=SSH%20Keys", /* space must be percent encoded */
4369a3
+	    compose_uri(NULL, 0, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
4369a3
+	/* library-manufacturer is not implmented now */
4369a3
+	/*check_gen("pkcs11:library-manufacturer=OpenSC",
4369a3
+	    compose_uri(NULL, 0, NULL, "OpenSC", NULL, NULL, NULL, NULL));*/
4369a3
+	check_gen("pkcs11:manufacturer=piv_II",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, NULL, NULL));
4369a3
+	check_gen("pkcs11:object=RSA%20Key",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, NULL, "RSA Key", NULL));
4369a3
+	/* query arguments */
4369a3
+	check_gen("pkcs11:?module-path=/usr/lib64/p11-kit-proxy.so",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
4369a3
+
4369a3
+	/* combinations */
4369a3
+	check_gen("pkcs11:id=%02;token=SSH%20Keys",
4369a3
+	    compose_uri("\x02", 1, "SSH Keys", NULL, NULL, NULL, NULL, NULL));
4369a3
+	check_gen("pkcs11:id=%EE%02?module-path=/usr/lib64/p11-kit-proxy.so",
4369a3
+	    compose_uri("\xEE\x02", 2, NULL, NULL, NULL, "/usr/lib64/p11-kit-proxy.so", NULL, NULL));
4369a3
+	check_gen("pkcs11:object=Encryption%20Key;manufacturer=piv_II",
4369a3
+	    compose_uri(NULL, 0, NULL, NULL, "piv_II", NULL, "Encryption Key", NULL));
4369a3
+
4369a3
+	/* empty path component matches everything */
4369a3
+	check_gen("pkcs11:", EMPTY_URI);
4369a3
+
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+check_encode(char *source, size_t len, char *whitelist, char *expect)
4369a3
+{
4369a3
+	char *buf = NULL;
4369a3
+	struct sshbuf *b;
4369a3
+
4369a3
+	asprintf(&buf, "percent_encode: expected %s", expect);
4369a3
+	TEST_START(buf);
4369a3
+	free(buf);
4369a3
+
4369a3
+	b = percent_encode(source, len, whitelist);
4369a3
+	ASSERT_STRING_EQ(sshbuf_ptr(b), expect);
4369a3
+	sshbuf_free(b);
4369a3
+	TEST_DONE();
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_percent_encode_multibyte(void)
4369a3
+{
4369a3
+	/* SHOULD be encoded as octets according to the UTF-8 character encoding */
4369a3
+
4369a3
+	/* multi-byte characters are "for free" */
4369a3
+	check_encode("$", 1, "", "%24");
4369a3
+	check_encode("¢", 2, "", "%C2%A2");
4369a3
+	check_encode("€", 3, "", "%E2%82%AC");
4369a3
+	check_encode("𐍈", 4, "", "%F0%90%8D%88");
4369a3
+
4369a3
+	/* CK_UTF8CHAR is unsigned char (1 byte) */
4369a3
+	/* labels SHOULD be normalized to NFC [UAX15] */
4369a3
+
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_percent_encode(void)
4369a3
+{
4369a3
+	/* Without whitelist encodes everything (for CKA_ID) */
4369a3
+	check_encode("A*", 2, "", "%41%2A");
4369a3
+	check_encode("\x00", 1, "", "%00");
4369a3
+	check_encode("\x7F", 1, "", "%7F");
4369a3
+	check_encode("\x80", 1, "", "%80");
4369a3
+	check_encode("\xff", 1, "", "%FF");
4369a3
+
4369a3
+	/* Default whitelist encodes anything but safe letters */
4369a3
+	check_encode("test" "\x00" "0alpha", 11, PKCS11_URI_WHITELIST,
4369a3
+	    "test%000alpha");
4369a3
+	check_encode(" ", 1, PKCS11_URI_WHITELIST,
4369a3
+	    "%20"); /* Space MUST be percent encoded */
4369a3
+	check_encode("/", 1, PKCS11_URI_WHITELIST,
4369a3
+	    "%2F"); /* '/' delimiter MUST be percent encoded (in the path) */
4369a3
+	check_encode("?", 1, PKCS11_URI_WHITELIST,
4369a3
+	    "%3F"); /* delimiter '?' MUST be percent encoded (in the path) */
4369a3
+	check_encode("#", 1, PKCS11_URI_WHITELIST,
4369a3
+	    "%23"); /* '#' MUST be always percent encoded */
4369a3
+	check_encode("key=value;separator?query&#anch", 35, PKCS11_URI_WHITELIST,
4369a3
+	    "key%3Dvalue%3Bseparator%3Fquery%26amp%3B%23anch");
4369a3
+
4369a3
+	/* Components in query can have '/' unencoded (useful for paths) */
4369a3
+	check_encode("/path/to.file", 13, PKCS11_URI_WHITELIST "/",
4369a3
+	    "/path/to.file");
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+check_decode(char *source, char *expect, int expect_len)
4369a3
+{
4369a3
+	char *buf = NULL, *out = NULL;
4369a3
+	int rv;
4369a3
+
4369a3
+	asprintf(&buf, "percent_decode: %s", source);
4369a3
+	TEST_START(buf);
4369a3
+	free(buf);
4369a3
+
4369a3
+	rv = percent_decode(source, &out;;
4369a3
+	ASSERT_INT_EQ(rv, expect_len);
4369a3
+	if (rv >= 0)
4369a3
+		ASSERT_MEM_EQ(out, expect, expect_len);
4369a3
+	free(out);
4369a3
+	TEST_DONE();
4369a3
+}
4369a3
+
4369a3
+static void
4369a3
+test_percent_decode(void)
4369a3
+{
4369a3
+	/* simple valid cases */
4369a3
+	check_decode("%00", "\x00", 1);
4369a3
+	check_decode("%FF", "\xFF", 1);
4369a3
+
4369a3
+	/* normal strings shold be kept intact */
4369a3
+	check_decode("strings are left", "strings are left", 16);
4369a3
+	check_decode("10%25 of trees", "10% of trees", 12);
4369a3
+
4369a3
+	/* make sure no more than 2 bytes are parsed */
4369a3
+	check_decode("%222", "\x22" "2", 2);
4369a3
+
4369a3
+	/* invalid expects failure */
4369a3
+	check_decode("%0", "", -1);
4369a3
+	check_decode("%Z", "", -1);
4369a3
+	check_decode("%FG", "", -1);
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+tests(void)
4369a3
+{
4369a3
+	test_percent_encode();
4369a3
+	test_percent_encode_multibyte();
4369a3
+	test_percent_decode();
4369a3
+	test_parse_valid();
4369a3
+	test_parse_invalid();
4369a3
+	test_generate_valid();
4369a3
+}
4369a3
diff --git a/ssh-add.c b/ssh-add.c
4369a3
index ac9c808d..f039e00e 100644
4369a3
--- a/ssh-add.c
4369a3
+++ b/ssh-add.c
4369a3
@@ -64,6 +64,7 @@
4369a3
 #include "misc.h"
4369a3
 #include "ssherr.h"
4369a3
 #include "digest.h"
4369a3
+#include "ssh-pkcs11-uri.h"
4369a3
 
4369a3
 /* argv0 */
4369a3
 extern char *__progname;
4369a3
@@ -188,6 +189,24 @@ delete_all(int agent_fd, int qflag)
4369a3
 	return ret;
4369a3
 }
4369a3
 
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+static int update_card(int, int, const char *, int);
4369a3
+
4369a3
+int
4369a3
+update_pkcs11_uri(int agent_fd, int adding, const char *pkcs11_uri, int qflag)
4369a3
+{
4369a3
+	struct pkcs11_uri *uri;
4369a3
+
4369a3
+	/* dry-run parse to make sure the URI is valid and to report errors */
4369a3
+	uri = pkcs11_uri_init();
4369a3
+	if (pkcs11_uri_parse((char *) pkcs11_uri, uri) != 0)
4369a3
+		fatal("Failed to parse PKCS#11 URI");
4369a3
+	pkcs11_uri_cleanup(uri);
4369a3
+
4369a3
+	return update_card(agent_fd, adding, pkcs11_uri, qflag);
4369a3
+}
4369a3
+#endif
4369a3
+
4369a3
 static int
4369a3
 add_file(int agent_fd, const char *filename, int key_only, int qflag)
4369a3
 {
4369a3
@@ -529,6 +548,13 @@ lock_agent(int agent_fd, int lock)
4369a3
 static int
4369a3
 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag)
4369a3
 {
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+	if (strlen(file) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+	    strncmp(file, PKCS11_URI_SCHEME,
4369a3
+	    strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+		return update_pkcs11_uri(agent_fd, !deleting, file, qflag);
4369a3
+	}
4369a3
+#endif
4369a3
 	if (deleting) {
4369a3
 		if (delete_file(agent_fd, file, key_only, qflag) == -1)
4369a3
 			return -1;
4369a3
diff --git a/ssh-agent.c b/ssh-agent.c
4369a3
index d06ecfd9..9c1b328f 100644
4369a3
--- a/ssh-agent.c
4369a3
+++ b/ssh-agent.c
4369a3
@@ -548,10 +548,72 @@ no_identities(SocketEntry *e)
4369a3
 }
4369a3
 
4369a3
 #ifdef ENABLE_PKCS11
4369a3
+static char *
4369a3
+sanitize_pkcs11_provider(const char *provider)
4369a3
+{
4369a3
+	struct pkcs11_uri *uri = NULL;
4369a3
+	char *sane_uri, *module_path = NULL; /* default path */
4369a3
+	char canonical_provider[PATH_MAX];
4369a3
+
4369a3
+	if (provider == NULL)
4369a3
+		return NULL;
4369a3
+
4369a3
+	if (strlen(provider) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+	    strncmp(provider, PKCS11_URI_SCHEME,
4369a3
+	    strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+		/* PKCS#11 URI */
4369a3
+		uri = pkcs11_uri_init();
4369a3
+		if (uri == NULL) {
4369a3
+			error("Failed to init PCKS#11 URI");
4369a3
+			return NULL;
4369a3
+		}
4369a3
+
4369a3
+		if (pkcs11_uri_parse(provider, uri) != 0) {
4369a3
+			error("Failed to parse PKCS#11 URI");
4369a3
+			return NULL;
4369a3
+		}
4369a3
+		/* validate also provider from URI */
4369a3
+		if (uri->module_path)
4369a3
+			module_path = strdup(uri->module_path);
4369a3
+	} else
4369a3
+		module_path = strdup(provider); /* simple path */
4369a3
+
4369a3
+	if (module_path != NULL) { /* do not validate default NULL path in URI */
4369a3
+		if (realpath(module_path, canonical_provider) == NULL) {
4369a3
+			verbose("failed PKCS#11 provider \"%.100s\": realpath: %s",
4369a3
+			    module_path, strerror(errno));
4369a3
+			free(module_path);
4369a3
+			pkcs11_uri_cleanup(uri);
4369a3
+			return NULL;
4369a3
+		}
4369a3
+		free(module_path);
4369a3
+		if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
4369a3
+			verbose("refusing PKCS#11 provider \"%.100s\": "
4369a3
+			    "not whitelisted", canonical_provider);
4369a3
+			pkcs11_uri_cleanup(uri);
4369a3
+			return NULL;
4369a3
+		}
4369a3
+
4369a3
+		/* copy verified and sanitized provider path back to the uri */
4369a3
+		if (uri) {
4369a3
+			free(uri->module_path);
4369a3
+			uri->module_path = xstrdup(canonical_provider);
4369a3
+		}
4369a3
+	}
4369a3
+
4369a3
+	if (uri) {
4369a3
+		sane_uri = pkcs11_uri_get(uri);
4369a3
+		pkcs11_uri_cleanup(uri);
4369a3
+		return sane_uri;
4369a3
+	} else {
4369a3
+		return xstrdup(canonical_provider); /* simple path */
4369a3
+	}
4369a3
+}
4369a3
+
4369a3
 static void
4369a3
 process_add_smartcard_key(SocketEntry *e)
4369a3
 {
4369a3
-	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
4369a3
+	char *provider = NULL, *pin = NULL, *sane_uri = NULL;
4369a3
 	int r, i, count = 0, success = 0, confirm = 0;
4369a3
 	u_int seconds;
4369a3
 	time_t death = 0;
4369a3
@@ -587,28 +649,23 @@ process_add_smartcard_key(SocketEntry *e)
4369a3
 			goto send;
4369a3
 		}
4369a3
 	}
4369a3
-	if (realpath(provider, canonical_provider) == NULL) {
4369a3
-		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
4369a3
-		    provider, strerror(errno));
4369a3
-		goto send;
4369a3
-	}
4369a3
-	if (match_pattern_list(canonical_provider, pkcs11_whitelist, 0) != 1) {
4369a3
-		verbose("refusing PKCS#11 add of \"%.100s\": "
4369a3
-		    "provider not whitelisted", canonical_provider);
4369a3
+
4369a3
+	sane_uri = sanitize_pkcs11_provider(provider);
4369a3
+	if (sane_uri == NULL)
4369a3
 		goto send;
4369a3
-	}
4369a3
-	debug("%s: add %.100s", __func__, canonical_provider);
4369a3
+
4369a3
 	if (lifetime && !death)
4369a3
 		death = monotime() + lifetime;
4369a3
 
4369a3
-	count = pkcs11_add_provider(canonical_provider, pin, &keys);
4369a3
+	debug("%s: add %.100s", __func__, sane_uri);
4369a3
+	count = pkcs11_add_provider(sane_uri, pin, &keys);
4369a3
 	for (i = 0; i < count; i++) {
4369a3
 		k = keys[i];
4369a3
 		if (lookup_identity(k) == NULL) {
4369a3
 			id = xcalloc(1, sizeof(Identity));
4369a3
 			id->key = k;
4369a3
-			id->provider = xstrdup(canonical_provider);
4369a3
-			id->comment = xstrdup(canonical_provider); /* XXX */
4369a3
+			id->provider = xstrdup(sane_uri);
4369a3
+			id->comment = xstrdup(sane_uri);
4369a3
 			id->death = death;
4369a3
 			id->confirm = confirm;
4369a3
 			TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
4369a3
@@ -622,6 +679,7 @@ process_add_smartcard_key(SocketEntry *e)
4369a3
 send:
4369a3
 	free(pin);
4369a3
 	free(provider);
4369a3
+	free(sane_uri);
4369a3
 	free(keys);
4369a3
 	send_status(e, success);
4369a3
 }
4369a3
@@ -629,7 +687,7 @@ send:
4369a3
 static void
4369a3
 process_remove_smartcard_key(SocketEntry *e)
4369a3
 {
4369a3
-	char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
4369a3
+	char *provider = NULL, *pin = NULL, *sane_uri = NULL;
4369a3
 	int r, success = 0;
4369a3
 	Identity *id, *nxt;
4369a3
 
4369a3
@@ -640,30 +698,29 @@ process_remove_smartcard_key(SocketEntry *e)
4369a3
 	}
4369a3
 	free(pin);
4369a3
 
4369a3
-	if (realpath(provider, canonical_provider) == NULL) {
4369a3
-		verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
4369a3
-		    provider, strerror(errno));
4369a3
+	sane_uri = sanitize_pkcs11_provider(provider);
4369a3
+	if (sane_uri == NULL)
4369a3
 		goto send;
4369a3
-	}
4369a3
 
4369a3
-	debug("%s: remove %.100s", __func__, canonical_provider);
4369a3
+	debug("%s: remove %.100s", __func__, sane_uri);
4369a3
 	for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
4369a3
 		nxt = TAILQ_NEXT(id, next);
4369a3
 		/* Skip file--based keys */
4369a3
 		if (id->provider == NULL)
4369a3
 			continue;
4369a3
-		if (!strcmp(canonical_provider, id->provider)) {
4369a3
+		if (!strcmp(sane_uri, id->provider)) {
4369a3
 			TAILQ_REMOVE(&idtab->idlist, id, next);
4369a3
 			free_identity(id);
4369a3
 			idtab->nentries--;
4369a3
 		}
4369a3
 	}
4369a3
-	if (pkcs11_del_provider(canonical_provider) == 0)
4369a3
+	if (pkcs11_del_provider(sane_uri) == 0)
4369a3
 		success = 1;
4369a3
 	else
4369a3
 		error("%s: pkcs11_del_provider failed", __func__);
4369a3
 send:
4369a3
 	free(provider);
4369a3
+	free(sane_uri);
4369a3
 	send_status(e, success);
4369a3
 }
4369a3
 #endif /* ENABLE_PKCS11 */
4369a3
diff --git a/ssh-keygen.c b/ssh-keygen.c
4369a3
index 3898b281..91c43b14 100644
4369a3
--- a/ssh-keygen.c
4369a3
+++ b/ssh-keygen.c
4369a3
@@ -798,6 +798,7 @@ do_download(struct passwd *pw)
4369a3
 			free(fp);
4369a3
 		} else {
4369a3
 			(void) sshkey_write(keys[i], stdout); /* XXX check */
4369a3
+			(void) pkcs11_uri_write(keys[i], stdout);
4369a3
 			fprintf(stdout, "\n");
4369a3
 		}
4369a3
 		sshkey_free(keys[i]);
4369a3
diff --git a/ssh-pkcs11-client.c b/ssh-pkcs11-client.c
4369a3
index e7860de8..7b2a9115 100644
4369a3
--- a/ssh-pkcs11-client.c
4369a3
+++ b/ssh-pkcs11-client.c
4369a3
@@ -321,6 +321,8 @@ pkcs11_add_provider(char *name, char *pin, struct sshkey ***keysp)
4369a3
 	u_int nkeys, i;
4369a3
 	struct sshbuf *msg;
4369a3
 
4369a3
+	debug("%s: called, name = %s", __func__, name);
4369a3
+
4369a3
 	if (fd < 0 && pkcs11_start_helper() < 0)
4369a3
 		return (-1);
4369a3
 
4369a3
@@ -338,6 +340,7 @@ pkcs11_add_provider(char *name, char *pin, struct sshkey ***keysp)
4369a3
 		if ((r = sshbuf_get_u32(msg, &nkeys)) != 0)
4369a3
 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
4369a3
 		*keysp = xcalloc(nkeys, sizeof(struct sshkey *));
4369a3
+		debug("%s: nkeys = %u", __func__, nkeys);
4369a3
 		for (i = 0; i < nkeys; i++) {
4369a3
 			/* XXX clean up properly instead of fatal() */
4369a3
 			if ((r = sshbuf_get_string(msg, &blob, &blen)) != 0 ||
4369a3
diff --git a/ssh-pkcs11-uri.c b/ssh-pkcs11-uri.c
4369a3
new file mode 100644
4369a3
index 00000000..e1a7b4e0
4369a3
--- /dev/null
4369a3
+++ b/ssh-pkcs11-uri.c
152122
@@ -0,0 +1,425 @@
4369a3
+/*
4369a3
+ * Copyright (c) 2017 Red Hat
4369a3
+ *
4369a3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
4369a3
+ *
4369a3
+ * Permission to use, copy, modify, and distribute this software for any
4369a3
+ * purpose with or without fee is hereby granted, provided that the above
4369a3
+ * copyright notice and this permission notice appear in all copies.
4369a3
+ *
4369a3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
4369a3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
4369a3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
4369a3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
4369a3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
4369a3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
4369a3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4369a3
+ */
4369a3
+
4369a3
+#include "includes.h"
4369a3
+
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+
4369a3
+#include <stdio.h>
4369a3
+#include <string.h>
4369a3
+
4369a3
+#include "sshkey.h"
4369a3
+#include "sshbuf.h"
4369a3
+#include "log.h"
4369a3
+
4369a3
+#define CRYPTOKI_COMPAT
4369a3
+#include "pkcs11.h"
4369a3
+
4369a3
+#include "ssh-pkcs11-uri.h"
4369a3
+
4369a3
+#define PKCS11_URI_PATH_SEPARATOR ";"
4369a3
+#define PKCS11_URI_QUERY_SEPARATOR "&"
4369a3
+#define PKCS11_URI_VALUE_SEPARATOR "="
4369a3
+#define PKCS11_URI_ID "id"
4369a3
+#define PKCS11_URI_TOKEN "token"
4369a3
+#define PKCS11_URI_OBJECT "object"
4369a3
+#define PKCS11_URI_LIB_MANUF "library-manufacturer"
4369a3
+#define PKCS11_URI_MANUF "manufacturer"
4369a3
+#define PKCS11_URI_MODULE_PATH "module-path"
4369a3
+#define PKCS11_URI_PIN_VALUE "pin-value"
4369a3
+
4369a3
+/* Keyword tokens. */
4369a3
+typedef enum {
4369a3
+	pId, pToken, pObject, pLibraryManufacturer, pManufacturer, pModulePath,
4369a3
+	pPinValue, pBadOption
4369a3
+} pkcs11uriOpCodes;
4369a3
+
4369a3
+/* Textual representation of the tokens. */
4369a3
+static struct {
4369a3
+	const char *name;
4369a3
+	pkcs11uriOpCodes opcode;
4369a3
+} keywords[] = {
4369a3
+	{ PKCS11_URI_ID, pId },
4369a3
+	{ PKCS11_URI_TOKEN, pToken },
4369a3
+	{ PKCS11_URI_OBJECT, pObject },
4369a3
+	{ PKCS11_URI_LIB_MANUF, pLibraryManufacturer },
4369a3
+	{ PKCS11_URI_MANUF, pManufacturer },
4369a3
+	{ PKCS11_URI_MODULE_PATH, pModulePath },
4369a3
+	{ PKCS11_URI_PIN_VALUE, pPinValue },
4369a3
+	{ NULL, pBadOption }
4369a3
+};
4369a3
+
4369a3
+static pkcs11uriOpCodes
4369a3
+parse_token(const char *cp)
4369a3
+{
4369a3
+	u_int i;
4369a3
+
4369a3
+	for (i = 0; keywords[i].name; i++)
4369a3
+		if (strncasecmp(cp, keywords[i].name,
4369a3
+		    strlen(keywords[i].name)) == 0)
4369a3
+			return keywords[i].opcode;
4369a3
+
4369a3
+	return pBadOption;
4369a3
+}
4369a3
+
4369a3
+int
4369a3
+percent_decode(char *data, char **outp)
4369a3
+{
4369a3
+	char tmp[3];
4369a3
+	char *out, *tmp_end;
4369a3
+	char *p = data;
4369a3
+	long value;
4369a3
+	size_t outlen = 0;
4369a3
+
4369a3
+	out = malloc(strlen(data)+1); /* upper bound */
4369a3
+	if (out == NULL)
4369a3
+		return -1;
4369a3
+	while (*p != '\0') {
4369a3
+		switch (*p) {
4369a3
+		case '%':
4369a3
+			p++;
4369a3
+			if (*p == '\0')
4369a3
+				goto fail;
4369a3
+			tmp[0] = *p++;
4369a3
+			if (*p == '\0')
4369a3
+				goto fail;
4369a3
+			tmp[1] = *p++;
4369a3
+			tmp[2] = '\0';
4369a3
+			tmp_end = NULL;
4369a3
+			value = strtol(tmp, &tmp_end, 16);
4369a3
+			if (tmp_end != tmp+2)
4369a3
+				goto fail;
4369a3
+			else
4369a3
+				out[outlen++] = (char) value;
4369a3
+			break;
4369a3
+		default:
4369a3
+			out[outlen++] = *p++;
4369a3
+			break;
4369a3
+		}
4369a3
+	}
4369a3
+
4369a3
+	/* zero terminate */
4369a3
+	out[outlen] = '\0';
4369a3
+	*outp = out;
4369a3
+	return outlen;
4369a3
+fail:
4369a3
+	free(out);
4369a3
+	return -1;
4369a3
+}
4369a3
+
4369a3
+struct sshbuf *
4369a3
+percent_encode(const char *data, size_t length, const char *whitelist)
4369a3
+{
4369a3
+	struct sshbuf *b = NULL;
4369a3
+	char tmp[4], *cp;
4369a3
+	size_t i;
4369a3
+
4369a3
+	if ((b = sshbuf_new()) == NULL)
4369a3
+		return NULL;
4369a3
+	for (i = 0; i < length; i++) {
4369a3
+		cp = strchr(whitelist, data[i]);
4369a3
+		/* if c is specified as '\0' pointer to terminator is returned !! */
4369a3
+		if (cp != NULL && *cp != '\0') {
4369a3
+			if (sshbuf_put(b, &data[i], 1) != 0)
4369a3
+				goto err;
4369a3
+		} else
4369a3
+			if (snprintf(tmp, 4, "%%%02X", (unsigned char) data[i]) < 3
4369a3
+			    || sshbuf_put(b, tmp, 3) != 0)
4369a3
+				goto err;
4369a3
+	}
4369a3
+	if (sshbuf_put(b, "\0", 1) == 0)
4369a3
+		return b;
4369a3
+err:
4369a3
+	sshbuf_free(b);
4369a3
+	return NULL;
4369a3
+}
4369a3
+
4369a3
+char *
4369a3
+pkcs11_uri_append(char *part, const char *separator, const char *key,
4369a3
+    struct sshbuf *value)
4369a3
+{
4369a3
+	char *new_part;
4369a3
+	size_t size = 0;
4369a3
+
4369a3
+	if (value == NULL)
4369a3
+		return NULL;
4369a3
+
4369a3
+	size = asprintf(&new_part,
4369a3
+	    "%s%s%s"  PKCS11_URI_VALUE_SEPARATOR "%s",
4369a3
+	    (part != NULL ? part : ""),
4369a3
+	    (part != NULL ? separator : ""),
4369a3
+	    key, sshbuf_ptr(value));
4369a3
+	sshbuf_free(value);
4369a3
+	free(part);
4369a3
+
4369a3
+	if (size <= 0)
4369a3
+		return NULL;
4369a3
+	return new_part;
4369a3
+}
4369a3
+
4369a3
+char *
4369a3
+pkcs11_uri_get(struct pkcs11_uri *uri)
4369a3
+{
4369a3
+	size_t size = 0;
4369a3
+	char *p = NULL, *path = NULL, *query = NULL;
4369a3
+
4369a3
+	/* compose a percent-encoded ID */
4369a3
+	if (uri->id_len > 0) {
4369a3
+		struct sshbuf *key_id = percent_encode(uri->id, uri->id_len, "");
4369a3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
4369a3
+		    PKCS11_URI_ID, key_id);
4369a3
+		if (path == NULL)
4369a3
+			goto err;
4369a3
+	}
4369a3
+
4369a3
+	/* Write object label */
4369a3
+	if (uri->object) {
4369a3
+		struct sshbuf *label = percent_encode(uri->object, strlen(uri->object),
4369a3
+		    PKCS11_URI_WHITELIST);
4369a3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
4369a3
+		    PKCS11_URI_OBJECT, label);
4369a3
+		if (path == NULL)
4369a3
+			goto err;
4369a3
+	}
4369a3
+
4369a3
+	/* Write token label */
4369a3
+	if (uri->token) {
4369a3
+		struct sshbuf *label = percent_encode(uri->token, strlen(uri->token),
4369a3
+		    PKCS11_URI_WHITELIST);
4369a3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
4369a3
+		    PKCS11_URI_TOKEN, label);
4369a3
+		if (path == NULL)
4369a3
+			goto err;
4369a3
+	}
4369a3
+
4369a3
+	/* Write manufacturer */
4369a3
+	if (uri->manuf) {
4369a3
+		struct sshbuf *manuf = percent_encode(uri->manuf,
4369a3
+		    strlen(uri->manuf), PKCS11_URI_WHITELIST);
4369a3
+		path = pkcs11_uri_append(path, PKCS11_URI_PATH_SEPARATOR,
4369a3
+		    PKCS11_URI_MANUF, manuf);
4369a3
+		if (path == NULL)
4369a3
+			goto err;
4369a3
+	}
4369a3
+
4369a3
+	/* Write module_path */
4369a3
+	if (uri->module_path) {
4369a3
+		struct sshbuf *module = percent_encode(uri->module_path,
4369a3
+		    strlen(uri->module_path), PKCS11_URI_WHITELIST "/");
4369a3
+		query = pkcs11_uri_append(query, PKCS11_URI_QUERY_SEPARATOR,
4369a3
+		    PKCS11_URI_MODULE_PATH, module);
4369a3
+		if (query == NULL)
4369a3
+			goto err;
4369a3
+	}
4369a3
+
4369a3
+	size = asprintf(&p, PKCS11_URI_SCHEME "%s%s%s",
4369a3
+	    path != NULL ? path : "",
4369a3
+	    query != NULL ? "?" : "",
4369a3
+	    query != NULL ? query : "");
4369a3
+err:
4369a3
+	free(query);
4369a3
+	free(path);
4369a3
+	if (size <= 0)
4369a3
+		return NULL;
4369a3
+	return p;
4369a3
+}
4369a3
+
4369a3
+struct pkcs11_uri *
4369a3
+pkcs11_uri_init()
4369a3
+{
4369a3
+	struct pkcs11_uri *d = calloc(1, sizeof(struct pkcs11_uri));
4369a3
+	return d;
4369a3
+}
4369a3
+
4369a3
+void
4369a3
+pkcs11_uri_cleanup(struct pkcs11_uri *pkcs11)
4369a3
+{
152122
+	if (pkcs11 == NULL) {
152122
+		return;
152122
+	}
152122
+
4369a3
+	free(pkcs11->id);
4369a3
+	free(pkcs11->module_path);
4369a3
+	free(pkcs11->token);
4369a3
+	free(pkcs11->object);
4369a3
+	free(pkcs11->lib_manuf);
4369a3
+	free(pkcs11->manuf);
4369a3
+	if (pkcs11->pin)
4369a3
+		freezero(pkcs11->pin, strlen(pkcs11->pin));
4369a3
+	free(pkcs11);
4369a3
+}
4369a3
+
4369a3
+int
4369a3
+pkcs11_uri_parse(const char *uri, struct pkcs11_uri *pkcs11)
4369a3
+{
4369a3
+	char *saveptr1, *saveptr2, *str1, *str2, *tok;
4369a3
+	int rv = 0, len;
4369a3
+	char *p = NULL;
4369a3
+
4369a3
+	size_t scheme_len = strlen(PKCS11_URI_SCHEME);
4369a3
+	if (strlen(uri) < scheme_len || /* empty URI matches everything */
4369a3
+	    strncmp(uri, PKCS11_URI_SCHEME, scheme_len) != 0) {
4369a3
+		error("%s: The '%s' does not look like PKCS#11 URI",
4369a3
+		    __func__, uri);
4369a3
+		return -1;
4369a3
+	}
4369a3
+
4369a3
+	if (pkcs11 == NULL) {
4369a3
+		error("%s: Bad arguments. The pkcs11 can't be null", __func__);
4369a3
+		return -1;
4369a3
+	}
4369a3
+
4369a3
+	/* skip URI schema name */
4369a3
+	p = strdup(uri);
4369a3
+	str1 = p;
4369a3
+
4369a3
+	/* everything before ? */
4369a3
+	tok = strtok_r(str1, "?", &saveptr1);
4369a3
+	if (tok == NULL) {
4369a3
+		error("%s: pk11-path expected, got EOF", __func__);
4369a3
+		rv = -1;
4369a3
+		goto out;
4369a3
+	}
4369a3
+
4369a3
+	/* skip URI schema name:
4369a3
+	 * the scheme ensures that there is at least something before "?"
4369a3
+	 * allowing empty pk11-path. Resulting token at worst pointing to
4369a3
+	 * \0 byte */
4369a3
+	tok = tok + scheme_len;
4369a3
+
4369a3
+	/* parse pk11-path */
4369a3
+	for (str2 = tok; ; str2 = NULL) {
4369a3
+		char **charptr, *arg = NULL;
4369a3
+		pkcs11uriOpCodes opcode;
4369a3
+		tok = strtok_r(str2, PKCS11_URI_PATH_SEPARATOR, &saveptr2);
4369a3
+		if (tok == NULL)
4369a3
+			break;
4369a3
+		opcode = parse_token(tok);
4369a3
+		if (opcode != pBadOption)
4369a3
+			arg = tok + strlen(keywords[opcode].name) + 1; /* separator "=" */
4369a3
+
4369a3
+		switch (opcode) {
4369a3
+		case pId:
4369a3
+			/* CKA_ID */
4369a3
+			if (pkcs11->id != NULL) {
4369a3
+				verbose("%s: The id already set in the PKCS#11 URI",
4369a3
+					__func__);
4369a3
+				rv = -1;
4369a3
+				goto out;
4369a3
+			}
4369a3
+			len = percent_decode(arg, &pkcs11->id);
4369a3
+			if (len <= 0) {
4369a3
+				verbose("%s: Failed to percent-decode CKA_ID: %s",
4369a3
+				    __func__, arg);
4369a3
+				rv = -1;
4369a3
+				goto out;
4369a3
+			} else
4369a3
+				pkcs11->id_len = len;
4369a3
+			debug3("%s: Setting CKA_ID = %s from PKCS#11 URI",
4369a3
+			    __func__, arg);
4369a3
+			break;
4369a3
+		case pToken:
4369a3
+			/* CK_TOKEN_INFO -> label */
4369a3
+			charptr = &pkcs11->token;
4369a3
+ parse_string:
4369a3
+			if (*charptr != NULL) {
4369a3
+				verbose("%s: The %s already set in the PKCS#11 URI",
4369a3
+				    keywords[opcode].name, __func__);
4369a3
+				rv = -1;
4369a3
+				goto out;
4369a3
+			}
4369a3
+			percent_decode(arg, charptr);
4369a3
+			debug3("%s: Setting %s = %s from PKCS#11 URI",
4369a3
+			    __func__, keywords[opcode].name, *charptr);
4369a3
+			break;
4369a3
+
4369a3
+		case pObject:
4369a3
+			/* CK_TOKEN_INFO -> manufacturerID */
4369a3
+			charptr = &pkcs11->object;
4369a3
+			goto parse_string;
4369a3
+
4369a3
+		case pManufacturer:
4369a3
+			/* CK_TOKEN_INFO -> manufacturerID */
4369a3
+			charptr = &pkcs11->manuf;
4369a3
+			goto parse_string;
4369a3
+
4369a3
+		case pLibraryManufacturer:
4369a3
+			/* CK_INFO -> manufacturerID */
4369a3
+			charptr = &pkcs11->lib_manuf;
4369a3
+			goto parse_string;
4369a3
+
4369a3
+		default:
4369a3
+			/* Unrecognized attribute in the URI path SHOULD be error */
4369a3
+			verbose("%s: Unknown part of path in PKCS#11 URI: %s",
4369a3
+			    __func__, tok);
4369a3
+		}
4369a3
+	}
4369a3
+
4369a3
+	tok = strtok_r(NULL, "?", &saveptr1);
4369a3
+	if (tok == NULL) {
4369a3
+		goto out;
4369a3
+	}
4369a3
+	/* parse pk11-query (optional) */
4369a3
+	for (str2 = tok; ; str2 = NULL) {
4369a3
+		char *arg;
4369a3
+		pkcs11uriOpCodes opcode;
4369a3
+		tok = strtok_r(str2, PKCS11_URI_QUERY_SEPARATOR, &saveptr2);
4369a3
+		if (tok == NULL)
4369a3
+			break;
4369a3
+		opcode = parse_token(tok);
4369a3
+		if (opcode != pBadOption)
4369a3
+			arg = tok + strlen(keywords[opcode].name) + 1; /* separator "=" */
4369a3
+
4369a3
+		switch (opcode) {
4369a3
+		case pModulePath:
4369a3
+			/* module-path is PKCS11Provider */
4369a3
+			if (pkcs11->module_path != NULL) {
4369a3
+				verbose("%s: Multiple module-path attributes are"
4369a3
+				    "not supported the PKCS#11 URI", __func__);
4369a3
+				rv = -1;
4369a3
+				goto out;
4369a3
+			}
4369a3
+			percent_decode(arg, &pkcs11->module_path);
4369a3
+			debug3("%s: Setting PKCS11Provider = %s from PKCS#11 URI",
4369a3
+			    __func__, pkcs11->module_path);
4369a3
+			break;
4369a3
+
4369a3
+		case pPinValue:
4369a3
+			/* pin-value */
4369a3
+			if (pkcs11->pin != NULL) {
4369a3
+				verbose("%s: Multiple pin-value attributes are"
4369a3
+				    "not supported the PKCS#11 URI", __func__);
4369a3
+				rv = -1;
4369a3
+				goto out;
4369a3
+			}
4369a3
+			percent_decode(arg, &pkcs11->pin);
4369a3
+			debug3("%s: Setting PIN from PKCS#11 URI", __func__);
4369a3
+			break;
4369a3
+
4369a3
+		default:
4369a3
+			/* Unrecognized attribute in the URI query SHOULD be ignored */
4369a3
+			verbose("%s: Unknown part of query in PKCS#11 URI: %s",
4369a3
+			    __func__, tok);
4369a3
+		}
4369a3
+	}
4369a3
+out:
4369a3
+	free(p);
4369a3
+	return rv;
4369a3
+}
4369a3
+
4369a3
+#endif /* ENABLE_PKCS11 */
4369a3
diff --git a/ssh-pkcs11-uri.h b/ssh-pkcs11-uri.h
4369a3
new file mode 100644
4369a3
index 00000000..942a5a5a
4369a3
--- /dev/null
4369a3
+++ b/ssh-pkcs11-uri.h
4369a3
@@ -0,0 +1,42 @@
4369a3
+/*
4369a3
+ * Copyright (c) 2017 Red Hat
4369a3
+ *
4369a3
+ * Authors: Jakub Jelen <jjelen@redhat.com>
4369a3
+ *
4369a3
+ * Permission to use, copy, modify, and distribute this software for any
4369a3
+ * purpose with or without fee is hereby granted, provided that the above
4369a3
+ * copyright notice and this permission notice appear in all copies.
4369a3
+ *
4369a3
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
4369a3
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
4369a3
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
4369a3
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
4369a3
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
4369a3
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
4369a3
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
4369a3
+ */
4369a3
+
4369a3
+#define PKCS11_URI_SCHEME "pkcs11:"
4369a3
+#define PKCS11_URI_WHITELIST	"abcdefghijklmnopqrstuvwxyz" \
4369a3
+				"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
4369a3
+				"0123456789_-.()"
4369a3
+
4369a3
+struct pkcs11_uri {
4369a3
+	/* path */
4369a3
+	char *id;
4369a3
+	size_t id_len;
4369a3
+	char *token;
4369a3
+	char *object;
4369a3
+	char *lib_manuf;
4369a3
+	char *manuf;
4369a3
+	/* query */
4369a3
+	char *module_path;
4369a3
+	char *pin; /* Only parsed, but not printed */
4369a3
+};
4369a3
+
4369a3
+struct	 pkcs11_uri *pkcs11_uri_init();
4369a3
+void	 pkcs11_uri_cleanup(struct pkcs11_uri *);
4369a3
+int	 pkcs11_uri_parse(const char *, struct pkcs11_uri *);
4369a3
+struct	 pkcs11_uri *pkcs11_uri_init();
4369a3
+char	*pkcs11_uri_get(struct pkcs11_uri *uri);
4369a3
+
4369a3
diff --git a/ssh-pkcs11.c b/ssh-pkcs11.c
4369a3
index 70f06bff..59332945 100644
4369a3
--- a/ssh-pkcs11.c
4369a3
+++ b/ssh-pkcs11.c
4369a3
@@ -54,8 +54,8 @@ struct pkcs11_slotinfo {
4369a3
 	int			logged_in;
4369a3
 };
4369a3
 
4369a3
-struct pkcs11_provider {
4369a3
-	char			*name;
4369a3
+struct pkcs11_module {
4369a3
+	char			*module_path;
4369a3
 	void			*handle;
4369a3
 	CK_FUNCTION_LIST	*function_list;
4369a3
 	CK_INFO			info;
4369a3
@@ -64,6 +64,13 @@ struct pkcs11_provider {
4369a3
 	struct pkcs11_slotinfo	*slotinfo;
4369a3
 	int			valid;
4369a3
 	int			refcount;
4369a3
+};
4369a3
+
4369a3
+struct pkcs11_provider {
4369a3
+	char			*name;
4369a3
+	struct pkcs11_module	*module; /* can be shared between various providers */
4369a3
+	int			refcount;
4369a3
+	int			valid;
4369a3
 	TAILQ_ENTRY(pkcs11_provider) next;
4369a3
 };
4369a3
 
4369a3
@@ -74,6 +81,7 @@ struct pkcs11_key {
4369a3
 	CK_ULONG		slotidx;
4369a3
 	char			*keyid;
4369a3
 	int			keyid_len;
4369a3
+	char			*label;
4369a3
 };
4369a3
 
4369a3
 int pkcs11_interactive = 0;
4369a3
@@ -106,26 +114,63 @@ pkcs11_init(int interactive)
4369a3
  * this is called when a provider gets unregistered.
4369a3
  */
4369a3
 static void
4369a3
-pkcs11_provider_finalize(struct pkcs11_provider *p)
4369a3
+pkcs11_module_finalize(struct pkcs11_module *m)
4369a3
 {
4369a3
 	CK_RV rv;
4369a3
 	CK_ULONG i;
4369a3
 
4369a3
-	debug("pkcs11_provider_finalize: %p refcount %d valid %d",
4369a3
-	    p, p->refcount, p->valid);
4369a3
-	if (!p->valid)
4369a3
+	debug("%s: %p refcount %d valid %d", __func__,
4369a3
+	    m, m->refcount, m->valid);
4369a3
+	if (!m->valid)
4369a3
 		return;
4369a3
-	for (i = 0; i < p->nslots; i++) {
4369a3
-		if (p->slotinfo[i].session &&
4369a3
-		    (rv = p->function_list->C_CloseSession(
4369a3
-		    p->slotinfo[i].session)) != CKR_OK)
4369a3
+	for (i = 0; i < m->nslots; i++) {
4369a3
+		if (m->slotinfo[i].session &&
4369a3
+		    (rv = m->function_list->C_CloseSession(
4369a3
+		    m->slotinfo[i].session)) != CKR_OK)
4369a3
 			error("C_CloseSession failed: %lu", rv);
4369a3
 	}
4369a3
-	if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
4369a3
+	if ((rv = m->function_list->C_Finalize(NULL)) != CKR_OK)
4369a3
 		error("C_Finalize failed: %lu", rv);
4369a3
+	m->valid = 0;
4369a3
+	m->function_list = NULL;
4369a3
+	dlclose(m->handle);
4369a3
+}
4369a3
+
4369a3
+/*
4369a3
+ * remove a reference to the pkcs11 module.
4369a3
+ * called when a provider is unregistered.
4369a3
+ */
4369a3
+static void
4369a3
+pkcs11_module_unref(struct pkcs11_module *m)
4369a3
+{
4369a3
+	debug("%s: %p refcount %d", __func__, m, m->refcount);
4369a3
+	if (--m->refcount <= 0) {
4369a3
+		pkcs11_module_finalize(m);
4369a3
+		if (m->valid)
4369a3
+			error("%s: %p still valid", __func__, m);
4369a3
+		free(m->slotlist);
4369a3
+		free(m->slotinfo);
4369a3
+		free(m->module_path);
4369a3
+		free(m);
4369a3
+	}
4369a3
+}
4369a3
+
4369a3
+/*
4369a3
+ * finalize a provider shared libarary, it's no longer usable.
4369a3
+ * however, there might still be keys referencing this provider,
4369a3
+ * so the actuall freeing of memory is handled by pkcs11_provider_unref().
4369a3
+ * this is called when a provider gets unregistered.
4369a3
+ */
4369a3
+static void
4369a3
+pkcs11_provider_finalize(struct pkcs11_provider *p)
4369a3
+{
4369a3
+	debug("%s: %p refcount %d valid %d", __func__,
4369a3
+	    p, p->refcount, p->valid);
4369a3
+	if (!p->valid)
4369a3
+		return;
4369a3
+	pkcs11_module_unref(p->module);
4369a3
+	p->module = NULL;
4369a3
 	p->valid = 0;
4369a3
-	p->function_list = NULL;
4369a3
-	dlclose(p->handle);
4369a3
 }
4369a3
 
4369a3
 /*
4369a3
@@ -135,13 +180,11 @@ pkcs11_provider_finalize(struct pkcs11_provider *p)
4369a3
 static void
4369a3
 pkcs11_provider_unref(struct pkcs11_provider *p)
4369a3
 {
4369a3
-	debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
4369a3
+	debug("%s: %p refcount %d", __func__, p, p->refcount);
4369a3
 	if (--p->refcount <= 0) {
4369a3
-		if (p->valid)
4369a3
-			error("pkcs11_provider_unref: %p still valid", p);
4369a3
 		free(p->name);
4369a3
-		free(p->slotlist);
4369a3
-		free(p->slotinfo);
4369a3
+		if (p->module)
4369a3
+			pkcs11_module_unref(p->module);
4369a3
 		free(p);
4369a3
 	}
4369a3
 }
4369a3
@@ -159,6 +202,20 @@ pkcs11_terminate(void)
4369a3
 	}
4369a3
 }
4369a3
 
4369a3
+/* lookup provider by module path */
4369a3
+static struct pkcs11_module *
4369a3
+pkcs11_provider_lookup_module(char *module_path)
4369a3
+{
4369a3
+	struct pkcs11_provider *p;
4369a3
+
4369a3
+	TAILQ_FOREACH(p, &pkcs11_providers, next) {
4369a3
+		debug("check %p %s (%s)", p, p->name, p->module->module_path);
4369a3
+		if (!strcmp(module_path, p->module->module_path))
4369a3
+			return (p->module);
4369a3
+	}
4369a3
+	return (NULL);
4369a3
+}
4369a3
+
4369a3
 /* lookup provider by name */
4369a3
 static struct pkcs11_provider *
4369a3
 pkcs11_provider_lookup(char *provider_id)
4369a3
@@ -173,19 +230,52 @@ pkcs11_provider_lookup(char *provider_id)
4369a3
 	return (NULL);
4369a3
 }
4369a3
 
4369a3
+int pkcs11_del_provider_by_uri(struct pkcs11_uri *);
4369a3
+
4369a3
 /* unregister provider by name */
4369a3
 int
4369a3
 pkcs11_del_provider(char *provider_id)
4369a3
+{
4369a3
+	int rv;
4369a3
+	struct pkcs11_uri *uri;
4369a3
+
4369a3
+	debug("%s: called, provider_id = %s", __func__, provider_id);
4369a3
+
4369a3
+	uri = pkcs11_uri_init();
4369a3
+	if (uri == NULL)
4369a3
+		fatal("Failed to init PCKS#11 URI");
4369a3
+
4369a3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
4369a3
+			fatal("Failed to parse PKCS#11 URI");
4369a3
+	} else {
4369a3
+		uri->module_path = strdup(provider_id);
4369a3
+	}
4369a3
+
4369a3
+	rv = pkcs11_del_provider_by_uri(uri);
4369a3
+	pkcs11_uri_cleanup(uri);
4369a3
+	return rv;
4369a3
+}
4369a3
+
4369a3
+/* unregister provider by PKCS#11 URI */
4369a3
+int
4369a3
+pkcs11_del_provider_by_uri(struct pkcs11_uri *uri)
4369a3
 {
4369a3
 	struct pkcs11_provider *p;
4369a3
+	int rv = -1;
4369a3
+	char *provider_uri = pkcs11_uri_get(uri);
4369a3
 
4369a3
-	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
4369a3
+	debug3("%s(%s): called", __func__, provider_uri);
4369a3
+
4369a3
+	if ((p = pkcs11_provider_lookup(provider_uri)) != NULL) {
4369a3
 		TAILQ_REMOVE(&pkcs11_providers, p, next);
4369a3
 		pkcs11_provider_finalize(p);
4369a3
 		pkcs11_provider_unref(p);
4369a3
-		return (0);
4369a3
+		rv = 0;
4369a3
 	}
4369a3
-	return (-1);
4369a3
+	free(provider_uri);
4369a3
+	return rv;
4369a3
 }
4369a3
 
4369a3
 static RSA_METHOD *rsa_method;
4369a3
@@ -195,6 +285,55 @@ static EC_KEY_METHOD *ec_key_method;
4369a3
 static int ec_key_idx = 0;
4369a3
 #endif
4369a3
 
4369a3
+/*
4369a3
+ * This can't be in the ssh-pkcs11-uri, becase we can not depend on
4369a3
+ * PKCS#11 structures in ssh-agent (using client-helper communication)
4369a3
+ */
4369a3
+int
4369a3
+pkcs11_uri_write(const struct sshkey *key, FILE *f)
4369a3
+{
4369a3
+	char *p = NULL;
4369a3
+	struct pkcs11_uri uri;
4369a3
+	struct pkcs11_key *k11;
4369a3
+
4369a3
+	/* sanity - is it a RSA key with associated app_data? */
4369a3
+	switch (key->type) {
4369a3
+	case KEY_RSA:
4369a3
+		k11 = RSA_get_ex_data(key->rsa, rsa_idx);
4369a3
+		break;
4369a3
+#ifdef HAVE_EC_KEY_METHOD_NEW
4369a3
+	case KEY_ECDSA:
4369a3
+		k11 = EC_KEY_get_ex_data(key->ecdsa, ec_key_idx);
4369a3
+		break;
4369a3
+#endif
4369a3
+	default:
4369a3
+		error("Unknown key type %d", key->type);
4369a3
+		return -1;
4369a3
+	}
4369a3
+	if (k11 == NULL) {
4369a3
+		error("Failed to get ex_data for key type %d", key->type);
4369a3
+		return (-1);
4369a3
+	}
4369a3
+
4369a3
+	/* omit type -- we are looking for private-public or private-certificate pairs */
4369a3
+	uri.id = k11->keyid;
4369a3
+	uri.id_len = k11->keyid_len;
4369a3
+	uri.token = k11->provider->module->slotinfo[k11->slotidx].token.label;
4369a3
+	uri.object = k11->label;
4369a3
+	uri.module_path = k11->provider->module->module_path;
4369a3
+	uri.lib_manuf = k11->provider->module->info.manufacturerID;
4369a3
+	uri.manuf = k11->provider->module->slotinfo[k11->slotidx].token.manufacturerID;
4369a3
+
4369a3
+	p = pkcs11_uri_get(&uri);
4369a3
+	/* do not cleanup -- we do not allocate here, only reference */
4369a3
+	if (p == NULL)
4369a3
+		return -1;
4369a3
+
4369a3
+	fprintf(f, " %s", p);
4369a3
+	free(p);
4369a3
+	return 0;
4369a3
+}
4369a3
+
4369a3
 /* release a wrapped object */
4369a3
 static void
4369a3
 pkcs11_k11_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
4369a3
@@ -208,6 +347,7 @@ pkcs11_k11_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
4369a3
         if (k11->provider)
4369a3
                 pkcs11_provider_unref(k11->provider);
4369a3
         free(k11->keyid);
4369a3
+	free(k11->label);
4369a3
         free(k11);
4369a3
 }
4369a3
 
4369a3
@@ -222,8 +362,8 @@ pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
4369a3
 	CK_RV			rv;
4369a3
 	int			ret = -1;
4369a3
 
4369a3
-	f = p->function_list;
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
 	if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
4369a3
 		error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
4369a3
 		return (-1);
4369a3
@@ -252,8 +392,8 @@ pkcs11_login(struct pkcs11_key *k11, CK_USER_TYPE type)
4369a3
 		return (-1);
4369a3
 	}
4369a3
 
4369a3
-	f = k11->provider->function_list;
4369a3
-	si = &k11->provider->slotinfo[k11->slotidx];
4369a3
+	f = k11->provider->module->function_list;
4369a3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
4369a3
 
4369a3
 	if (!pkcs11_interactive) {
4369a3
 		error("need pin entry%s",
4369a3
@@ -300,8 +440,8 @@ pkcs11_check_obj_bool_attrib(struct pkcs11_key *k11, CK_OBJECT_HANDLE obj,
4369a3
 		return (-1);
4369a3
 	}
4369a3
 
4369a3
-	f = k11->provider->function_list;
4369a3
-	si = &k11->provider->slotinfo[k11->slotidx];
4369a3
+	f = k11->provider->module->function_list;
4369a3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
4369a3
 
4369a3
 	attr.type = type;
4369a3
 	attr.pValue = &flag;
4369a3
@@ -332,13 +472,14 @@ pkcs11_get_key(struct pkcs11_key *k11, CK_MECHANISM_TYPE mech_type)
4369a3
 	int			 always_auth = 0;
4369a3
 	int			 did_login = 0;
4369a3
 
4369a3
-	if (!k11->provider || !k11->provider->valid) {
4369a3
+	if (!k11->provider || !k11->provider->valid || !k11->provider->module
4369a3
+	    || !k11->provider->module->valid) {
4369a3
 		error("no pkcs11 (valid) provider found");
4369a3
 		return (-1);
4369a3
 	}
4369a3
 
4369a3
-	f = k11->provider->function_list;
4369a3
-	si = &k11->provider->slotinfo[k11->slotidx];
4369a3
+	f = k11->provider->module->function_list;
4369a3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
4369a3
 
4369a3
 	if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
4369a3
 		if (pkcs11_login(k11, CKU_USER) < 0) {
4369a3
@@ -415,8 +556,8 @@ pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
4369a3
 		return (-1);
4369a3
 	}
4369a3
 
4369a3
-	f = k11->provider->function_list;
4369a3
-	si = &k11->provider->slotinfo[k11->slotidx];
4369a3
+	f = k11->provider->module->function_list;
4369a3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
4369a3
 	tlen = RSA_size(rsa);
4369a3
 
4369a3
 	/* XXX handle CKR_BUFFER_TOO_SMALL */
4369a3
@@ -460,7 +601,7 @@ pkcs11_rsa_start_wrapper(void)
4369a3
 /* redirect private key operations for rsa key to pkcs11 token */
4369a3
 static int
4369a3
 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
4369a3
-    CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
4369a3
+    CK_ATTRIBUTE *keyid_attrib, CK_ATTRIBUTE *label_attrib, RSA *rsa)
4369a3
 {
4369a3
 	struct pkcs11_key	*k11;
4369a3
 
4369a3
@@ -478,6 +619,12 @@ pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
4369a3
 		memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
4369a3
 	}
4369a3
 
4369a3
+	if (label_attrib->ulValueLen > 0 ) {
4369a3
+		k11->label = xmalloc(label_attrib->ulValueLen+1);
4369a3
+		memcpy(k11->label, label_attrib->pValue, label_attrib->ulValueLen);
4369a3
+		k11->label[label_attrib->ulValueLen] = 0;
4369a3
+	}
4369a3
+
4369a3
 	RSA_set_method(rsa, rsa_method);
4369a3
 	RSA_set_ex_data(rsa, rsa_idx, k11);
4369a3
 	return (0);
4369a3
@@ -508,8 +655,8 @@ ecdsa_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv,
4369a3
 		return (NULL);
4369a3
 	}
4369a3
 
4369a3
-	f = k11->provider->function_list;
4369a3
-	si = &k11->provider->slotinfo[k11->slotidx];
4369a3
+	f = k11->provider->module->function_list;
4369a3
+	si = &k11->provider->module->slotinfo[k11->slotidx];
4369a3
 
4369a3
 	siglen = ECDSA_size(ec);
4369a3
 	sig = xmalloc(siglen);
4369a3
@@ -574,7 +721,7 @@ pkcs11_ecdsa_start_wrapper(void)
4369a3
 
4369a3
 static int
4369a3
 pkcs11_ecdsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
4369a3
-    CK_ATTRIBUTE *keyid_attrib, EC_KEY *ec)
4369a3
+    CK_ATTRIBUTE *keyid_attrib, CK_ATTRIBUTE *label_attrib, EC_KEY *ec)
4369a3
 {
4369a3
 	struct pkcs11_key	*k11;
4369a3
 
4369a3
@@ -590,6 +737,12 @@ pkcs11_ecdsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
4369a3
 	k11->keyid = xmalloc(k11->keyid_len);
4369a3
 	memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
4369a3
 
4369a3
+	if (label_attrib->ulValueLen > 0 ) {
4369a3
+		k11->label = xmalloc(label_attrib->ulValueLen+1);
4369a3
+		memcpy(k11->label, label_attrib->pValue, label_attrib->ulValueLen);
4369a3
+		k11->label[label_attrib->ulValueLen] = 0;
4369a3
+	}
4369a3
+
4369a3
 	EC_KEY_set_method(ec, ec_key_method);
4369a3
 	EC_KEY_set_ex_data(ec, ec_key_idx, k11);
4369a3
 
4369a3
@@ -624,47 +777,26 @@ pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin,
4369a3
 	CK_FUNCTION_LIST	*f;
4369a3
 	CK_RV			rv;
4369a3
 	CK_SESSION_HANDLE	session;
4369a3
-	int			login_required, have_pinpad, ret;
4369a3
-	char			prompt[1024], *xpin = NULL;
4369a3
+	int			login_required, ret;
4369a3
 
4369a3
-	f = p->function_list;
4369a3
-	si = &p->slotinfo[slotidx];
4369a3
+	f = p->module->function_list;
4369a3
+	si = &p->module->slotinfo[slotidx];
4369a3
 
4369a3
-	have_pinpad = si->token.flags & CKF_PROTECTED_AUTHENTICATION_PATH;
4369a3
 	login_required = si->token.flags & CKF_LOGIN_REQUIRED;
4369a3
 
4369a3
 	/* fail early before opening session */
4369a3
-	if (login_required && !have_pinpad && !pkcs11_interactive &&
4369a3
+	if (login_required && !pkcs11_interactive &&
4369a3
 	    (pin == NULL || strlen(pin) == 0)) {
4369a3
 		error("pin required");
4369a3
 		return (-SSH_PKCS11_ERR_PIN_REQUIRED);
4369a3
 	}
4369a3
-	if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
4369a3
+	if ((rv = f->C_OpenSession(p->module->slotlist[slotidx], CKF_RW_SESSION|
4369a3
 	    CKF_SERIAL_SESSION, NULL, NULL, &session)) != CKR_OK) {
4369a3
-		error("C_OpenSession failed: %lu", rv);
4369a3
+		error("C_OpenSession failed for slot %lu: %lu", slotidx, rv);
4369a3
 		return (-1);
4369a3
 	}
4369a3
-	if (login_required) {
4369a3
-		if (have_pinpad && (pin == NULL || strlen(pin) == 0)) {
4369a3
-			/* defer PIN entry to the reader keypad */
4369a3
-			rv = f->C_Login(session, CKU_USER, NULL_PTR, 0);
4369a3
-		} else {
4369a3
-			if (pkcs11_interactive) {
4369a3
-				snprintf(prompt, sizeof(prompt),
4369a3
-				    "Enter PIN for '%s': ", si->token.label);
4369a3
-				if ((xpin = read_passphrase(prompt,
4369a3
-				    RP_ALLOW_EOF)) == NULL) {
4369a3
-					debug("%s: no pin specified",
4369a3
-					    __func__);
4369a3
-					return (-SSH_PKCS11_ERR_PIN_REQUIRED);
4369a3
-				}
4369a3
-				pin = xpin;
4369a3
-			}
4369a3
-			rv = f->C_Login(session, CKU_USER,
4369a3
-			    (u_char *)pin, strlen(pin));
4369a3
-			if (xpin != NULL)
4369a3
-				freezero(xpin, strlen(xpin));
4369a3
-		}
4369a3
+	if (login_required && pin != NULL && strlen(pin) != 0) {
4369a3
+		rv = f->C_Login(session, user, (u_char *)pin, strlen(pin));
4369a3
 		if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
4369a3
 			error("C_Login failed: %lu", rv);
4369a3
 			ret = (rv == CKR_PIN_LOCKED) ?
4369a3
@@ -696,7 +828,8 @@ static struct sshkey *
4369a3
 pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
     CK_OBJECT_HANDLE *obj)
4369a3
 {
4369a3
-	CK_ATTRIBUTE		 key_attr[3];
4369a3
+	CK_ATTRIBUTE		 key_attr[4];
4369a3
+	int			 nattr = 4;
4369a3
 	CK_SESSION_HANDLE	 session;
4369a3
 	CK_FUNCTION_LIST	*f = NULL;
4369a3
 	CK_RV			 rv;
4369a3
@@ -710,14 +843,15 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 
4369a3
 	memset(&key_attr, 0, sizeof(key_attr));
4369a3
 	key_attr[0].type = CKA_ID;
4369a3
-	key_attr[1].type = CKA_EC_POINT;
4369a3
-	key_attr[2].type = CKA_EC_PARAMS;
4369a3
+	key_attr[1].type = CKA_LABEL;
4369a3
+	key_attr[2].type = CKA_EC_POINT;
4369a3
+	key_attr[3].type = CKA_EC_PARAMS;
4369a3
 
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
-	f = p->function_list;
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
 
4369a3
 	/* figure out size of the attributes */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		return (NULL);
4369a3
@@ -730,19 +863,19 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	 * ensure that none of the others are zero length.
4369a3
 	 * XXX assumes CKA_ID is always first.
4369a3
 	 */
4369a3
-	if (key_attr[1].ulValueLen == 0 ||
4369a3
-	    key_attr[2].ulValueLen == 0) {
4369a3
+	if (key_attr[2].ulValueLen == 0 ||
4369a3
+	    key_attr[3].ulValueLen == 0) {
4369a3
 		error("invalid attribute length");
4369a3
 		return (NULL);
4369a3
 	}
4369a3
 
4369a3
 	/* allocate buffers for attributes */
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		if (key_attr[i].ulValueLen > 0)
4369a3
 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
4369a3
 
4369a3
 	/* retrieve ID, public point and curve parameters of EC key */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		goto fail;
4369a3
@@ -752,8 +887,8 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	attrp = key_attr[2].pValue;
4369a3
-	group = d2i_ECPKParameters(NULL, &attrp, key_attr[2].ulValueLen);
4369a3
+	attrp = key_attr[3].pValue;
4369a3
+	group = d2i_ECPKParameters(NULL, &attrp, key_attr[3].ulValueLen);
4369a3
 	if (group == NULL) {
4369a3
 		ossl_error("d2i_ECPKParameters failed");
4369a3
 		goto fail;
4369a3
@@ -764,13 +899,13 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	if (key_attr[1].ulValueLen <= 2) {
4369a3
+	if (key_attr[2].ulValueLen <= 2) {
4369a3
 		error("CKA_EC_POINT too small");
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	attrp = key_attr[1].pValue;
4369a3
-	octet = d2i_ASN1_OCTET_STRING(NULL, &attrp, key_attr[1].ulValueLen);
4369a3
+	attrp = key_attr[2].pValue;
4369a3
+	octet = d2i_ASN1_OCTET_STRING(NULL, &attrp, key_attr[2].ulValueLen);
4369a3
 	if (octet == NULL) {
4369a3
 		ossl_error("d2i_ASN1_OCTET_STRING failed");
4369a3
 		goto fail;
4369a3
@@ -787,7 +922,7 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	if (pkcs11_ecdsa_wrap(p, slotidx, &key_attr[0], ec))
4369a3
+	if (pkcs11_ecdsa_wrap(p, slotidx, &key_attr[0], &key_attr[1], ec))
4369a3
 		goto fail;
4369a3
 
4369a3
 	key = sshkey_new(KEY_UNSPEC);
4369a3
@@ -803,7 +938,7 @@ pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	ec = NULL;	/* now owned by key */
4369a3
 
4369a3
 fail:
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		free(key_attr[i].pValue);
4369a3
 	if (ec)
4369a3
 		EC_KEY_free(ec);
4369a3
@@ -820,7 +955,8 @@ static struct sshkey *
4369a3
 pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
     CK_OBJECT_HANDLE *obj)
4369a3
 {
4369a3
-	CK_ATTRIBUTE		 key_attr[3];
4369a3
+	CK_ATTRIBUTE		 key_attr[4];
4369a3
+	int			 nattr = 4;
4369a3
 	CK_SESSION_HANDLE	 session;
4369a3
 	CK_FUNCTION_LIST	*f = NULL;
4369a3
 	CK_RV			 rv;
4369a3
@@ -831,14 +967,15 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 
4369a3
 	memset(&key_attr, 0, sizeof(key_attr));
4369a3
 	key_attr[0].type = CKA_ID;
4369a3
-	key_attr[1].type = CKA_MODULUS;
4369a3
-	key_attr[2].type = CKA_PUBLIC_EXPONENT;
4369a3
+	key_attr[1].type = CKA_LABEL;
4369a3
+	key_attr[2].type = CKA_MODULUS;
4369a3
+	key_attr[3].type = CKA_PUBLIC_EXPONENT;
4369a3
 
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
-	f = p->function_list;
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
 
4369a3
 	/* figure out size of the attributes */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		return (NULL);
4369a3
@@ -850,19 +987,19 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	 * ensure that none of the others are zero length.
4369a3
 	 * XXX assumes CKA_ID is always first.
4369a3
 	 */
4369a3
-	if (key_attr[1].ulValueLen == 0 ||
4369a3
-	    key_attr[2].ulValueLen == 0) {
4369a3
+	if (key_attr[2].ulValueLen == 0 ||
4369a3
+	    key_attr[3].ulValueLen == 0) {
4369a3
 		error("invalid attribute length");
4369a3
 		return (NULL);
4369a3
 	}
4369a3
 
4369a3
 	/* allocate buffers for attributes */
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		if (key_attr[i].ulValueLen > 0)
4369a3
 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
4369a3
 
4369a3
 	/* retrieve ID, modulus and public exponent of RSA key */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		goto fail;
4369a3
@@ -873,8 +1011,8 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	rsa_n = BN_bin2bn(key_attr[1].pValue, key_attr[1].ulValueLen, NULL);
4369a3
-	rsa_e = BN_bin2bn(key_attr[2].pValue, key_attr[2].ulValueLen, NULL);
4369a3
+	rsa_n = BN_bin2bn(key_attr[2].pValue, key_attr[2].ulValueLen, NULL);
4369a3
+	rsa_e = BN_bin2bn(key_attr[3].pValue, key_attr[3].ulValueLen, NULL);
4369a3
 	if (rsa_n == NULL || rsa_e == NULL) {
4369a3
 		error("BN_bin2bn failed");
4369a3
 		goto fail;
4369a3
@@ -883,7 +1021,7 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		fatal("%s: set key", __func__);
4369a3
 	rsa_n = rsa_e = NULL; /* transferred */
4369a3
 
4369a3
-	if (pkcs11_rsa_wrap(p, slotidx, &key_attr[0], rsa))
4369a3
+	if (pkcs11_rsa_wrap(p, slotidx, &key_attr[0], &key_attr[1], rsa))
4369a3
 		goto fail;
4369a3
 
4369a3
 	key = sshkey_new(KEY_UNSPEC);
4369a3
@@ -898,7 +1036,7 @@ pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	rsa = NULL;	/* now owned by key */
4369a3
 
4369a3
 fail:
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		free(key_attr[i].pValue);
4369a3
 	RSA_free(rsa);
4369a3
 
4369a3
@@ -909,7 +1047,8 @@ static struct sshkey *
4369a3
 pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
     CK_OBJECT_HANDLE *obj)
4369a3
 {
4369a3
-	CK_ATTRIBUTE		 cert_attr[3];
4369a3
+	CK_ATTRIBUTE		 cert_attr[4];
4369a3
+	int			 nattr = 4;
4369a3
 	CK_SESSION_HANDLE	 session;
4369a3
 	CK_FUNCTION_LIST	*f = NULL;
4369a3
 	CK_RV			 rv;
4369a3
@@ -926,14 +1065,15 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 
4369a3
 	memset(&cert_attr, 0, sizeof(cert_attr));
4369a3
 	cert_attr[0].type = CKA_ID;
4369a3
-	cert_attr[1].type = CKA_SUBJECT;
4369a3
-	cert_attr[2].type = CKA_VALUE;
4369a3
+	cert_attr[1].type = CKA_LABEL;
4369a3
+	cert_attr[2].type = CKA_SUBJECT;
4369a3
+	cert_attr[3].type = CKA_VALUE;
4369a3
 
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
-	f = p->function_list;
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
 
4369a3
 	/* figure out size of the attributes */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, cert_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		return (NULL);
4369a3
@@ -945,18 +1085,19 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	 * XXX assumes CKA_ID is always first.
4369a3
 	 */
4369a3
 	if (cert_attr[1].ulValueLen == 0 ||
4369a3
-	    cert_attr[2].ulValueLen == 0) {
4369a3
+	    cert_attr[2].ulValueLen == 0 ||
4369a3
+	    cert_attr[3].ulValueLen == 0) {
4369a3
 		error("invalid attribute length");
4369a3
 		return (NULL);
4369a3
 	}
4369a3
 
4369a3
 	/* allocate buffers for attributes */
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		if (cert_attr[i].ulValueLen > 0)
4369a3
 			cert_attr[i].pValue = xcalloc(1, cert_attr[i].ulValueLen);
4369a3
 
4369a3
 	/* retrieve ID, subject and value of certificate */
4369a3
-	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
4369a3
+	rv = f->C_GetAttributeValue(session, *obj, cert_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_GetAttributeValue failed: %lu", rv);
4369a3
 		goto fail;
4369a3
@@ -968,8 +1109,8 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		goto fail;
4369a3
 	}
4369a3
 
4369a3
-	cp = cert_attr[2].pValue;
4369a3
-	if (d2i_X509(&x509, &cp, cert_attr[2].ulValueLen) == NULL) {
4369a3
+	cp = cert_attr[3].pValue;
4369a3
+	if (d2i_X509(&x509, &cp, cert_attr[3].ulValueLen) == NULL) {
4369a3
 		error("d2i_x509 failed");
4369a3
 		goto fail;
4369a3
 	}
4369a3
@@ -990,7 +1131,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 			goto fail;
4369a3
 		}
4369a3
 
4369a3
-		if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], rsa))
4369a3
+		if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], &cert_attr[1], rsa))
4369a3
 			goto fail;
4369a3
 
4369a3
 		key = sshkey_new(KEY_UNSPEC);
4369a3
@@ -1020,7 +1161,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 			goto fail;
4369a3
 		}
4369a3
 
4369a3
-		if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], ec))
4369a3
+		if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], &cert_attr[1], ec))
4369a3
 			goto fail;
4369a3
 
4369a3
 		key = sshkey_new(KEY_UNSPEC);
4369a3
@@ -1039,7 +1180,7 @@ pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 		error("unknown certificate key type");
4369a3
 
4369a3
 fail:
4369a3
-	for (i = 0; i < 3; i++)
4369a3
+	for (i = 0; i < nattr; i++)
4369a3
 		free(cert_attr[i].pValue);
4369a3
 	X509_free(x509);
4369a3
 	RSA_free(rsa);
4369a3
@@ -1066,11 +1207,12 @@ have_rsa_key(const RSA *rsa)
4369a3
  */
4369a3
 static int
4369a3
 pkcs11_fetch_certs(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
-    struct sshkey ***keysp, int *nkeys)
4369a3
+    struct sshkey ***keysp, int *nkeys, struct pkcs11_uri *uri)
4369a3
 {
4369a3
 	struct sshkey		*key = NULL;
4369a3
 	CK_OBJECT_CLASS		 key_class;
4369a3
-	CK_ATTRIBUTE		 key_attr[1];
4369a3
+	CK_ATTRIBUTE		 key_attr[3];
4369a3
+	int			 nattr = 1;
4369a3
 	CK_SESSION_HANDLE	 session;
4369a3
 	CK_FUNCTION_LIST	*f = NULL;
4369a3
 	CK_RV			 rv;
4369a3
@@ -1086,10 +1228,23 @@ pkcs11_fetch_certs(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	key_attr[0].pValue = &key_class;
4369a3
 	key_attr[0].ulValueLen = sizeof(key_class);
4369a3
 
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
-	f = p->function_list;
4369a3
+	if (uri->id != NULL) {
4369a3
+		key_attr[nattr].type = CKA_ID;
4369a3
+		key_attr[nattr].pValue = uri->id;
4369a3
+		key_attr[nattr].ulValueLen = uri->id_len;
4369a3
+		nattr++;
4369a3
+	}
4369a3
+	if (uri->object != NULL) {
4369a3
+		key_attr[nattr].type = CKA_LABEL;
4369a3
+		key_attr[nattr].pValue = uri->object;
4369a3
+		key_attr[nattr].ulValueLen = strlen(uri->object);
4369a3
+		nattr++;
4369a3
+	}
4369a3
 
4369a3
-	rv = f->C_FindObjectsInit(session, key_attr, 1);
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
+
4369a3
+	rv = f->C_FindObjectsInit(session, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_FindObjectsInit failed: %lu", rv);
4369a3
 		goto fail;
4369a3
@@ -1163,11 +1318,12 @@ fail:
4369a3
  */
4369a3
 static int
4369a3
 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
-    struct sshkey ***keysp, int *nkeys)
4369a3
+    struct sshkey ***keysp, int *nkeys, struct pkcs11_uri *uri)
4369a3
 {
4369a3
 	struct sshkey		*key = NULL;
4369a3
 	CK_OBJECT_CLASS		 key_class;
4369a3
-	CK_ATTRIBUTE		 key_attr[1];
4369a3
+	CK_ATTRIBUTE		 key_attr[3];
4369a3
+	int			 nattr = 1;
4369a3
 	CK_SESSION_HANDLE	 session;
4369a3
 	CK_FUNCTION_LIST	*f = NULL;
4369a3
 	CK_RV			 rv;
4369a3
@@ -1183,10 +1339,23 @@ pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 	key_attr[0].pValue = &key_class;
4369a3
 	key_attr[0].ulValueLen = sizeof(key_class);
4369a3
 
4369a3
-	session = p->slotinfo[slotidx].session;
4369a3
-	f = p->function_list;
4369a3
+	if (uri->id != NULL) {
4369a3
+		key_attr[nattr].type = CKA_ID;
4369a3
+		key_attr[nattr].pValue = uri->id;
4369a3
+		key_attr[nattr].ulValueLen = uri->id_len;
4369a3
+		nattr++;
4369a3
+	}
4369a3
+	if (uri->object != NULL) {
4369a3
+		key_attr[nattr].type = CKA_LABEL;
4369a3
+		key_attr[nattr].pValue = uri->object;
4369a3
+		key_attr[nattr].ulValueLen = strlen(uri->object);
4369a3
+		nattr++;
4369a3
+	}
4369a3
 
4369a3
-	rv = f->C_FindObjectsInit(session, key_attr, 1);
4369a3
+	session = p->module->slotinfo[slotidx].session;
4369a3
+	f = p->module->function_list;
4369a3
+
4369a3
+	rv = f->C_FindObjectsInit(session, key_attr, nattr);
4369a3
 	if (rv != CKR_OK) {
4369a3
 		error("C_FindObjectsInit failed: %lu", rv);
4369a3
 		goto fail;
4369a3
@@ -1443,15 +1612,10 @@ pkcs11_ecdsa_generate_private_key(struct pkcs11_provider *p, CK_ULONG slotidx,
4369a3
 }
4369a3
 #endif /* WITH_PKCS11_KEYGEN */
4369a3
 
4369a3
-/*
4369a3
- * register a new provider, fails if provider already exists. if
4369a3
- * keyp is provided, fetch keys.
4369a3
- */
4369a3
 static int
4369a3
-pkcs11_register_provider(char *provider_id, char *pin, struct sshkey ***keyp,
4369a3
-    struct pkcs11_provider **providerp, CK_ULONG user)
4369a3
+pkcs11_initialize_provider(struct pkcs11_uri *uri, struct pkcs11_provider **providerp)
4369a3
 {
4369a3
-	int nkeys, need_finalize = 0;
4369a3
+	int need_finalize = 0;
4369a3
 	int ret = -1;
4369a3
 	struct pkcs11_provider *p = NULL;
4369a3
 	void *handle = NULL;
4369a3
@@ -1460,148 +1624,285 @@ pkcs11_register_provider(char *provider_id, char *pin, struct sshkey ***keyp,
4369a3
 	CK_FUNCTION_LIST *f = NULL;
4369a3
 	CK_TOKEN_INFO *token;
4369a3
 	CK_ULONG i;
4369a3
-
4369a3
-	if (providerp == NULL)
4369a3
+	char *provider_module = NULL;
4369a3
+	struct pkcs11_module *m = NULL;
4369a3
+
4369a3
+	/* if no provider specified, fallback to p11-kit */
4369a3
+	if (uri->module_path == NULL) {
4369a3
+#ifdef PKCS11_DEFAULT_PROVIDER
4369a3
+		provider_module = strdup(PKCS11_DEFAULT_PROVIDER);
4369a3
+#else
4369a3
+		error("%s: No module path provided", __func__);
4369a3
 		goto fail;
4369a3
-	*providerp = NULL;
4369a3
-
4369a3
-	if (keyp != NULL)
4369a3
-		*keyp = NULL;
4369a3
+#endif
4369a3
+	} else {
4369a3
+		provider_module = strdup(uri->module_path);
4369a3
+	}
4369a3
 
4369a3
-	if (pkcs11_provider_lookup(provider_id) != NULL) {
4369a3
-		debug("%s: provider already registered: %s",
4369a3
-		    __func__, provider_id);
4369a3
-		goto fail;
4369a3
+	p = xcalloc(1, sizeof(*p));
4369a3
+	p->name = pkcs11_uri_get(uri);
4369a3
+
4369a3
+	if ((m = pkcs11_provider_lookup_module(provider_module)) != NULL
4369a3
+	   && m->valid) {
4369a3
+		debug("%s: provider module already initialized: %s",
4369a3
+		    __func__, provider_module);
4369a3
+		free(provider_module);
4369a3
+		/* Skip the initialization of PKCS#11 module */
4369a3
+		m->refcount++;
4369a3
+		p->module = m;
4369a3
+		p->valid = 1;
4369a3
+		TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
4369a3
+		p->refcount++;	/* add to provider list */
4369a3
+		*providerp = p;
4369a3
+		return 0;
4369a3
+	} else {
4369a3
+		m = xcalloc(1, sizeof(*m));
4369a3
+		p->module = m;
4369a3
+		m->refcount++;
4369a3
 	}
4369a3
+
4369a3
 	/* open shared pkcs11-library */
4369a3
-	if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
4369a3
-		error("dlopen %s failed: %s", provider_id, dlerror());
4369a3
+	if ((handle = dlopen(provider_module, RTLD_NOW)) == NULL) {
4369a3
+		error("dlopen %s failed: %s", provider_module, dlerror());
4369a3
 		goto fail;
4369a3
 	}
4369a3
 	if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
4369a3
 		error("dlsym(C_GetFunctionList) failed: %s", dlerror());
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	p = xcalloc(1, sizeof(*p));
4369a3
-	p->name = xstrdup(provider_id);
4369a3
-	p->handle = handle;
4369a3
+
4369a3
+	p->module->handle = handle;
4369a3
 	/* setup the pkcs11 callbacks */
4369a3
 	if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
4369a3
 		error("C_GetFunctionList for provider %s failed: %lu",
4369a3
-		    provider_id, rv);
4369a3
+		    provider_module, rv);
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	p->function_list = f;
4369a3
+	m->function_list = f;
4369a3
 	if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
4369a3
 		error("C_Initialize for provider %s failed: %lu",
4369a3
-		    provider_id, rv);
4369a3
+		    provider_module, rv);
4369a3
 		goto fail;
4369a3
 	}
4369a3
 	need_finalize = 1;
4369a3
-	if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
4369a3
+	if ((rv = f->C_GetInfo(&m->info)) != CKR_OK) {
4369a3
 		error("C_GetInfo for provider %s failed: %lu",
4369a3
-		    provider_id, rv);
4369a3
+		    provider_module, rv);
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
4369a3
-	rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
4369a3
+	rmspace(m->info.manufacturerID, sizeof(m->info.manufacturerID));
4369a3
+	if (uri->lib_manuf != NULL &&
4369a3
+	    strcmp(uri->lib_manuf, m->info.manufacturerID)) {
4369a3
+		debug("%s: Skipping provider %s not matching library_manufacturer",
4369a3
+		    __func__, m->info.manufacturerID);
4369a3
+		goto fail;
4369a3
+	}
4369a3
+	rmspace(m->info.libraryDescription, sizeof(m->info.libraryDescription));
4369a3
 	debug("provider %s: manufacturerID <%s> cryptokiVersion %d.%d"
4369a3
 	    " libraryDescription <%s> libraryVersion %d.%d",
4369a3
-	    provider_id,
4369a3
-	    p->info.manufacturerID,
4369a3
-	    p->info.cryptokiVersion.major,
4369a3
-	    p->info.cryptokiVersion.minor,
4369a3
-	    p->info.libraryDescription,
4369a3
-	    p->info.libraryVersion.major,
4369a3
-	    p->info.libraryVersion.minor);
4369a3
-	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
4369a3
+	    provider_module,
4369a3
+	    m->info.manufacturerID,
4369a3
+	    m->info.cryptokiVersion.major,
4369a3
+	    m->info.cryptokiVersion.minor,
4369a3
+	    m->info.libraryDescription,
4369a3
+	    m->info.libraryVersion.major,
4369a3
+	    m->info.libraryVersion.minor);
4369a3
+
4369a3
+	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &m->nslots)) != CKR_OK) {
4369a3
 		error("C_GetSlotList failed: %lu", rv);
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	if (p->nslots == 0) {
4369a3
+	if (m->nslots == 0) {
0d83e7
-		error("%s: provider %s returned no slots", __func__,
0d83e7
+		debug("%s: provider %s returned no slots", __func__,
4369a3
-		    provider_id);
4369a3
+		    provider_module);
4369a3
 		ret = -SSH_PKCS11_ERR_NO_SLOTS;
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
4369a3
-	if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
4369a3
+	m->slotlist = xcalloc(m->nslots, sizeof(CK_SLOT_ID));
4369a3
+	if ((rv = f->C_GetSlotList(CK_TRUE, m->slotlist, &m->nslots))
4369a3
 	    != CKR_OK) {
4369a3
 		error("C_GetSlotList for provider %s failed: %lu",
4369a3
-		    provider_id, rv);
4369a3
+		    provider_module, rv);
4369a3
 		goto fail;
4369a3
 	}
4369a3
-	p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
4369a3
 	p->valid = 1;
4369a3
-	nkeys = 0;
4369a3
-	for (i = 0; i < p->nslots; i++) {
4369a3
-		token = &p->slotinfo[i].token;
4369a3
-		if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
4369a3
+	m->slotinfo = xcalloc(m->nslots, sizeof(struct pkcs11_slotinfo));
4369a3
+	m->valid = 1;
4369a3
+	for (i = 0; i < m->nslots; i++) {
4369a3
+		token = &m->slotinfo[i].token;
4369a3
+		if ((rv = f->C_GetTokenInfo(m->slotlist[i], token))
4369a3
 		    != CKR_OK) {
4369a3
 			error("C_GetTokenInfo for provider %s slot %lu "
4369a3
-			    "failed: %lu", provider_id, (unsigned long)i, rv);
4369a3
+			    "failed: %lu", provider_module, (unsigned long)i, rv);
4369a3
+			token->flags = 0;
4369a3
 			continue;
4369a3
 		}
4369a3
+		rmspace(token->label, sizeof(token->label));
4369a3
+		rmspace(token->manufacturerID, sizeof(token->manufacturerID));
4369a3
+		rmspace(token->model, sizeof(token->model));
4369a3
+		rmspace(token->serialNumber, sizeof(token->serialNumber));
4369a3
+	}
4369a3
+	m->module_path = provider_module;
4369a3
+	provider_module = NULL;
4369a3
+
4369a3
+	/* insert unconditionally -- remove if there will be no keys later */
4369a3
+	TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
4369a3
+	p->refcount++;	/* add to provider list */
4369a3
+	*providerp = p;
4369a3
+	return 0;
4369a3
+
4369a3
+fail:
4369a3
+	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
4369a3
+		error("C_Finalize for provider %s failed: %lu",
4369a3
+		    provider_module, rv);
4369a3
+	free(provider_module);
4369a3
+	if (m) {
4369a3
+		free(m->slotlist);
4369a3
+		free(m);
4369a3
+	}
4369a3
+	if (p) {
4369a3
+		free(p->name);
4369a3
+		free(p);
4369a3
+	}
4369a3
+	if (handle)
4369a3
+		dlclose(handle);
4369a3
+	return ret;
4369a3
+}
4369a3
+
4369a3
+/*
4369a3
+ * register a new provider, fails if provider already exists. if
4369a3
+ * keyp is provided, fetch keys.
4369a3
+ */
4369a3
+static int
4369a3
+pkcs11_register_provider_by_uri(struct pkcs11_uri *uri, char *pin,
4369a3
+    struct sshkey ***keyp, struct pkcs11_provider **providerp, CK_ULONG user)
4369a3
+{
4369a3
+	int nkeys;
4369a3
+	int ret = -1;
4369a3
+	struct pkcs11_provider *p = NULL;
4369a3
+	CK_ULONG i;
4369a3
+	CK_TOKEN_INFO *token;
4369a3
+	char *provider_uri = NULL;
4369a3
+
4369a3
+	if (providerp == NULL)
4369a3
+		goto fail;
4369a3
+	*providerp = NULL;
4369a3
+
4369a3
+	if (keyp != NULL)
4369a3
+		*keyp = NULL;
4369a3
+
4369a3
+	if ((ret = pkcs11_initialize_provider(uri, &p)) != 0) {
4369a3
+		goto fail;
4369a3
+	}
4369a3
+
4369a3
+	provider_uri = pkcs11_uri_get(uri);
152122
+	if (pin == NULL && uri->pin != NULL) {
152122
+		pin = uri->pin;
152122
+	}
4369a3
+	nkeys = 0;
4369a3
+	for (i = 0; i < p->module->nslots; i++) {
4369a3
+		token = &p->module->slotinfo[i].token;
4369a3
 		if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
4369a3
 			debug2("%s: ignoring uninitialised token in "
4369a3
 			    "provider %s slot %lu", __func__,
4369a3
-			    provider_id, (unsigned long)i);
4369a3
+			    provider_uri, (unsigned long)i);
4369a3
+			continue;
4369a3
+		}
4369a3
+		if (uri->token != NULL &&
4369a3
+		    strcmp(token->label, uri->token) != 0) {
4369a3
+			debug2("%s: ignoring token not matching label (%s) "
4369a3
+			    "specified by PKCS#11 URI in slot %lu", __func__,
4369a3
+			    token->label, (unsigned long)i);
4369a3
+			continue;
4369a3
+		}
4369a3
+		if (uri->manuf != NULL &&
4369a3
+		    strcmp(token->manufacturerID, uri->manuf) != 0) {
4369a3
+			debug2("%s: ignoring token not matching requrested "
4369a3
+			    "manufacturerID (%s) specified by PKCS#11 URI in "
4369a3
+			    "slot %lu", __func__,
4369a3
+			    token->manufacturerID, (unsigned long)i);
4369a3
 			continue;
4369a3
 		}
4369a3
-		rmspace(token->label, sizeof(token->label));
4369a3
-		rmspace(token->manufacturerID, sizeof(token->manufacturerID));
4369a3
-		rmspace(token->model, sizeof(token->model));
4369a3
-		rmspace(token->serialNumber, sizeof(token->serialNumber));
4369a3
 		debug("provider %s slot %lu: label <%s> manufacturerID <%s> "
4369a3
 		    "model <%s> serial <%s> flags 0x%lx",
4369a3
-		    provider_id, (unsigned long)i,
4369a3
+		    provider_uri, (unsigned long)i,
4369a3
 		    token->label, token->manufacturerID, token->model,
4369a3
 		    token->serialNumber, token->flags);
4369a3
 		/*
4369a3
-		 * open session, login with pin and retrieve public
4369a3
-		 * keys (if keyp is provided)
4369a3
+		 * open session if not yet openend, login with pin and
4369a3
+		 * retrieve public keys (if keyp is provided)
4369a3
 		 */
4369a3
-		if ((ret = pkcs11_open_session(p, i, pin, user)) == 0) {
4369a3
+		if (p->module->slotinfo[i].session != 0 ||
4369a3
+		    (ret = pkcs11_open_session(p, i, pin, user)) == 0) {
4369a3
 			if (keyp == NULL)
4369a3
 				continue;
4369a3
-			pkcs11_fetch_keys(p, i, keyp, &nkeys);
4369a3
-			pkcs11_fetch_certs(p, i, keyp, &nkeys);
4369a3
+			pkcs11_fetch_keys(p, i, keyp, &nkeys, uri);
4369a3
+			pkcs11_fetch_certs(p, i, keyp, &nkeys, uri);
4369a3
+			if (nkeys == 0 && uri->object != NULL) {
4369a3
+				debug3("%s: No keys found. Retrying without label (%s) ",
4369a3
+				    __func__, token->label);
4369a3
+				/* Try once more without the label filter */
4369a3
+				char *label = uri->object;
4369a3
+				uri->object = NULL; /* XXX clone uri? */
4369a3
+				pkcs11_fetch_keys(p, i, keyp, &nkeys, uri);
4369a3
+				pkcs11_fetch_certs(p, i, keyp, &nkeys, uri);
4369a3
+				uri->object = label;
4369a3
+			}
4369a3
 		}
4369a3
 	}
152122
+	pin = NULL; /* Will be cleaned up with URI */
4369a3
 
4369a3
 	/* now owned by caller */
4369a3
 	*providerp = p;
4369a3
 
4369a3
-	TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
4369a3
-	p->refcount++;	/* add to provider list */
4369a3
-
4369a3
+	free(provider_uri);
4369a3
 	return (nkeys);
4369a3
 fail:
4369a3
-	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
4369a3
-		error("C_Finalize for provider %s failed: %lu",
4369a3
-		    provider_id, rv);
4369a3
 	if (p) {
4369a3
-		free(p->name);
4369a3
-		free(p->slotlist);
4369a3
-		free(p->slotinfo);
4369a3
-		free(p);
4369a3
+ 		TAILQ_REMOVE(&pkcs11_providers, p, next);
4369a3
+		pkcs11_provider_unref(p);
4369a3
 	}
4369a3
-	if (handle)
4369a3
-		dlclose(handle);
4369a3
 	return (ret);
4369a3
 }
4369a3
 
4369a3
-/*
4369a3
- * register a new provider and get number of keys hold by the token,
4369a3
- * fails if provider already exists
4369a3
- */
4369a3
+static int
4369a3
+pkcs11_register_provider(char *provider_id, char *pin, struct sshkey ***keyp,
4369a3
+    struct pkcs11_provider **providerp, CK_ULONG user)
4369a3
+{
4369a3
+	struct pkcs11_uri *uri = NULL;
4369a3
+	int r;
4369a3
+
4369a3
+	debug("%s: called, provider_id = %s", __func__, provider_id);
4369a3
+
4369a3
+	uri = pkcs11_uri_init();
4369a3
+	if (uri == NULL)
4369a3
+		fatal("failed to init PKCS#11 URI");
4369a3
+
4369a3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
4369a3
+			fatal("Failed to parse PKCS#11 URI");
4369a3
+	} else {
4369a3
+		uri->module_path = strdup(provider_id);
4369a3
+	}
4369a3
+
4369a3
+	r = pkcs11_register_provider_by_uri(uri, pin, keyp, providerp, user);
4369a3
+	pkcs11_uri_cleanup(uri);
4369a3
+
4369a3
+	return r;
4369a3
+}
4369a3
+
4369a3
 int
4369a3
-pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
4369a3
+pkcs11_add_provider_by_uri(struct pkcs11_uri *uri, char *pin,
4369a3
+    struct sshkey ***keyp)
4369a3
 {
4369a3
-	struct pkcs11_provider *p = NULL;
4369a3
 	int nkeys;
4369a3
+	struct pkcs11_provider *p = NULL;
4369a3
+	char *provider_uri = pkcs11_uri_get(uri);
4369a3
 
4369a3
-	nkeys = pkcs11_register_provider(provider_id, pin, keyp, &p, CKU_USER);
4369a3
+	debug("%s: called, provider_uri = %s", __func__, provider_uri);
4369a3
+
4369a3
+	nkeys = pkcs11_register_provider_by_uri(uri, pin, keyp, &p, CKU_USER);
4369a3
 
4369a3
 	/* no keys found or some other error, de-register provider */
4369a3
 	if (nkeys <= 0 && p != NULL) {
4369a3
@@ -1611,7 +1912,36 @@ pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
4369a3
 	}
4369a3
 	if (nkeys == 0)
4369a3
 		debug("%s: provider %s returned no keys", __func__,
4369a3
-		    provider_id);
4369a3
+		    provider_uri);
4369a3
+
4369a3
+	free(provider_uri);
4369a3
+	return nkeys;
4369a3
+}
4369a3
+
4369a3
+/*
4369a3
+ * register a new provider and get number of keys hold by the token,
4369a3
+ * fails if provider already exists
4369a3
+ */
4369a3
+int
4369a3
+pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
4369a3
+{
4369a3
+	struct pkcs11_uri *uri;
4369a3
+	int nkeys;
4369a3
+
4369a3
+	uri = pkcs11_uri_init();
4369a3
+	if (uri == NULL)
4369a3
+		fatal("Failed to init PCKS#11 URI");
4369a3
+
4369a3
+	if (strlen(provider_id) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+	    strncmp(provider_id, PKCS11_URI_SCHEME, strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+		if (pkcs11_uri_parse(provider_id, uri) != 0)
4369a3
+			fatal("Failed to parse PKCS#11 URI");
4369a3
+	} else {
4369a3
+		uri->module_path = strdup(provider_id);
4369a3
+	}
4369a3
+
4369a3
+	nkeys = pkcs11_add_provider_by_uri(uri, pin, keyp);
4369a3
+	pkcs11_uri_cleanup(uri);
4369a3
 
4369a3
 	return (nkeys);
4369a3
 }
4369a3
@@ -1633,8 +1963,7 @@ pkcs11_gakp(char *provider_id, char *pin, unsigned int slotidx, char *label,
4369a3
 
4369a3
 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL)
4369a3
 		debug("%s: provider \"%s\" available", __func__, provider_id);
4369a3
-	else if ((ret = pkcs11_register_provider(provider_id, pin, NULL, &p,
4369a3
-	    CKU_SO)) < 0) {
4369a3
+	else if ((rv = pkcs11_register_provider(provider_id, pin, NULL, &p, CKU_SO)) != 0) {
4369a3
 		debug("%s: could not register provider %s", __func__,
4369a3
 		    provider_id);
4369a3
 		goto out;
4369a3
@@ -1705,8 +2034,7 @@ pkcs11_destroy_keypair(char *provider_id, char *pin, unsigned long slotidx,
4369a3
 
4369a3
 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
4369a3
 		debug("%s: using provider \"%s\"", __func__, provider_id);
4369a3
-	} else if (pkcs11_register_provider(provider_id, pin, NULL, &p,
4369a3
-	    CKU_SO) < 0) {
4369a3
+	} else if ((rv = pkcs11_register_provider(provider_id, pin, NULL, &p, CKU_SO)) != 0) {
4369a3
 		debug("%s: could not register provider %s", __func__,
4369a3
 		    provider_id);
4369a3
 		goto out;
4369a3
diff --git a/ssh-pkcs11.h b/ssh-pkcs11.h
4369a3
index b9038450..5a855338 100644
4369a3
--- a/ssh-pkcs11.h
4369a3
+++ b/ssh-pkcs11.h
4369a3
@@ -22,10 +22,14 @@
4369a3
 #define	SSH_PKCS11_ERR_PIN_REQUIRED		4
4369a3
 #define	SSH_PKCS11_ERR_PIN_LOCKED		5
4369a3
 
4369a3
+#include "ssh-pkcs11-uri.h"
4369a3
+
4369a3
 int	pkcs11_init(int);
4369a3
 void	pkcs11_terminate(void);
4369a3
 int	pkcs11_add_provider(char *, char *, struct sshkey ***);
4369a3
+int	pkcs11_add_provider_by_uri(struct pkcs11_uri *, char *, struct sshkey ***);
4369a3
 int	pkcs11_del_provider(char *);
4369a3
+int	pkcs11_uri_write(const struct sshkey *, FILE *);
4369a3
 #ifdef WITH_PKCS11_KEYGEN
4369a3
 struct sshkey *
4369a3
 	pkcs11_gakp(char *, char *, unsigned int, char *, unsigned int,
4369a3
diff --git a/ssh.c b/ssh.c
4369a3
index 91e7c351..47f4f299 100644
4369a3
--- a/ssh.c
4369a3
+++ b/ssh.c
4369a3
@@ -772,6 +772,14 @@ main(int ac, char **av)
4369a3
 			options.gss_deleg_creds = 1;
4369a3
 			break;
4369a3
 		case 'i':
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+			if (strlen(optarg) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+			    strncmp(optarg, PKCS11_URI_SCHEME,
4369a3
+			    strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+				add_identity_file(&options, NULL, optarg, 1);
4369a3
+				break;
4369a3
+			}
4369a3
+#endif
4369a3
 			p = tilde_expand_filename(optarg, getuid());
4369a3
 			if (stat(p, &st) < 0)
4369a3
 				fprintf(stderr, "Warning: Identity file %s "
4369a3
@@ -1521,6 +1529,7 @@ main(int ac, char **av)
4369a3
 		free(options.certificate_files[i]);
4369a3
 		options.certificate_files[i] = NULL;
4369a3
 	}
4369a3
+	pkcs11_terminate();
4369a3
 
4369a3
  skip_connect:
4369a3
 	exit_status = ssh_session2(ssh, pw);
4369a3
@@ -1994,6 +2003,45 @@ ssh_session2(struct ssh *ssh, struct passwd *pw)
4369a3
 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
4369a3
 }
4369a3
 
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+static void
4369a3
+load_pkcs11_identity(char *pkcs11_uri, char *identity_files[],
4369a3
+    struct sshkey *identity_keys[], int *n_ids)
4369a3
+{
4369a3
+	int nkeys, i;
4369a3
+	struct sshkey **keys;
4369a3
+	struct pkcs11_uri *uri;
4369a3
+
4369a3
+	debug("identity file '%s' from pkcs#11", pkcs11_uri);
4369a3
+	uri = pkcs11_uri_init();
4369a3
+	if (uri == NULL)
4369a3
+		fatal("Failed to init PCKS#11 URI");
4369a3
+
4369a3
+	if (pkcs11_uri_parse(pkcs11_uri, uri) != 0)
4369a3
+	fatal("Failed to parse PKCS#11 URI %s", pkcs11_uri);
4369a3
+
4369a3
+	/* we need to merge URI and provider together */
4369a3
+	if (options.pkcs11_provider != NULL && uri->module_path == NULL)
4369a3
+		uri->module_path = strdup(options.pkcs11_provider);
4369a3
+
4369a3
+	if (options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
4369a3
+	    (nkeys = pkcs11_add_provider_by_uri(uri, NULL, &keys)) > 0) {
4369a3
+		for (i = 0; i < nkeys; i++) {
4369a3
+			if (*n_ids >= SSH_MAX_IDENTITY_FILES) {
4369a3
+				sshkey_free(keys[i]);
4369a3
+				continue;
4369a3
+			}
4369a3
+			identity_keys[*n_ids] = keys[i];
4369a3
+			identity_files[*n_ids] = pkcs11_uri_get(uri);
4369a3
+			(*n_ids)++;
4369a3
+		}
4369a3
+		free(keys);
4369a3
+	}
4369a3
+
4369a3
+	pkcs11_uri_cleanup(uri);
4369a3
+}
4369a3
+#endif /* ENABLE_PKCS11 */
4369a3
+
4369a3
 /* Loads all IdentityFile and CertificateFile keys */
4369a3
 static void
4369a3
 load_public_identity_files(struct passwd *pw)
4369a3
@@ -2008,10 +2056,6 @@ load_public_identity_files(struct passwd *pw)
4369a3
 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
4369a3
 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
4369a3
 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
4369a3
-#ifdef ENABLE_PKCS11
4369a3
-	struct sshkey **keys;
4369a3
-	int nkeys;
4369a3
-#endif /* PKCS11 */
4369a3
 
4369a3
 	n_ids = n_certs = 0;
4369a3
 	memset(identity_files, 0, sizeof(identity_files));
4369a3
@@ -2024,32 +2068,46 @@ load_public_identity_files(struct passwd *pw)
4369a3
 	    sizeof(certificate_file_userprovided));
4369a3
 
4369a3
 #ifdef ENABLE_PKCS11
4369a3
-	if (options.pkcs11_provider != NULL &&
4369a3
-	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
4369a3
-	    (pkcs11_init(!options.batch_mode) == 0) &&
4369a3
-	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
4369a3
-	    &keys)) > 0) {
4369a3
-		for (i = 0; i < nkeys; i++) {
4369a3
-			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
4369a3
-				sshkey_free(keys[i]);
4369a3
-				continue;
4369a3
-			}
4369a3
-			identity_keys[n_ids] = keys[i];
4369a3
-			identity_files[n_ids] =
4369a3
-			    xstrdup(options.pkcs11_provider); /* XXX */
4369a3
-			n_ids++;
4369a3
-		}
4369a3
-		free(keys);
4369a3
+	/* handle fallback from PKCS11Provider option */
4369a3
+	pkcs11_init(!options.batch_mode);
4369a3
+
4369a3
+	if (options.pkcs11_provider != NULL) {
4369a3
+		struct pkcs11_uri *uri;
4369a3
+
4369a3
+		uri = pkcs11_uri_init();
4369a3
+		if (uri == NULL)
4369a3
+			fatal("Failed to init PCKS#11 URI");
4369a3
+
4369a3
+		/* Construct simple PKCS#11 URI to simplify access */
4369a3
+		uri->module_path = strdup(options.pkcs11_provider);
4369a3
+
4369a3
+		/* Add it as any other IdentityFile */
4369a3
+		cp = pkcs11_uri_get(uri);
4369a3
+		add_identity_file(&options, NULL, cp, 1);
4369a3
+		free(cp);
4369a3
+
4369a3
+		pkcs11_uri_cleanup(uri);
4369a3
 	}
4369a3
 #endif /* ENABLE_PKCS11 */
4369a3
 	for (i = 0; i < options.num_identity_files; i++) {
4369a3
+		char *name = options.identity_files[i];
4369a3
 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
4369a3
-		    strcasecmp(options.identity_files[i], "none") == 0) {
4369a3
+		    strcasecmp(name, "none") == 0) {
4369a3
 			free(options.identity_files[i]);
4369a3
 			options.identity_files[i] = NULL;
4369a3
 			continue;
4369a3
 		}
4369a3
-		cp = tilde_expand_filename(options.identity_files[i], getuid());
4369a3
+#ifdef ENABLE_PKCS11
4369a3
+		if (strlen(name) >= strlen(PKCS11_URI_SCHEME) &&
4369a3
+		    strncmp(name, PKCS11_URI_SCHEME,
4369a3
+		    strlen(PKCS11_URI_SCHEME)) == 0) {
4369a3
+			load_pkcs11_identity(name, identity_files,
4369a3
+			    identity_keys, &n_ids);
4369a3
+			free(options.identity_files[i]);
4369a3
+			continue;
4369a3
+		}
4369a3
+#endif /* ENABLE_PKCS11 */
4369a3
+		cp = tilde_expand_filename(name, getuid());
4369a3
 		filename = percent_expand(cp, "d", pw->pw_dir,
4369a3
 		    "u", pw->pw_name, "l", thishost, "h", host,
4369a3
 		    "r", options.user, (char *)NULL);
4369a3
diff --git a/ssh_config.5 b/ssh_config.5
4369a3
index 41262963..a211034e 100644
4369a3
--- a/ssh_config.5
4369a3
+++ b/ssh_config.5
4369a3
@@ -952,6 +952,21 @@ may also be used in conjunction with
4369a3
 .Cm CertificateFile
4369a3
 in order to provide any certificate also needed for authentication with
4369a3
 the identity.
4369a3
+.Pp
4369a3
+The authentication identity can be also specified in a form of PKCS#11 URI
4369a3
+starting with a string
4369a3
+.Cm pkcs11: .
4369a3
+There is supported a subset of the PKCS#11 URI as defined
4369a3
+in RFC 7512 (implemented path arguments
4369a3
+.Cm id ,
4369a3
+.Cm manufacturer ,
4369a3
+.Cm object ,
4369a3
+.Cm token
4369a3
+and query arguments
4369a3
+.Cm module-path
4369a3
+and
4369a3
+.Cm pin-value
4369a3
+). The URI can not be in quotes.
4369a3
 .It Cm IgnoreUnknown
4369a3
 Specifies a pattern-list of unknown options to be ignored if they are
4369a3
 encountered in configuration parsing.
4369a3
commit 1efe98998408593861fdcd4da392dd10820f0fde
4369a3
Author: Jakub Jelen <jjelen@redhat.com>
4369a3
Date:   Wed Jun 12 14:30:30 2019 +0200
4369a3
4369a3
    Allow to specify the pin also for the ssh-add
4369a3
4369a3
diff --git a/ssh-add.c b/ssh-add.c
4369a3
index f039e00e..adc4e5c9 100644
4369a3
--- a/ssh-add.c
4369a3
+++ b/ssh-add.c
4369a3
@@ -190,20 +190,28 @@ delete_all(int agent_fd, int qflag)
4369a3
 }
4369a3
 
4369a3
 #ifdef ENABLE_PKCS11
4369a3
-static int update_card(int, int, const char *, int);
4369a3
+static int update_card(int, int, const char *, int, char *);
4369a3
 
4369a3
 int
4369a3
 update_pkcs11_uri(int agent_fd, int adding, const char *pkcs11_uri, int qflag)
4369a3
 {
4369a3
+	char *pin = NULL;
4369a3
 	struct pkcs11_uri *uri;
4369a3
 
4369a3
 	/* dry-run parse to make sure the URI is valid and to report errors */
4369a3
 	uri = pkcs11_uri_init();
4369a3
 	if (pkcs11_uri_parse((char *) pkcs11_uri, uri) != 0)
4369a3
 		fatal("Failed to parse PKCS#11 URI");
4369a3
+	if (uri->pin != NULL) {
4369a3
+		pin = strdup(uri->pin);
4369a3
+		if (pin == NULL) {
4369a3
+			fatal("Failed to dupplicate string");
4369a3
+		}
4369a3
+		/* pin is freed in the update_card() */
4369a3
+	}
4369a3
 	pkcs11_uri_cleanup(uri);
4369a3
 
4369a3
-	return update_card(agent_fd, adding, pkcs11_uri, qflag);
4369a3
+	return update_card(agent_fd, adding, pkcs11_uri, qflag, pin);
4369a3
 }
4369a3
 #endif
4369a3
 
4369a3
@@ -409,12 +417,11 @@ add_file(int agent_fd, const char *filename, int key_only, int qflag)
4369a3
 }
4369a3
 
4369a3
 static int
4369a3
-update_card(int agent_fd, int add, const char *id, int qflag)
4369a3
+update_card(int agent_fd, int add, const char *id, int qflag, char *pin)
4369a3
 {
4369a3
-	char *pin = NULL;
4369a3
 	int r, ret = -1;
4369a3
 
4369a3
-	if (add) {
4369a3
+	if (add && pin == NULL) {
4369a3
 		if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
4369a3
 		    RP_ALLOW_STDIN)) == NULL)
4369a3
 			return -1;
4369a3
@@ -734,7 +741,7 @@ main(int argc, char **argv)
4369a3
 	}
4369a3
 	if (pkcs11provider != NULL) {
4369a3
 		if (update_card(agent_fd, !deleting, pkcs11provider,
4369a3
-		    qflag) == -1)
4369a3
+		    qflag, NULL) == -1)
4369a3
 			ret = 1;
4369a3
 		goto done;
4369a3
 	}