bmh10 / rpms / openssh

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