xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-pkcs11.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: ssh-pkcs11.c,v 1.10 2016/03/11 01:55:00 christos Exp $	*/
2 /* $OpenBSD: ssh-pkcs11.c,v 1.22 2016/02/12 00:20:30 djm Exp $ */
3 
4 /*
5  * Copyright (c) 2010 Markus Friedl.  All rights reserved.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 #include "includes.h"
20 __RCSID("$NetBSD: ssh-pkcs11.c,v 1.10 2016/03/11 01:55:00 christos Exp $");
21 
22 #include <sys/types.h>
23 #include <sys/queue.h>
24 #include <sys/time.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 
28 #include <string.h>
29 #include <dlfcn.h>
30 
31 #include <openssl/x509.h>
32 
33 #define CRYPTOKI_COMPAT
34 #include "pkcs11.h"
35 
36 #include "log.h"
37 #include "misc.h"
38 #include "sshkey.h"
39 #include "ssh-pkcs11.h"
40 #include "xmalloc.h"
41 
42 struct pkcs11_slotinfo {
43 	CK_TOKEN_INFO		token;
44 	CK_SESSION_HANDLE	session;
45 	int			logged_in;
46 };
47 
48 struct pkcs11_provider {
49 	char			*name;
50 	void			*handle;
51 	CK_FUNCTION_LIST	*function_list;
52 	CK_INFO			info;
53 	CK_ULONG		nslots;
54 	CK_SLOT_ID		*slotlist;
55 	struct pkcs11_slotinfo	*slotinfo;
56 	int			valid;
57 	int			refcount;
58 	TAILQ_ENTRY(pkcs11_provider) next;
59 };
60 
61 TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
62 
63 struct pkcs11_key {
64 	struct pkcs11_provider	*provider;
65 	CK_ULONG		slotidx;
66 	int			(*orig_finish)(RSA *rsa);
67 	RSA_METHOD		rsa_method;
68 	char			*keyid;
69 	int			keyid_len;
70 };
71 
72 int pkcs11_interactive = 0;
73 
74 int
75 pkcs11_init(int interactive)
76 {
77 	pkcs11_interactive = interactive;
78 	TAILQ_INIT(&pkcs11_providers);
79 	return (0);
80 }
81 
82 /*
83  * finalize a provider shared libarary, it's no longer usable.
84  * however, there might still be keys referencing this provider,
85  * so the actuall freeing of memory is handled by pkcs11_provider_unref().
86  * this is called when a provider gets unregistered.
87  */
88 static void
89 pkcs11_provider_finalize(struct pkcs11_provider *p)
90 {
91 	CK_RV rv;
92 	CK_ULONG i;
93 
94 	debug("pkcs11_provider_finalize: %p refcount %d valid %d",
95 	    p, p->refcount, p->valid);
96 	if (!p->valid)
97 		return;
98 	for (i = 0; i < p->nslots; i++) {
99 		if (p->slotinfo[i].session &&
100 		    (rv = p->function_list->C_CloseSession(
101 		    p->slotinfo[i].session)) != CKR_OK)
102 			error("C_CloseSession failed: %lu", rv);
103 	}
104 	if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
105 		error("C_Finalize failed: %lu", rv);
106 	p->valid = 0;
107 	p->function_list = NULL;
108 #ifdef HAVE_DLOPEN
109 	dlclose(p->handle);
110 #endif
111 }
112 
113 /*
114  * remove a reference to the provider.
115  * called when a key gets destroyed or when the provider is unregistered.
116  */
117 static void
118 pkcs11_provider_unref(struct pkcs11_provider *p)
119 {
120 	debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
121 	if (--p->refcount <= 0) {
122 		if (p->valid)
123 			error("pkcs11_provider_unref: %p still valid", p);
124 		free(p->slotlist);
125 		free(p->slotinfo);
126 		free(p);
127 	}
128 }
129 
130 /* unregister all providers, keys might still point to the providers */
131 void
132 pkcs11_terminate(void)
133 {
134 	struct pkcs11_provider *p;
135 
136 	while ((p = TAILQ_FIRST(&pkcs11_providers)) != NULL) {
137 		TAILQ_REMOVE(&pkcs11_providers, p, next);
138 		pkcs11_provider_finalize(p);
139 		pkcs11_provider_unref(p);
140 	}
141 }
142 
143 /* lookup provider by name */
144 static struct pkcs11_provider *
145 pkcs11_provider_lookup(char *provider_id)
146 {
147 	struct pkcs11_provider *p;
148 
149 	TAILQ_FOREACH(p, &pkcs11_providers, next) {
150 		debug("check %p %s", p, p->name);
151 		if (!strcmp(provider_id, p->name))
152 			return (p);
153 	}
154 	return (NULL);
155 }
156 
157 /* unregister provider by name */
158 int
159 pkcs11_del_provider(char *provider_id)
160 {
161 	struct pkcs11_provider *p;
162 
163 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
164 		TAILQ_REMOVE(&pkcs11_providers, p, next);
165 		pkcs11_provider_finalize(p);
166 		pkcs11_provider_unref(p);
167 		return (0);
168 	}
169 	return (-1);
170 }
171 
172 #ifdef HAVE_DLOPEN
173 /* openssl callback for freeing an RSA key */
174 static int
175 pkcs11_rsa_finish(RSA *rsa)
176 {
177 	struct pkcs11_key	*k11;
178 	int rv = -1;
179 
180 	if ((k11 = RSA_get_app_data(rsa)) != NULL) {
181 		if (k11->orig_finish)
182 			rv = k11->orig_finish(rsa);
183 		if (k11->provider)
184 			pkcs11_provider_unref(k11->provider);
185 		free(k11->keyid);
186 		free(k11);
187 	}
188 	return (rv);
189 }
190 
191 /* find a single 'obj' for given attributes */
192 static int
193 pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
194     CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
195 {
196 	CK_FUNCTION_LIST	*f;
197 	CK_SESSION_HANDLE	session;
198 	CK_ULONG		nfound = 0;
199 	CK_RV			rv;
200 	int			ret = -1;
201 
202 	f = p->function_list;
203 	session = p->slotinfo[slotidx].session;
204 	if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
205 		error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
206 		return (-1);
207 	}
208 	if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
209 	    nfound != 1) {
210 		debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
211 		    nfound, nattr, rv);
212 	} else
213 		ret = 0;
214 	if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
215 		error("C_FindObjectsFinal failed: %lu", rv);
216 	return (ret);
217 }
218 
219 /* openssl callback doing the actual signing operation */
220 static int
221 pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
222     int padding)
223 {
224 	struct pkcs11_key	*k11;
225 	struct pkcs11_slotinfo	*si;
226 	CK_FUNCTION_LIST	*f;
227 	CK_OBJECT_HANDLE	obj;
228 	CK_ULONG		tlen = 0;
229 	CK_RV			rv;
230 	CK_OBJECT_CLASS		private_key_class = CKO_PRIVATE_KEY;
231 	CK_BBOOL		true_val = CK_TRUE;
232 	CK_MECHANISM		mech = {
233 		CKM_RSA_PKCS, NULL_PTR, 0
234 	};
235 	CK_ATTRIBUTE		key_filter[] = {
236 		{CKA_CLASS, &private_key_class, sizeof(private_key_class) },
237 		{CKA_ID, NULL, 0},
238 		{CKA_SIGN, &true_val, sizeof(true_val) }
239 	};
240 	char			*pin = NULL, prompt[1024];
241 	int			rval = -1;
242 
243 	if ((k11 = RSA_get_app_data(rsa)) == NULL) {
244 		error("RSA_get_app_data failed for rsa %p", rsa);
245 		return (-1);
246 	}
247 	if (!k11->provider || !k11->provider->valid) {
248 		error("no pkcs11 (valid) provider for rsa %p", rsa);
249 		return (-1);
250 	}
251 	f = k11->provider->function_list;
252 	si = &k11->provider->slotinfo[k11->slotidx];
253 	if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
254 		if (!pkcs11_interactive) {
255 			error("need pin entry%s", (si->token.flags &
256 			    CKF_PROTECTED_AUTHENTICATION_PATH) ?
257 			    " on reader keypad" : "");
258 			return (-1);
259 		}
260 		if (si->token.flags & CKF_PROTECTED_AUTHENTICATION_PATH)
261 			verbose("Deferring PIN entry to reader keypad.");
262 		else {
263 			snprintf(prompt, sizeof(prompt),
264 			    "Enter PIN for '%s': ", si->token.label);
265 			pin = read_passphrase(prompt, RP_ALLOW_EOF);
266 			if (pin == NULL)
267 				return (-1);	/* bail out */
268 		}
269 		rv = f->C_Login(si->session, CKU_USER, (u_char *)pin,
270 		    (pin != NULL) ? strlen(pin) : 0);
271 		if (pin != NULL) {
272 			explicit_bzero(pin, strlen(pin));
273 			free(pin);
274 		}
275 		if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
276 			error("C_Login failed: %lu", rv);
277 			return (-1);
278 		}
279 		si->logged_in = 1;
280 	}
281 	key_filter[1].pValue = k11->keyid;
282 	key_filter[1].ulValueLen = k11->keyid_len;
283 	/* try to find object w/CKA_SIGN first, retry w/o */
284 	if (pkcs11_find(k11->provider, k11->slotidx, key_filter, 3, &obj) < 0 &&
285 	    pkcs11_find(k11->provider, k11->slotidx, key_filter, 2, &obj) < 0) {
286 		error("cannot find private key");
287 	} else if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
288 		error("C_SignInit failed: %lu", rv);
289 	} else {
290 		/* XXX handle CKR_BUFFER_TOO_SMALL */
291 		tlen = RSA_size(rsa);
292 		rv = f->C_Sign(si->session, __UNCONST(from), flen, to, &tlen);
293 		if (rv == CKR_OK)
294 			rval = tlen;
295 		else
296 			error("C_Sign failed: %lu", rv);
297 	}
298 	return (rval);
299 }
300 
301 static int
302 pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
303     int padding)
304 {
305 	return (-1);
306 }
307 
308 /* redirect private key operations for rsa key to pkcs11 token */
309 static int
310 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
311     CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
312 {
313 	struct pkcs11_key	*k11;
314 	const RSA_METHOD	*def = RSA_get_default_method();
315 
316 	k11 = xcalloc(1, sizeof(*k11));
317 	k11->provider = provider;
318 	provider->refcount++;	/* provider referenced by RSA key */
319 	k11->slotidx = slotidx;
320 	/* identify key object on smartcard */
321 	k11->keyid_len = keyid_attrib->ulValueLen;
322 	if (k11->keyid_len > 0) {
323 		k11->keyid = xmalloc(k11->keyid_len);
324 		memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
325 	}
326 	k11->orig_finish = def->finish;
327 	memcpy(&k11->rsa_method, def, sizeof(k11->rsa_method));
328 	k11->rsa_method.name = "pkcs11";
329 	k11->rsa_method.rsa_priv_enc = pkcs11_rsa_private_encrypt;
330 	k11->rsa_method.rsa_priv_dec = pkcs11_rsa_private_decrypt;
331 	k11->rsa_method.finish = pkcs11_rsa_finish;
332 	RSA_set_method(rsa, &k11->rsa_method);
333 	RSA_set_app_data(rsa, k11);
334 	return (0);
335 }
336 
337 /* remove trailing spaces */
338 static void
339 rmspace(u_char *buf, size_t len)
340 {
341 	size_t i;
342 
343 	if (!len)
344 		return;
345 	for (i = len - 1;  i > 0; i--)
346 		if (i == len - 1 || buf[i] == ' ')
347 			buf[i] = '\0';
348 		else
349 			break;
350 }
351 
352 /*
353  * open a pkcs11 session and login if required.
354  * if pin == NULL we delay login until key use
355  */
356 static int
357 pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
358 {
359 	CK_RV			rv;
360 	CK_FUNCTION_LIST	*f;
361 	CK_SESSION_HANDLE	session;
362 	int			login_required;
363 
364 	f = p->function_list;
365 	login_required = p->slotinfo[slotidx].token.flags & CKF_LOGIN_REQUIRED;
366 	if (pin && login_required && !strlen(pin)) {
367 		error("pin required");
368 		return (-1);
369 	}
370 	if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
371 	    CKF_SERIAL_SESSION, NULL, NULL, &session))
372 	    != CKR_OK) {
373 		error("C_OpenSession failed: %lu", rv);
374 		return (-1);
375 	}
376 	if (login_required && pin) {
377 		rv = f->C_Login(session, CKU_USER,
378 		    (u_char *)pin, strlen(pin));
379 		if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
380 			error("C_Login failed: %lu", rv);
381 			if ((rv = f->C_CloseSession(session)) != CKR_OK)
382 				error("C_CloseSession failed: %lu", rv);
383 			return (-1);
384 		}
385 		p->slotinfo[slotidx].logged_in = 1;
386 	}
387 	p->slotinfo[slotidx].session = session;
388 	return (0);
389 }
390 
391 /*
392  * lookup public keys for token in slot identified by slotidx,
393  * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
394  * keysp points to an (possibly empty) array with *nkeys keys.
395  */
396 static int pkcs11_fetch_keys_filter(struct pkcs11_provider *, CK_ULONG,
397     CK_ATTRIBUTE [], CK_ATTRIBUTE [3], struct sshkey ***, int *)
398 	__attribute__((__bounded__(__minbytes__,4, 3 * sizeof(CK_ATTRIBUTE))));
399 
400 static int
401 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
402     struct sshkey ***keysp, int *nkeys)
403 {
404 	CK_OBJECT_CLASS		pubkey_class = CKO_PUBLIC_KEY;
405 	CK_OBJECT_CLASS		cert_class = CKO_CERTIFICATE;
406 	CK_ATTRIBUTE		pubkey_filter[] = {
407 		{ CKA_CLASS, &pubkey_class, sizeof(pubkey_class) }
408 	};
409 	CK_ATTRIBUTE		cert_filter[] = {
410 		{ CKA_CLASS, &cert_class, sizeof(cert_class) }
411 	};
412 	CK_ATTRIBUTE		pubkey_attribs[] = {
413 		{ CKA_ID, NULL, 0 },
414 		{ CKA_MODULUS, NULL, 0 },
415 		{ CKA_PUBLIC_EXPONENT, NULL, 0 }
416 	};
417 	CK_ATTRIBUTE		cert_attribs[] = {
418 		{ CKA_ID, NULL, 0 },
419 		{ CKA_SUBJECT, NULL, 0 },
420 		{ CKA_VALUE, NULL, 0 }
421 	};
422 
423 	if (pkcs11_fetch_keys_filter(p, slotidx, pubkey_filter, pubkey_attribs,
424 	    keysp, nkeys) < 0 ||
425 	    pkcs11_fetch_keys_filter(p, slotidx, cert_filter, cert_attribs,
426 	    keysp, nkeys) < 0)
427 		return (-1);
428 	return (0);
429 }
430 
431 static int
432 pkcs11_key_included(struct sshkey ***keysp, int *nkeys, struct sshkey *key)
433 {
434 	int i;
435 
436 	for (i = 0; i < *nkeys; i++)
437 		if (sshkey_equal(key, (*keysp)[i]))
438 			return (1);
439 	return (0);
440 }
441 
442 static int
443 pkcs11_fetch_keys_filter(struct pkcs11_provider *p, CK_ULONG slotidx,
444     CK_ATTRIBUTE filter[], CK_ATTRIBUTE attribs[3],
445     struct sshkey ***keysp, int *nkeys)
446 {
447 	struct sshkey		*key;
448 	RSA			*rsa;
449 	X509 			*x509;
450 	EVP_PKEY		*evp;
451 	int			i;
452 	const u_char		*cp;
453 	CK_RV			rv;
454 	CK_OBJECT_HANDLE	obj;
455 	CK_ULONG		nfound;
456 	CK_SESSION_HANDLE	session;
457 	CK_FUNCTION_LIST	*f;
458 
459 	f = p->function_list;
460 	session = p->slotinfo[slotidx].session;
461 	/* setup a filter the looks for public keys */
462 	if ((rv = f->C_FindObjectsInit(session, filter, 1)) != CKR_OK) {
463 		error("C_FindObjectsInit failed: %lu", rv);
464 		return (-1);
465 	}
466 	while (1) {
467 		/* XXX 3 attributes in attribs[] */
468 		for (i = 0; i < 3; i++) {
469 			attribs[i].pValue = NULL;
470 			attribs[i].ulValueLen = 0;
471 		}
472 		if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
473 		    || nfound == 0)
474 			break;
475 		/* found a key, so figure out size of the attributes */
476 		if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
477 		    != CKR_OK) {
478 			error("C_GetAttributeValue failed: %lu", rv);
479 			continue;
480 		}
481 		/*
482 		 * Allow CKA_ID (always first attribute) to be empty, but
483 		 * ensure that none of the others are zero length.
484 		 * XXX assumes CKA_ID is always first.
485 		 */
486 		if (attribs[1].ulValueLen == 0 ||
487 		    attribs[2].ulValueLen == 0) {
488 			continue;
489 		}
490 		/* allocate buffers for attributes */
491 		for (i = 0; i < 3; i++) {
492 			if (attribs[i].ulValueLen > 0) {
493 				attribs[i].pValue = xmalloc(
494 				    attribs[i].ulValueLen);
495 			}
496 		}
497 
498 		/*
499 		 * retrieve ID, modulus and public exponent of RSA key,
500 		 * or ID, subject and value for certificates.
501 		 */
502 		rsa = NULL;
503 		if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
504 		    != CKR_OK) {
505 			error("C_GetAttributeValue failed: %lu", rv);
506 		} else if (attribs[1].type == CKA_MODULUS ) {
507 			if ((rsa = RSA_new()) == NULL) {
508 				error("RSA_new failed");
509 			} else {
510 				rsa->n = BN_bin2bn(attribs[1].pValue,
511 				    attribs[1].ulValueLen, NULL);
512 				rsa->e = BN_bin2bn(attribs[2].pValue,
513 				    attribs[2].ulValueLen, NULL);
514 			}
515 		} else {
516 			cp = attribs[2].pValue;
517 			if ((x509 = X509_new()) == NULL) {
518 				error("X509_new failed");
519 			} else if (d2i_X509(&x509, &cp, attribs[2].ulValueLen)
520 			    == NULL) {
521 				error("d2i_X509 failed");
522 			} else if ((evp = X509_get_pubkey(x509)) == NULL ||
523 			    evp->type != EVP_PKEY_RSA ||
524 			    evp->pkey.rsa == NULL) {
525 				debug("X509_get_pubkey failed or no rsa");
526 			} else if ((rsa = RSAPublicKey_dup(evp->pkey.rsa))
527 			    == NULL) {
528 				error("RSAPublicKey_dup");
529 			}
530 			if (x509)
531 				X509_free(x509);
532 		}
533 		if (rsa && rsa->n && rsa->e &&
534 		    pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
535 			key = sshkey_new(KEY_UNSPEC);
536 			key->rsa = rsa;
537 			key->type = KEY_RSA;
538 			key->flags |= SSHKEY_FLAG_EXT;
539 			if (pkcs11_key_included(keysp, nkeys, key)) {
540 				sshkey_free(key);
541 			} else {
542 				/* expand key array and add key */
543 				*keysp = xreallocarray(*keysp, *nkeys + 1,
544 				    sizeof(struct sshkey *));
545 				(*keysp)[*nkeys] = key;
546 				*nkeys = *nkeys + 1;
547 				debug("have %d keys", *nkeys);
548 			}
549 		} else if (rsa) {
550 			RSA_free(rsa);
551 		}
552 		for (i = 0; i < 3; i++)
553 			free(attribs[i].pValue);
554 	}
555 	if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
556 		error("C_FindObjectsFinal failed: %lu", rv);
557 	return (0);
558 }
559 
560 /* register a new provider, fails if provider already exists */
561 int
562 pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
563 {
564 	int nkeys, need_finalize = 0;
565 	struct pkcs11_provider *p = NULL;
566 	void *handle = NULL;
567 	CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
568 	CK_RV rv;
569 	CK_FUNCTION_LIST *f = NULL;
570 	CK_TOKEN_INFO *token;
571 	CK_ULONG i;
572 
573 	*keyp = NULL;
574 	if (pkcs11_provider_lookup(provider_id) != NULL) {
575 		error("provider already registered: %s", provider_id);
576 		goto fail;
577 	}
578 	/* open shared pkcs11-libarary */
579 	if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
580 		error("dlopen %s failed: %s", provider_id, dlerror());
581 		goto fail;
582 	}
583 	if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
584 		error("dlsym(C_GetFunctionList) failed: %s", dlerror());
585 		goto fail;
586 	}
587 	p = xcalloc(1, sizeof(*p));
588 	p->name = xstrdup(provider_id);
589 	p->handle = handle;
590 	/* setup the pkcs11 callbacks */
591 	if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
592 		error("C_GetFunctionList failed: %lu", rv);
593 		goto fail;
594 	}
595 	p->function_list = f;
596 	if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
597 		error("C_Initialize failed: %lu", rv);
598 		goto fail;
599 	}
600 	need_finalize = 1;
601 	if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
602 		error("C_GetInfo failed: %lu", rv);
603 		goto fail;
604 	}
605 	rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
606 	rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
607 	debug("manufacturerID <%s> cryptokiVersion %d.%d"
608 	    " libraryDescription <%s> libraryVersion %d.%d",
609 	    p->info.manufacturerID,
610 	    p->info.cryptokiVersion.major,
611 	    p->info.cryptokiVersion.minor,
612 	    p->info.libraryDescription,
613 	    p->info.libraryVersion.major,
614 	    p->info.libraryVersion.minor);
615 	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
616 		error("C_GetSlotList failed: %lu", rv);
617 		goto fail;
618 	}
619 	if (p->nslots == 0) {
620 		error("no slots");
621 		goto fail;
622 	}
623 	p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
624 	if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
625 	    != CKR_OK) {
626 		error("C_GetSlotList failed: %lu", rv);
627 		goto fail;
628 	}
629 	p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
630 	p->valid = 1;
631 	nkeys = 0;
632 	for (i = 0; i < p->nslots; i++) {
633 		token = &p->slotinfo[i].token;
634 		if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
635 		    != CKR_OK) {
636 			error("C_GetTokenInfo failed: %lu", rv);
637 			continue;
638 		}
639 		if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
640 			debug2("%s: ignoring uninitialised token in slot %lu",
641 			    __func__, (unsigned long)i);
642 			continue;
643 		}
644 		rmspace(token->label, sizeof(token->label));
645 		rmspace(token->manufacturerID, sizeof(token->manufacturerID));
646 		rmspace(token->model, sizeof(token->model));
647 		rmspace(token->serialNumber, sizeof(token->serialNumber));
648 		debug("label <%s> manufacturerID <%s> model <%s> serial <%s>"
649 		    " flags 0x%lx",
650 		    token->label, token->manufacturerID, token->model,
651 		    token->serialNumber, token->flags);
652 		/* open session, login with pin and retrieve public keys */
653 		if (pkcs11_open_session(p, i, pin) == 0)
654 			pkcs11_fetch_keys(p, i, keyp, &nkeys);
655 	}
656 	if (nkeys > 0) {
657 		TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
658 		p->refcount++;	/* add to provider list */
659 		return (nkeys);
660 	}
661 	error("no keys");
662 	/* don't add the provider, since it does not have any keys */
663 fail:
664 	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
665 		error("C_Finalize failed: %lu", rv);
666 	if (p) {
667 		free(p->slotlist);
668 		free(p->slotinfo);
669 		free(p);
670 	}
671 	if (handle)
672 		dlclose(handle);
673 	return (-1);
674 }
675 #else
676 int
677 pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
678 {
679 	error("dlopen() not supported");
680 	return (-1);
681 }
682 #endif
683