xref: /openssh-portable/ssh-pkcs11.c (revision 1d89232a)
1 /* $OpenBSD: ssh-pkcs11.c,v 1.49 2020/03/13 04:16:27 djm Exp $ */
2 /*
3  * Copyright (c) 2010 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2014 Pedro Martelletto. All rights reserved.
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include "includes.h"
20 
21 #ifdef ENABLE_PKCS11
22 
23 #ifdef HAVE_SYS_TIME_H
24 # include <sys/time.h>
25 #endif
26 
27 #include <sys/types.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 
31 #include <ctype.h>
32 #include <string.h>
33 #include <dlfcn.h>
34 
35 #include "openbsd-compat/sys-queue.h"
36 #include "openbsd-compat/openssl-compat.h"
37 
38 #include <openssl/ecdsa.h>
39 #include <openssl/x509.h>
40 #include <openssl/err.h>
41 
42 #define CRYPTOKI_COMPAT
43 #include "pkcs11.h"
44 
45 #include "log.h"
46 #include "misc.h"
47 #include "sshkey.h"
48 #include "ssh-pkcs11.h"
49 #include "xmalloc.h"
50 
51 struct pkcs11_slotinfo {
52 	CK_TOKEN_INFO		token;
53 	CK_SESSION_HANDLE	session;
54 	int			logged_in;
55 };
56 
57 struct pkcs11_provider {
58 	char			*name;
59 	void			*handle;
60 	CK_FUNCTION_LIST	*function_list;
61 	CK_INFO			info;
62 	CK_ULONG		nslots;
63 	CK_SLOT_ID		*slotlist;
64 	struct pkcs11_slotinfo	*slotinfo;
65 	int			valid;
66 	int			refcount;
67 	TAILQ_ENTRY(pkcs11_provider) next;
68 };
69 
70 TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
71 
72 struct pkcs11_key {
73 	struct pkcs11_provider	*provider;
74 	CK_ULONG		slotidx;
75 	char			*keyid;
76 	int			keyid_len;
77 };
78 
79 int pkcs11_interactive = 0;
80 
81 #ifdef HAVE_EC_KEY_METHOD_NEW
82 static void
ossl_error(const char * msg)83 ossl_error(const char *msg)
84 {
85 	unsigned long    e;
86 
87 	error("%s: %s", __func__, msg);
88 	while ((e = ERR_get_error()) != 0)
89 		error("%s: libcrypto error: %.100s", __func__,
90 		    ERR_error_string(e, NULL));
91 }
92 #endif /* HAVE_EC_KEY_METHOD_NEW */
93 
94 int
pkcs11_init(int interactive)95 pkcs11_init(int interactive)
96 {
97 	pkcs11_interactive = interactive;
98 	TAILQ_INIT(&pkcs11_providers);
99 	return (0);
100 }
101 
102 /*
103  * finalize a provider shared library, it's no longer usable.
104  * however, there might still be keys referencing this provider,
105  * so the actual freeing of memory is handled by pkcs11_provider_unref().
106  * this is called when a provider gets unregistered.
107  */
108 static void
pkcs11_provider_finalize(struct pkcs11_provider * p)109 pkcs11_provider_finalize(struct pkcs11_provider *p)
110 {
111 	CK_RV rv;
112 	CK_ULONG i;
113 
114 	debug("pkcs11_provider_finalize: %p refcount %d valid %d",
115 	    p, p->refcount, p->valid);
116 	if (!p->valid)
117 		return;
118 	for (i = 0; i < p->nslots; i++) {
119 		if (p->slotinfo[i].session &&
120 		    (rv = p->function_list->C_CloseSession(
121 		    p->slotinfo[i].session)) != CKR_OK)
122 			error("C_CloseSession failed: %lu", rv);
123 	}
124 	if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
125 		error("C_Finalize failed: %lu", rv);
126 	p->valid = 0;
127 	p->function_list = NULL;
128 	dlclose(p->handle);
129 }
130 
131 /*
132  * remove a reference to the provider.
133  * called when a key gets destroyed or when the provider is unregistered.
134  */
135 static void
pkcs11_provider_unref(struct pkcs11_provider * p)136 pkcs11_provider_unref(struct pkcs11_provider *p)
137 {
138 	debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
139 	if (--p->refcount <= 0) {
140 		if (p->valid)
141 			error("pkcs11_provider_unref: %p still valid", p);
142 		free(p->name);
143 		free(p->slotlist);
144 		free(p->slotinfo);
145 		free(p);
146 	}
147 }
148 
149 /* unregister all providers, keys might still point to the providers */
150 void
pkcs11_terminate(void)151 pkcs11_terminate(void)
152 {
153 	struct pkcs11_provider *p;
154 
155 	while ((p = TAILQ_FIRST(&pkcs11_providers)) != NULL) {
156 		TAILQ_REMOVE(&pkcs11_providers, p, next);
157 		pkcs11_provider_finalize(p);
158 		pkcs11_provider_unref(p);
159 	}
160 }
161 
162 /* lookup provider by name */
163 static struct pkcs11_provider *
pkcs11_provider_lookup(char * provider_id)164 pkcs11_provider_lookup(char *provider_id)
165 {
166 	struct pkcs11_provider *p;
167 
168 	TAILQ_FOREACH(p, &pkcs11_providers, next) {
169 		debug("check %p %s", p, p->name);
170 		if (!strcmp(provider_id, p->name))
171 			return (p);
172 	}
173 	return (NULL);
174 }
175 
176 /* unregister provider by name */
177 int
pkcs11_del_provider(char * provider_id)178 pkcs11_del_provider(char *provider_id)
179 {
180 	struct pkcs11_provider *p;
181 
182 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
183 		TAILQ_REMOVE(&pkcs11_providers, p, next);
184 		pkcs11_provider_finalize(p);
185 		pkcs11_provider_unref(p);
186 		return (0);
187 	}
188 	return (-1);
189 }
190 
191 static RSA_METHOD *rsa_method;
192 static int rsa_idx = 0;
193 #ifdef HAVE_EC_KEY_METHOD_NEW
194 static EC_KEY_METHOD *ec_key_method;
195 static int ec_key_idx = 0;
196 #endif
197 
198 /* release a wrapped object */
199 static void
pkcs11_k11_free(void * parent,void * ptr,CRYPTO_EX_DATA * ad,int idx,long argl,void * argp)200 pkcs11_k11_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
201     long argl, void *argp)
202 {
203 	struct pkcs11_key	*k11 = ptr;
204 
205 	debug("%s: parent %p ptr %p idx %d", __func__, parent, ptr, idx);
206 	if (k11 == NULL)
207 		return;
208 	if (k11->provider)
209 		pkcs11_provider_unref(k11->provider);
210 	free(k11->keyid);
211 	free(k11);
212 }
213 
214 /* find a single 'obj' for given attributes */
215 static int
pkcs11_find(struct pkcs11_provider * p,CK_ULONG slotidx,CK_ATTRIBUTE * attr,CK_ULONG nattr,CK_OBJECT_HANDLE * obj)216 pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
217     CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
218 {
219 	CK_FUNCTION_LIST	*f;
220 	CK_SESSION_HANDLE	session;
221 	CK_ULONG		nfound = 0;
222 	CK_RV			rv;
223 	int			ret = -1;
224 
225 	f = p->function_list;
226 	session = p->slotinfo[slotidx].session;
227 	if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
228 		error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
229 		return (-1);
230 	}
231 	if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
232 	    nfound != 1) {
233 		debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
234 		    nfound, nattr, rv);
235 	} else
236 		ret = 0;
237 	if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
238 		error("C_FindObjectsFinal failed: %lu", rv);
239 	return (ret);
240 }
241 
242 static int
pkcs11_login_slot(struct pkcs11_provider * provider,struct pkcs11_slotinfo * si,CK_USER_TYPE type)243 pkcs11_login_slot(struct pkcs11_provider *provider, struct pkcs11_slotinfo *si,
244     CK_USER_TYPE type)
245 {
246 	char			*pin = NULL, prompt[1024];
247 	CK_RV			 rv;
248 
249 	if (provider == NULL || si == NULL || !provider->valid) {
250 		error("no pkcs11 (valid) provider found");
251 		return (-1);
252 	}
253 
254 	if (!pkcs11_interactive) {
255 		error("need pin entry%s",
256 		    (si->token.flags & 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), "Enter PIN for '%s': ",
264 		    si->token.label);
265 		if ((pin = read_passphrase(prompt, RP_ALLOW_EOF)) == NULL) {
266 			debug("%s: no pin specified", __func__);
267 			return (-1);	/* bail out */
268 		}
269 	}
270 	rv = provider->function_list->C_Login(si->session, type, (u_char *)pin,
271 	    (pin != NULL) ? strlen(pin) : 0);
272 	if (pin != NULL)
273 		freezero(pin, strlen(pin));
274 
275 	switch (rv) {
276 	case CKR_OK:
277 	case CKR_USER_ALREADY_LOGGED_IN:
278 		/* success */
279 		break;
280 	case CKR_PIN_LEN_RANGE:
281 		error("PKCS#11 login failed: PIN length out of range");
282 		return -1;
283 	case CKR_PIN_INCORRECT:
284 		error("PKCS#11 login failed: PIN incorrect");
285 		return -1;
286 	case CKR_PIN_LOCKED:
287 		error("PKCS#11 login failed: PIN locked");
288 		return -1;
289 	default:
290 		error("PKCS#11 login failed: error %lu", rv);
291 		return -1;
292 	}
293 	si->logged_in = 1;
294 	return (0);
295 }
296 
297 static int
pkcs11_login(struct pkcs11_key * k11,CK_USER_TYPE type)298 pkcs11_login(struct pkcs11_key *k11, CK_USER_TYPE type)
299 {
300 	if (k11 == NULL || k11->provider == NULL || !k11->provider->valid) {
301 		error("no pkcs11 (valid) provider found");
302 		return (-1);
303 	}
304 
305 	return pkcs11_login_slot(k11->provider,
306 	    &k11->provider->slotinfo[k11->slotidx], type);
307 }
308 
309 
310 static int
pkcs11_check_obj_bool_attrib(struct pkcs11_key * k11,CK_OBJECT_HANDLE obj,CK_ATTRIBUTE_TYPE type,int * val)311 pkcs11_check_obj_bool_attrib(struct pkcs11_key *k11, CK_OBJECT_HANDLE obj,
312     CK_ATTRIBUTE_TYPE type, int *val)
313 {
314 	struct pkcs11_slotinfo	*si;
315 	CK_FUNCTION_LIST	*f;
316 	CK_BBOOL		flag = 0;
317 	CK_ATTRIBUTE		attr;
318 	CK_RV			 rv;
319 
320 	*val = 0;
321 
322 	if (!k11->provider || !k11->provider->valid) {
323 		error("no pkcs11 (valid) provider found");
324 		return (-1);
325 	}
326 
327 	f = k11->provider->function_list;
328 	si = &k11->provider->slotinfo[k11->slotidx];
329 
330 	attr.type = type;
331 	attr.pValue = &flag;
332 	attr.ulValueLen = sizeof(flag);
333 
334 	rv = f->C_GetAttributeValue(si->session, obj, &attr, 1);
335 	if (rv != CKR_OK) {
336 		error("C_GetAttributeValue failed: %lu", rv);
337 		return (-1);
338 	}
339 	*val = flag != 0;
340 	debug("%s: provider %p slot %lu object %lu: attrib %lu = %d",
341 	    __func__, k11->provider, k11->slotidx, obj, type, *val);
342 	return (0);
343 }
344 
345 static int
pkcs11_get_key(struct pkcs11_key * k11,CK_MECHANISM_TYPE mech_type)346 pkcs11_get_key(struct pkcs11_key *k11, CK_MECHANISM_TYPE mech_type)
347 {
348 	struct pkcs11_slotinfo	*si;
349 	CK_FUNCTION_LIST	*f;
350 	CK_OBJECT_HANDLE	 obj;
351 	CK_RV			 rv;
352 	CK_OBJECT_CLASS		 private_key_class;
353 	CK_BBOOL		 true_val;
354 	CK_MECHANISM		 mech;
355 	CK_ATTRIBUTE		 key_filter[3];
356 	int			 always_auth = 0;
357 	int			 did_login = 0;
358 
359 	if (!k11->provider || !k11->provider->valid) {
360 		error("no pkcs11 (valid) provider found");
361 		return (-1);
362 	}
363 
364 	f = k11->provider->function_list;
365 	si = &k11->provider->slotinfo[k11->slotidx];
366 
367 	if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
368 		if (pkcs11_login(k11, CKU_USER) < 0) {
369 			error("login failed");
370 			return (-1);
371 		}
372 		did_login = 1;
373 	}
374 
375 	memset(&key_filter, 0, sizeof(key_filter));
376 	private_key_class = CKO_PRIVATE_KEY;
377 	key_filter[0].type = CKA_CLASS;
378 	key_filter[0].pValue = &private_key_class;
379 	key_filter[0].ulValueLen = sizeof(private_key_class);
380 
381 	key_filter[1].type = CKA_ID;
382 	key_filter[1].pValue = k11->keyid;
383 	key_filter[1].ulValueLen = k11->keyid_len;
384 
385 	true_val = CK_TRUE;
386 	key_filter[2].type = CKA_SIGN;
387 	key_filter[2].pValue = &true_val;
388 	key_filter[2].ulValueLen = sizeof(true_val);
389 
390 	/* try to find object w/CKA_SIGN first, retry w/o */
391 	if (pkcs11_find(k11->provider, k11->slotidx, key_filter, 3, &obj) < 0 &&
392 	    pkcs11_find(k11->provider, k11->slotidx, key_filter, 2, &obj) < 0) {
393 		error("cannot find private key");
394 		return (-1);
395 	}
396 
397 	memset(&mech, 0, sizeof(mech));
398 	mech.mechanism = mech_type;
399 	mech.pParameter = NULL_PTR;
400 	mech.ulParameterLen = 0;
401 
402 	if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
403 		error("C_SignInit failed: %lu", rv);
404 		return (-1);
405 	}
406 
407 	pkcs11_check_obj_bool_attrib(k11, obj, CKA_ALWAYS_AUTHENTICATE,
408 	    &always_auth); /* ignore errors here */
409 	if (always_auth && !did_login) {
410 		debug("%s: always-auth key", __func__);
411 		if (pkcs11_login(k11, CKU_CONTEXT_SPECIFIC) < 0) {
412 			error("login failed for always-auth key");
413 			return (-1);
414 		}
415 	}
416 
417 	return (0);
418 }
419 
420 /* openssl callback doing the actual signing operation */
421 static int
pkcs11_rsa_private_encrypt(int flen,const u_char * from,u_char * to,RSA * rsa,int padding)422 pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
423     int padding)
424 {
425 	struct pkcs11_key	*k11;
426 	struct pkcs11_slotinfo	*si;
427 	CK_FUNCTION_LIST	*f;
428 	CK_ULONG		tlen = 0;
429 	CK_RV			rv;
430 	int			rval = -1;
431 
432 	if ((k11 = RSA_get_ex_data(rsa, rsa_idx)) == NULL) {
433 		error("RSA_get_ex_data failed for rsa %p", rsa);
434 		return (-1);
435 	}
436 
437 	if (pkcs11_get_key(k11, CKM_RSA_PKCS) == -1) {
438 		error("pkcs11_get_key failed");
439 		return (-1);
440 	}
441 
442 	f = k11->provider->function_list;
443 	si = &k11->provider->slotinfo[k11->slotidx];
444 	tlen = RSA_size(rsa);
445 
446 	/* XXX handle CKR_BUFFER_TOO_SMALL */
447 	rv = f->C_Sign(si->session, (CK_BYTE *)from, flen, to, &tlen);
448 	if (rv == CKR_OK)
449 		rval = tlen;
450 	else
451 		error("C_Sign failed: %lu", rv);
452 
453 	return (rval);
454 }
455 
456 static int
pkcs11_rsa_private_decrypt(int flen,const u_char * from,u_char * to,RSA * rsa,int padding)457 pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
458     int padding)
459 {
460 	return (-1);
461 }
462 
463 static int
pkcs11_rsa_start_wrapper(void)464 pkcs11_rsa_start_wrapper(void)
465 {
466 	if (rsa_method != NULL)
467 		return (0);
468 	rsa_method = RSA_meth_dup(RSA_get_default_method());
469 	if (rsa_method == NULL)
470 		return (-1);
471 	rsa_idx = RSA_get_ex_new_index(0, "ssh-pkcs11-rsa",
472 	    NULL, NULL, pkcs11_k11_free);
473 	if (rsa_idx == -1)
474 		return (-1);
475 	if (!RSA_meth_set1_name(rsa_method, "pkcs11") ||
476 	    !RSA_meth_set_priv_enc(rsa_method, pkcs11_rsa_private_encrypt) ||
477 	    !RSA_meth_set_priv_dec(rsa_method, pkcs11_rsa_private_decrypt)) {
478 		error("%s: setup pkcs11 method failed", __func__);
479 		return (-1);
480 	}
481 	return (0);
482 }
483 
484 /* redirect private key operations for rsa key to pkcs11 token */
485 static int
pkcs11_rsa_wrap(struct pkcs11_provider * provider,CK_ULONG slotidx,CK_ATTRIBUTE * keyid_attrib,RSA * rsa)486 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
487     CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
488 {
489 	struct pkcs11_key	*k11;
490 
491 	if (pkcs11_rsa_start_wrapper() == -1)
492 		return (-1);
493 
494 	k11 = xcalloc(1, sizeof(*k11));
495 	k11->provider = provider;
496 	provider->refcount++;	/* provider referenced by RSA key */
497 	k11->slotidx = slotidx;
498 	/* identify key object on smartcard */
499 	k11->keyid_len = keyid_attrib->ulValueLen;
500 	if (k11->keyid_len > 0) {
501 		k11->keyid = xmalloc(k11->keyid_len);
502 		memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
503 	}
504 
505 	RSA_set_method(rsa, rsa_method);
506 	RSA_set_ex_data(rsa, rsa_idx, k11);
507 	return (0);
508 }
509 
510 #ifdef HAVE_EC_KEY_METHOD_NEW
511 /* openssl callback doing the actual signing operation */
512 static ECDSA_SIG *
ecdsa_do_sign(const unsigned char * dgst,int dgst_len,const BIGNUM * inv,const BIGNUM * rp,EC_KEY * ec)513 ecdsa_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv,
514     const BIGNUM *rp, EC_KEY *ec)
515 {
516 	struct pkcs11_key	*k11;
517 	struct pkcs11_slotinfo	*si;
518 	CK_FUNCTION_LIST	*f;
519 	CK_ULONG		siglen = 0, bnlen;
520 	CK_RV			rv;
521 	ECDSA_SIG		*ret = NULL;
522 	u_char			*sig;
523 	BIGNUM			*r = NULL, *s = NULL;
524 
525 	if ((k11 = EC_KEY_get_ex_data(ec, ec_key_idx)) == NULL) {
526 		ossl_error("EC_KEY_get_key_method_data failed for ec");
527 		return (NULL);
528 	}
529 
530 	if (pkcs11_get_key(k11, CKM_ECDSA) == -1) {
531 		error("pkcs11_get_key failed");
532 		return (NULL);
533 	}
534 
535 	f = k11->provider->function_list;
536 	si = &k11->provider->slotinfo[k11->slotidx];
537 
538 	siglen = ECDSA_size(ec);
539 	sig = xmalloc(siglen);
540 
541 	/* XXX handle CKR_BUFFER_TOO_SMALL */
542 	rv = f->C_Sign(si->session, (CK_BYTE *)dgst, dgst_len, sig, &siglen);
543 	if (rv != CKR_OK) {
544 		error("C_Sign failed: %lu", rv);
545 		goto done;
546 	}
547 	if (siglen < 64 || siglen > 132 || siglen % 2) {
548 		ossl_error("d2i_ECDSA_SIG failed");
549 		goto done;
550 	}
551 	bnlen = siglen/2;
552 	if ((ret = ECDSA_SIG_new()) == NULL) {
553 		error("ECDSA_SIG_new failed");
554 		goto done;
555 	}
556 	if ((r = BN_bin2bn(sig, bnlen, NULL)) == NULL ||
557 	    (s = BN_bin2bn(sig+bnlen, bnlen, NULL)) == NULL) {
558 		ossl_error("d2i_ECDSA_SIG failed");
559 		ECDSA_SIG_free(ret);
560 		ret = NULL;
561 		goto done;
562 	}
563 	if (!ECDSA_SIG_set0(ret, r, s)) {
564 		error("%s: ECDSA_SIG_set0 failed", __func__);
565 		ECDSA_SIG_free(ret);
566 		ret = NULL;
567 		goto done;
568 	}
569 	r = s = NULL; /* now owned by ret */
570 	/* success */
571  done:
572 	BN_free(r);
573 	BN_free(s);
574 	free(sig);
575 
576 	return (ret);
577 }
578 
579 static int
pkcs11_ecdsa_start_wrapper(void)580 pkcs11_ecdsa_start_wrapper(void)
581 {
582 	int (*orig_sign)(int, const unsigned char *, int, unsigned char *,
583 	    unsigned int *, const BIGNUM *, const BIGNUM *, EC_KEY *) = NULL;
584 
585 	if (ec_key_method != NULL)
586 		return (0);
587 	ec_key_idx = EC_KEY_get_ex_new_index(0, "ssh-pkcs11-ecdsa",
588 	    NULL, NULL, pkcs11_k11_free);
589 	if (ec_key_idx == -1)
590 		return (-1);
591 	ec_key_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
592 	if (ec_key_method == NULL)
593 		return (-1);
594 	EC_KEY_METHOD_get_sign(ec_key_method, &orig_sign, NULL, NULL);
595 	EC_KEY_METHOD_set_sign(ec_key_method, orig_sign, NULL, ecdsa_do_sign);
596 	return (0);
597 }
598 
599 static int
pkcs11_ecdsa_wrap(struct pkcs11_provider * provider,CK_ULONG slotidx,CK_ATTRIBUTE * keyid_attrib,EC_KEY * ec)600 pkcs11_ecdsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
601     CK_ATTRIBUTE *keyid_attrib, EC_KEY *ec)
602 {
603 	struct pkcs11_key	*k11;
604 
605 	if (pkcs11_ecdsa_start_wrapper() == -1)
606 		return (-1);
607 
608 	k11 = xcalloc(1, sizeof(*k11));
609 	k11->provider = provider;
610 	provider->refcount++;	/* provider referenced by ECDSA key */
611 	k11->slotidx = slotidx;
612 	/* identify key object on smartcard */
613 	k11->keyid_len = keyid_attrib->ulValueLen;
614 	k11->keyid = xmalloc(k11->keyid_len);
615 	memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
616 
617 	EC_KEY_set_method(ec, ec_key_method);
618 	EC_KEY_set_ex_data(ec, ec_key_idx, k11);
619 
620 	return (0);
621 }
622 #endif /* HAVE_EC_KEY_METHOD_NEW */
623 
624 /* remove trailing spaces */
625 static void
rmspace(u_char * buf,size_t len)626 rmspace(u_char *buf, size_t len)
627 {
628 	size_t i;
629 
630 	if (!len)
631 		return;
632 	for (i = len - 1;  i > 0; i--)
633 		if (i == len - 1 || buf[i] == ' ')
634 			buf[i] = '\0';
635 		else
636 			break;
637 }
638 
639 /*
640  * open a pkcs11 session and login if required.
641  * if pin == NULL we delay login until key use
642  */
643 static int
pkcs11_open_session(struct pkcs11_provider * p,CK_ULONG slotidx,char * pin,CK_ULONG user)644 pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin,
645     CK_ULONG user)
646 {
647 	struct pkcs11_slotinfo	*si;
648 	CK_FUNCTION_LIST	*f;
649 	CK_RV			rv;
650 	CK_SESSION_HANDLE	session;
651 	int			login_required, ret;
652 
653 	f = p->function_list;
654 	si = &p->slotinfo[slotidx];
655 
656 	login_required = si->token.flags & CKF_LOGIN_REQUIRED;
657 
658 	/* fail early before opening session */
659 	if (login_required && !pkcs11_interactive &&
660 	    (pin == NULL || strlen(pin) == 0)) {
661 		error("pin required");
662 		return (-SSH_PKCS11_ERR_PIN_REQUIRED);
663 	}
664 	if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
665 	    CKF_SERIAL_SESSION, NULL, NULL, &session)) != CKR_OK) {
666 		error("C_OpenSession failed: %lu", rv);
667 		return (-1);
668 	}
669 	if (login_required && pin != NULL && strlen(pin) != 0) {
670 		rv = f->C_Login(session, user, (u_char *)pin, strlen(pin));
671 		if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
672 			error("C_Login failed: %lu", rv);
673 			ret = (rv == CKR_PIN_LOCKED) ?
674 			    -SSH_PKCS11_ERR_PIN_LOCKED :
675 			    -SSH_PKCS11_ERR_LOGIN_FAIL;
676 			if ((rv = f->C_CloseSession(session)) != CKR_OK)
677 				error("C_CloseSession failed: %lu", rv);
678 			return (ret);
679 		}
680 		si->logged_in = 1;
681 	}
682 	si->session = session;
683 	return (0);
684 }
685 
686 static int
pkcs11_key_included(struct sshkey *** keysp,int * nkeys,struct sshkey * key)687 pkcs11_key_included(struct sshkey ***keysp, int *nkeys, struct sshkey *key)
688 {
689 	int i;
690 
691 	for (i = 0; i < *nkeys; i++)
692 		if (sshkey_equal(key, (*keysp)[i]))
693 			return (1);
694 	return (0);
695 }
696 
697 #ifdef HAVE_EC_KEY_METHOD_NEW
698 static struct sshkey *
pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider * p,CK_ULONG slotidx,CK_OBJECT_HANDLE * obj)699 pkcs11_fetch_ecdsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
700     CK_OBJECT_HANDLE *obj)
701 {
702 	CK_ATTRIBUTE		 key_attr[3];
703 	CK_SESSION_HANDLE	 session;
704 	CK_FUNCTION_LIST	*f = NULL;
705 	CK_RV			 rv;
706 	ASN1_OCTET_STRING	*octet = NULL;
707 	EC_KEY			*ec = NULL;
708 	EC_GROUP		*group = NULL;
709 	struct sshkey		*key = NULL;
710 	const unsigned char	*attrp = NULL;
711 	int			 i;
712 	int			 nid;
713 
714 	memset(&key_attr, 0, sizeof(key_attr));
715 	key_attr[0].type = CKA_ID;
716 	key_attr[1].type = CKA_EC_POINT;
717 	key_attr[2].type = CKA_EC_PARAMS;
718 
719 	session = p->slotinfo[slotidx].session;
720 	f = p->function_list;
721 
722 	/* figure out size of the attributes */
723 	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
724 	if (rv != CKR_OK) {
725 		error("C_GetAttributeValue failed: %lu", rv);
726 		return (NULL);
727 	}
728 
729 	/*
730 	 * Allow CKA_ID (always first attribute) to be empty, but
731 	 * ensure that none of the others are zero length.
732 	 * XXX assumes CKA_ID is always first.
733 	 */
734 	if (key_attr[1].ulValueLen == 0 ||
735 	    key_attr[2].ulValueLen == 0) {
736 		error("invalid attribute length");
737 		return (NULL);
738 	}
739 
740 	/* allocate buffers for attributes */
741 	for (i = 0; i < 3; i++)
742 		if (key_attr[i].ulValueLen > 0)
743 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
744 
745 	/* retrieve ID, public point and curve parameters of EC key */
746 	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
747 	if (rv != CKR_OK) {
748 		error("C_GetAttributeValue failed: %lu", rv);
749 		goto fail;
750 	}
751 
752 	ec = EC_KEY_new();
753 	if (ec == NULL) {
754 		error("EC_KEY_new failed");
755 		goto fail;
756 	}
757 
758 	attrp = key_attr[2].pValue;
759 	group = d2i_ECPKParameters(NULL, &attrp, key_attr[2].ulValueLen);
760 	if (group == NULL) {
761 		ossl_error("d2i_ECPKParameters failed");
762 		goto fail;
763 	}
764 
765 	if (EC_KEY_set_group(ec, group) == 0) {
766 		ossl_error("EC_KEY_set_group failed");
767 		goto fail;
768 	}
769 
770 	if (key_attr[1].ulValueLen <= 2) {
771 		error("CKA_EC_POINT too small");
772 		goto fail;
773 	}
774 
775 	attrp = key_attr[1].pValue;
776 	octet = d2i_ASN1_OCTET_STRING(NULL, &attrp, key_attr[1].ulValueLen);
777 	if (octet == NULL) {
778 		ossl_error("d2i_ASN1_OCTET_STRING failed");
779 		goto fail;
780 	}
781 	attrp = octet->data;
782 	if (o2i_ECPublicKey(&ec, &attrp, octet->length) == NULL) {
783 		ossl_error("o2i_ECPublicKey failed");
784 		goto fail;
785 	}
786 
787 	nid = sshkey_ecdsa_key_to_nid(ec);
788 	if (nid < 0) {
789 		error("couldn't get curve nid");
790 		goto fail;
791 	}
792 
793 	if (pkcs11_ecdsa_wrap(p, slotidx, &key_attr[0], ec))
794 		goto fail;
795 
796 	key = sshkey_new(KEY_UNSPEC);
797 	if (key == NULL) {
798 		error("sshkey_new failed");
799 		goto fail;
800 	}
801 
802 	key->ecdsa = ec;
803 	key->ecdsa_nid = nid;
804 	key->type = KEY_ECDSA;
805 	key->flags |= SSHKEY_FLAG_EXT;
806 	ec = NULL;	/* now owned by key */
807 
808 fail:
809 	for (i = 0; i < 3; i++)
810 		free(key_attr[i].pValue);
811 	if (ec)
812 		EC_KEY_free(ec);
813 	if (group)
814 		EC_GROUP_free(group);
815 	if (octet)
816 		ASN1_OCTET_STRING_free(octet);
817 
818 	return (key);
819 }
820 #endif /* HAVE_EC_KEY_METHOD_NEW */
821 
822 static struct sshkey *
pkcs11_fetch_rsa_pubkey(struct pkcs11_provider * p,CK_ULONG slotidx,CK_OBJECT_HANDLE * obj)823 pkcs11_fetch_rsa_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
824     CK_OBJECT_HANDLE *obj)
825 {
826 	CK_ATTRIBUTE		 key_attr[3];
827 	CK_SESSION_HANDLE	 session;
828 	CK_FUNCTION_LIST	*f = NULL;
829 	CK_RV			 rv;
830 	RSA			*rsa = NULL;
831 	BIGNUM			*rsa_n, *rsa_e;
832 	struct sshkey		*key = NULL;
833 	int			 i;
834 
835 	memset(&key_attr, 0, sizeof(key_attr));
836 	key_attr[0].type = CKA_ID;
837 	key_attr[1].type = CKA_MODULUS;
838 	key_attr[2].type = CKA_PUBLIC_EXPONENT;
839 
840 	session = p->slotinfo[slotidx].session;
841 	f = p->function_list;
842 
843 	/* figure out size of the attributes */
844 	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
845 	if (rv != CKR_OK) {
846 		error("C_GetAttributeValue failed: %lu", rv);
847 		return (NULL);
848 	}
849 
850 	/*
851 	 * Allow CKA_ID (always first attribute) to be empty, but
852 	 * ensure that none of the others are zero length.
853 	 * XXX assumes CKA_ID is always first.
854 	 */
855 	if (key_attr[1].ulValueLen == 0 ||
856 	    key_attr[2].ulValueLen == 0) {
857 		error("invalid attribute length");
858 		return (NULL);
859 	}
860 
861 	/* allocate buffers for attributes */
862 	for (i = 0; i < 3; i++)
863 		if (key_attr[i].ulValueLen > 0)
864 			key_attr[i].pValue = xcalloc(1, key_attr[i].ulValueLen);
865 
866 	/* retrieve ID, modulus and public exponent of RSA key */
867 	rv = f->C_GetAttributeValue(session, *obj, key_attr, 3);
868 	if (rv != CKR_OK) {
869 		error("C_GetAttributeValue failed: %lu", rv);
870 		goto fail;
871 	}
872 
873 	rsa = RSA_new();
874 	if (rsa == NULL) {
875 		error("RSA_new failed");
876 		goto fail;
877 	}
878 
879 	rsa_n = BN_bin2bn(key_attr[1].pValue, key_attr[1].ulValueLen, NULL);
880 	rsa_e = BN_bin2bn(key_attr[2].pValue, key_attr[2].ulValueLen, NULL);
881 	if (rsa_n == NULL || rsa_e == NULL) {
882 		error("BN_bin2bn failed");
883 		goto fail;
884 	}
885 	if (!RSA_set0_key(rsa, rsa_n, rsa_e, NULL))
886 		fatal("%s: set key", __func__);
887 	rsa_n = rsa_e = NULL; /* transferred */
888 
889 	if (pkcs11_rsa_wrap(p, slotidx, &key_attr[0], rsa))
890 		goto fail;
891 
892 	key = sshkey_new(KEY_UNSPEC);
893 	if (key == NULL) {
894 		error("sshkey_new failed");
895 		goto fail;
896 	}
897 
898 	key->rsa = rsa;
899 	key->type = KEY_RSA;
900 	key->flags |= SSHKEY_FLAG_EXT;
901 	rsa = NULL;	/* now owned by key */
902 
903 fail:
904 	for (i = 0; i < 3; i++)
905 		free(key_attr[i].pValue);
906 	RSA_free(rsa);
907 
908 	return (key);
909 }
910 
911 static int
pkcs11_fetch_x509_pubkey(struct pkcs11_provider * p,CK_ULONG slotidx,CK_OBJECT_HANDLE * obj,struct sshkey ** keyp,char ** labelp)912 pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
913     CK_OBJECT_HANDLE *obj, struct sshkey **keyp, char **labelp)
914 {
915 	CK_ATTRIBUTE		 cert_attr[3];
916 	CK_SESSION_HANDLE	 session;
917 	CK_FUNCTION_LIST	*f = NULL;
918 	CK_RV			 rv;
919 	X509			*x509 = NULL;
920 	X509_NAME		*x509_name = NULL;
921 	EVP_PKEY		*evp;
922 	RSA			*rsa = NULL;
923 #ifdef OPENSSL_HAS_ECC
924 	EC_KEY			*ec = NULL;
925 #endif
926 	struct sshkey		*key = NULL;
927 	int			 i;
928 #ifdef HAVE_EC_KEY_METHOD_NEW
929 	int			 nid;
930 #endif
931 	const u_char		*cp;
932 	char			*subject = NULL;
933 
934 	*keyp = NULL;
935 	*labelp = NULL;
936 
937 	memset(&cert_attr, 0, sizeof(cert_attr));
938 	cert_attr[0].type = CKA_ID;
939 	cert_attr[1].type = CKA_SUBJECT;
940 	cert_attr[2].type = CKA_VALUE;
941 
942 	session = p->slotinfo[slotidx].session;
943 	f = p->function_list;
944 
945 	/* figure out size of the attributes */
946 	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
947 	if (rv != CKR_OK) {
948 		error("C_GetAttributeValue failed: %lu", rv);
949 		return -1;
950 	}
951 
952 	/*
953 	 * Allow CKA_ID (always first attribute) to be empty, but
954 	 * ensure that none of the others are zero length.
955 	 * XXX assumes CKA_ID is always first.
956 	 */
957 	if (cert_attr[1].ulValueLen == 0 ||
958 	    cert_attr[2].ulValueLen == 0) {
959 		error("invalid attribute length");
960 		return -1;
961 	}
962 
963 	/* allocate buffers for attributes */
964 	for (i = 0; i < 3; i++)
965 		if (cert_attr[i].ulValueLen > 0)
966 			cert_attr[i].pValue = xcalloc(1, cert_attr[i].ulValueLen);
967 
968 	/* retrieve ID, subject and value of certificate */
969 	rv = f->C_GetAttributeValue(session, *obj, cert_attr, 3);
970 	if (rv != CKR_OK) {
971 		error("C_GetAttributeValue failed: %lu", rv);
972 		goto out;
973 	}
974 
975 	/* Decode DER-encoded cert subject */
976 	cp = cert_attr[2].pValue;
977 	if ((x509_name = d2i_X509_NAME(NULL, &cp,
978 	    cert_attr[1].ulValueLen)) == NULL ||
979 	    (subject = X509_NAME_oneline(x509_name, NULL, 0)) == NULL)
980 		subject = xstrdup("invalid subject");
981 	X509_NAME_free(x509_name);
982 
983 	cp = cert_attr[2].pValue;
984 	if ((x509 = d2i_X509(NULL, &cp, cert_attr[2].ulValueLen)) == NULL) {
985 		error("d2i_x509 failed");
986 		goto out;
987 	}
988 
989 	if ((evp = X509_get_pubkey(x509)) == NULL) {
990 		error("X509_get_pubkey failed");
991 		goto out;
992 	}
993 
994 	if (EVP_PKEY_base_id(evp) == EVP_PKEY_RSA) {
995 		if (EVP_PKEY_get0_RSA(evp) == NULL) {
996 			error("invalid x509; no rsa key");
997 			goto out;
998 		}
999 		if ((rsa = RSAPublicKey_dup(EVP_PKEY_get0_RSA(evp))) == NULL) {
1000 			error("RSAPublicKey_dup failed");
1001 			goto out;
1002 		}
1003 
1004 		if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], rsa))
1005 			goto out;
1006 
1007 		key = sshkey_new(KEY_UNSPEC);
1008 		if (key == NULL) {
1009 			error("sshkey_new failed");
1010 			goto out;
1011 		}
1012 
1013 		key->rsa = rsa;
1014 		key->type = KEY_RSA;
1015 		key->flags |= SSHKEY_FLAG_EXT;
1016 		rsa = NULL;	/* now owned by key */
1017 #ifdef HAVE_EC_KEY_METHOD_NEW
1018 	} else if (EVP_PKEY_base_id(evp) == EVP_PKEY_EC) {
1019 		if (EVP_PKEY_get0_EC_KEY(evp) == NULL) {
1020 			error("invalid x509; no ec key");
1021 			goto out;
1022 		}
1023 		if ((ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(evp))) == NULL) {
1024 			error("EC_KEY_dup failed");
1025 			goto out;
1026 		}
1027 
1028 		nid = sshkey_ecdsa_key_to_nid(ec);
1029 		if (nid < 0) {
1030 			error("couldn't get curve nid");
1031 			goto out;
1032 		}
1033 
1034 		if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], ec))
1035 			goto out;
1036 
1037 		key = sshkey_new(KEY_UNSPEC);
1038 		if (key == NULL) {
1039 			error("sshkey_new failed");
1040 			goto out;
1041 		}
1042 
1043 		key->ecdsa = ec;
1044 		key->ecdsa_nid = nid;
1045 		key->type = KEY_ECDSA;
1046 		key->flags |= SSHKEY_FLAG_EXT;
1047 		ec = NULL;	/* now owned by key */
1048 #endif /* HAVE_EC_KEY_METHOD_NEW */
1049 	} else {
1050 		error("unknown certificate key type");
1051 		goto out;
1052 	}
1053  out:
1054 	for (i = 0; i < 3; i++)
1055 		free(cert_attr[i].pValue);
1056 	X509_free(x509);
1057 	RSA_free(rsa);
1058 #ifdef OPENSSL_HAS_ECC
1059 	EC_KEY_free(ec);
1060 #endif
1061 	if (key == NULL) {
1062 		free(subject);
1063 		return -1;
1064 	}
1065 	/* success */
1066 	*keyp = key;
1067 	*labelp = subject;
1068 	return 0;
1069 }
1070 
1071 #if 0
1072 static int
1073 have_rsa_key(const RSA *rsa)
1074 {
1075 	const BIGNUM *rsa_n, *rsa_e;
1076 
1077 	RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL);
1078 	return rsa_n != NULL && rsa_e != NULL;
1079 }
1080 #endif
1081 
1082 /*
1083  * lookup certificates for token in slot identified by slotidx,
1084  * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
1085  * keysp points to an (possibly empty) array with *nkeys keys.
1086  */
1087 static int
pkcs11_fetch_certs(struct pkcs11_provider * p,CK_ULONG slotidx,struct sshkey *** keysp,char *** labelsp,int * nkeys)1088 pkcs11_fetch_certs(struct pkcs11_provider *p, CK_ULONG slotidx,
1089     struct sshkey ***keysp, char ***labelsp, int *nkeys)
1090 {
1091 	struct sshkey		*key = NULL;
1092 	CK_OBJECT_CLASS		 key_class;
1093 	CK_ATTRIBUTE		 key_attr[1];
1094 	CK_SESSION_HANDLE	 session;
1095 	CK_FUNCTION_LIST	*f = NULL;
1096 	CK_RV			 rv;
1097 	CK_OBJECT_HANDLE	 obj;
1098 	CK_ULONG		 n = 0;
1099 	int			 ret = -1;
1100 	char			*label;
1101 
1102 	memset(&key_attr, 0, sizeof(key_attr));
1103 	memset(&obj, 0, sizeof(obj));
1104 
1105 	key_class = CKO_CERTIFICATE;
1106 	key_attr[0].type = CKA_CLASS;
1107 	key_attr[0].pValue = &key_class;
1108 	key_attr[0].ulValueLen = sizeof(key_class);
1109 
1110 	session = p->slotinfo[slotidx].session;
1111 	f = p->function_list;
1112 
1113 	rv = f->C_FindObjectsInit(session, key_attr, 1);
1114 	if (rv != CKR_OK) {
1115 		error("C_FindObjectsInit failed: %lu", rv);
1116 		goto fail;
1117 	}
1118 
1119 	while (1) {
1120 		CK_CERTIFICATE_TYPE	ck_cert_type;
1121 
1122 		rv = f->C_FindObjects(session, &obj, 1, &n);
1123 		if (rv != CKR_OK) {
1124 			error("C_FindObjects failed: %lu", rv);
1125 			goto fail;
1126 		}
1127 		if (n == 0)
1128 			break;
1129 
1130 		memset(&ck_cert_type, 0, sizeof(ck_cert_type));
1131 		memset(&key_attr, 0, sizeof(key_attr));
1132 		key_attr[0].type = CKA_CERTIFICATE_TYPE;
1133 		key_attr[0].pValue = &ck_cert_type;
1134 		key_attr[0].ulValueLen = sizeof(ck_cert_type);
1135 
1136 		rv = f->C_GetAttributeValue(session, obj, key_attr, 1);
1137 		if (rv != CKR_OK) {
1138 			error("C_GetAttributeValue failed: %lu", rv);
1139 			goto fail;
1140 		}
1141 
1142 		key = NULL;
1143 		label = NULL;
1144 		switch (ck_cert_type) {
1145 		case CKC_X_509:
1146 			if (pkcs11_fetch_x509_pubkey(p, slotidx, &obj,
1147 			    &key, &label) != 0) {
1148 				error("failed to fetch key");
1149 				continue;
1150 			}
1151 			break;
1152 		default:
1153 			error("skipping unsupported certificate type %lu",
1154 			    ck_cert_type);
1155 			continue;
1156 		}
1157 
1158 		if (pkcs11_key_included(keysp, nkeys, key)) {
1159 			sshkey_free(key);
1160 		} else {
1161 			/* expand key array and add key */
1162 			*keysp = xrecallocarray(*keysp, *nkeys,
1163 			    *nkeys + 1, sizeof(struct sshkey *));
1164 			(*keysp)[*nkeys] = key;
1165 			if (labelsp != NULL) {
1166 				*labelsp = xrecallocarray(*labelsp, *nkeys,
1167 				    *nkeys + 1, sizeof(char *));
1168 				(*labelsp)[*nkeys] = xstrdup((char *)label);
1169 			}
1170 			*nkeys = *nkeys + 1;
1171 			debug("have %d keys", *nkeys);
1172 		}
1173 	}
1174 
1175 	ret = 0;
1176 fail:
1177 	rv = f->C_FindObjectsFinal(session);
1178 	if (rv != CKR_OK) {
1179 		error("C_FindObjectsFinal failed: %lu", rv);
1180 		ret = -1;
1181 	}
1182 
1183 	return (ret);
1184 }
1185 
1186 /*
1187  * lookup public keys for token in slot identified by slotidx,
1188  * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
1189  * keysp points to an (possibly empty) array with *nkeys keys.
1190  */
1191 static int
pkcs11_fetch_keys(struct pkcs11_provider * p,CK_ULONG slotidx,struct sshkey *** keysp,char *** labelsp,int * nkeys)1192 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
1193     struct sshkey ***keysp, char ***labelsp, int *nkeys)
1194 {
1195 	struct sshkey		*key = NULL;
1196 	CK_OBJECT_CLASS		 key_class;
1197 	CK_ATTRIBUTE		 key_attr[2];
1198 	CK_SESSION_HANDLE	 session;
1199 	CK_FUNCTION_LIST	*f = NULL;
1200 	CK_RV			 rv;
1201 	CK_OBJECT_HANDLE	 obj;
1202 	CK_ULONG		 n = 0;
1203 	int			 ret = -1;
1204 
1205 	memset(&key_attr, 0, sizeof(key_attr));
1206 	memset(&obj, 0, sizeof(obj));
1207 
1208 	key_class = CKO_PUBLIC_KEY;
1209 	key_attr[0].type = CKA_CLASS;
1210 	key_attr[0].pValue = &key_class;
1211 	key_attr[0].ulValueLen = sizeof(key_class);
1212 
1213 	session = p->slotinfo[slotidx].session;
1214 	f = p->function_list;
1215 
1216 	rv = f->C_FindObjectsInit(session, key_attr, 1);
1217 	if (rv != CKR_OK) {
1218 		error("C_FindObjectsInit failed: %lu", rv);
1219 		goto fail;
1220 	}
1221 
1222 	while (1) {
1223 		CK_KEY_TYPE	ck_key_type;
1224 		CK_UTF8CHAR	label[256];
1225 
1226 		rv = f->C_FindObjects(session, &obj, 1, &n);
1227 		if (rv != CKR_OK) {
1228 			error("C_FindObjects failed: %lu", rv);
1229 			goto fail;
1230 		}
1231 		if (n == 0)
1232 			break;
1233 
1234 		memset(&ck_key_type, 0, sizeof(ck_key_type));
1235 		memset(&key_attr, 0, sizeof(key_attr));
1236 		key_attr[0].type = CKA_KEY_TYPE;
1237 		key_attr[0].pValue = &ck_key_type;
1238 		key_attr[0].ulValueLen = sizeof(ck_key_type);
1239 		key_attr[1].type = CKA_LABEL;
1240 		key_attr[1].pValue = &label;
1241 		key_attr[1].ulValueLen = sizeof(label) - 1;
1242 
1243 		rv = f->C_GetAttributeValue(session, obj, key_attr, 2);
1244 		if (rv != CKR_OK) {
1245 			error("C_GetAttributeValue failed: %lu", rv);
1246 			goto fail;
1247 		}
1248 
1249 		label[key_attr[1].ulValueLen] = '\0';
1250 
1251 		switch (ck_key_type) {
1252 		case CKK_RSA:
1253 			key = pkcs11_fetch_rsa_pubkey(p, slotidx, &obj);
1254 			break;
1255 #ifdef HAVE_EC_KEY_METHOD_NEW
1256 		case CKK_ECDSA:
1257 			key = pkcs11_fetch_ecdsa_pubkey(p, slotidx, &obj);
1258 			break;
1259 #endif /* HAVE_EC_KEY_METHOD_NEW */
1260 		default:
1261 			/* XXX print key type? */
1262 			key = NULL;
1263 			error("skipping unsupported key type");
1264 		}
1265 
1266 		if (key == NULL) {
1267 			error("failed to fetch key");
1268 			continue;
1269 		}
1270 
1271 		if (pkcs11_key_included(keysp, nkeys, key)) {
1272 			sshkey_free(key);
1273 		} else {
1274 			/* expand key array and add key */
1275 			*keysp = xrecallocarray(*keysp, *nkeys,
1276 			    *nkeys + 1, sizeof(struct sshkey *));
1277 			(*keysp)[*nkeys] = key;
1278 			if (labelsp != NULL) {
1279 				*labelsp = xrecallocarray(*labelsp, *nkeys,
1280 				    *nkeys + 1, sizeof(char *));
1281 				(*labelsp)[*nkeys] = xstrdup((char *)label);
1282 			}
1283 			*nkeys = *nkeys + 1;
1284 			debug("have %d keys", *nkeys);
1285 		}
1286 	}
1287 
1288 	ret = 0;
1289 fail:
1290 	rv = f->C_FindObjectsFinal(session);
1291 	if (rv != CKR_OK) {
1292 		error("C_FindObjectsFinal failed: %lu", rv);
1293 		ret = -1;
1294 	}
1295 
1296 	return (ret);
1297 }
1298 
1299 #ifdef WITH_PKCS11_KEYGEN
1300 #define FILL_ATTR(attr, idx, typ, val, len) \
1301 	{ (attr[idx]).type=(typ); (attr[idx]).pValue=(val); (attr[idx]).ulValueLen=len; idx++; }
1302 
1303 static struct sshkey *
pkcs11_rsa_generate_private_key(struct pkcs11_provider * p,CK_ULONG slotidx,char * label,CK_ULONG bits,CK_BYTE keyid,u_int32_t * err)1304 pkcs11_rsa_generate_private_key(struct pkcs11_provider *p, CK_ULONG slotidx,
1305     char *label, CK_ULONG bits, CK_BYTE keyid, u_int32_t *err)
1306 {
1307 	struct pkcs11_slotinfo	*si;
1308 	char			*plabel = label ? label : "";
1309 	int			 npub = 0, npriv = 0;
1310 	CK_RV			 rv;
1311 	CK_FUNCTION_LIST	*f;
1312 	CK_SESSION_HANDLE	 session;
1313 	CK_BBOOL		 true_val = CK_TRUE, false_val = CK_FALSE;
1314 	CK_OBJECT_HANDLE	 pubKey, privKey;
1315 	CK_ATTRIBUTE		 tpub[16], tpriv[16];
1316 	CK_MECHANISM		 mech = {
1317 	    CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0
1318 	};
1319 	CK_BYTE			 pubExponent[] = {
1320 	    0x01, 0x00, 0x01 /* RSA_F4 in bytes */
1321 	};
1322 	pubkey_filter[0].pValue = &pubkey_class;
1323 	cert_filter[0].pValue = &cert_class;
1324 
1325 	*err = 0;
1326 
1327 	FILL_ATTR(tpub, npub, CKA_TOKEN, &true_val, sizeof(true_val));
1328 	FILL_ATTR(tpub, npub, CKA_LABEL, plabel, strlen(plabel));
1329 	FILL_ATTR(tpub, npub, CKA_ENCRYPT, &false_val, sizeof(false_val));
1330 	FILL_ATTR(tpub, npub, CKA_VERIFY, &true_val, sizeof(true_val));
1331 	FILL_ATTR(tpub, npub, CKA_VERIFY_RECOVER, &false_val,
1332 	    sizeof(false_val));
1333 	FILL_ATTR(tpub, npub, CKA_WRAP, &false_val, sizeof(false_val));
1334 	FILL_ATTR(tpub, npub, CKA_DERIVE, &false_val, sizeof(false_val));
1335 	FILL_ATTR(tpub, npub, CKA_MODULUS_BITS, &bits, sizeof(bits));
1336 	FILL_ATTR(tpub, npub, CKA_PUBLIC_EXPONENT, pubExponent,
1337 	    sizeof(pubExponent));
1338 	FILL_ATTR(tpub, npub, CKA_ID, &keyid, sizeof(keyid));
1339 
1340 	FILL_ATTR(tpriv, npriv, CKA_TOKEN,  &true_val, sizeof(true_val));
1341 	FILL_ATTR(tpriv, npriv, CKA_LABEL,  plabel, strlen(plabel));
1342 	FILL_ATTR(tpriv, npriv, CKA_PRIVATE,  &true_val, sizeof(true_val));
1343 	FILL_ATTR(tpriv, npriv, CKA_SENSITIVE,  &true_val, sizeof(true_val));
1344 	FILL_ATTR(tpriv, npriv, CKA_DECRYPT,  &false_val, sizeof(false_val));
1345 	FILL_ATTR(tpriv, npriv, CKA_SIGN,  &true_val, sizeof(true_val));
1346 	FILL_ATTR(tpriv, npriv, CKA_SIGN_RECOVER,  &false_val,
1347 	    sizeof(false_val));
1348 	FILL_ATTR(tpriv, npriv, CKA_UNWRAP,  &false_val, sizeof(false_val));
1349 	FILL_ATTR(tpriv, npriv, CKA_DERIVE,  &false_val, sizeof(false_val));
1350 	FILL_ATTR(tpriv, npriv, CKA_ID, &keyid, sizeof(keyid));
1351 
1352 	f = p->function_list;
1353 	si = &p->slotinfo[slotidx];
1354 	session = si->session;
1355 
1356 	if ((rv = f->C_GenerateKeyPair(session, &mech, tpub, npub, tpriv, npriv,
1357 	    &pubKey, &privKey)) != CKR_OK) {
1358 		error("%s: key generation failed: error 0x%lx", __func__, rv);
1359 		*err = rv;
1360 		return NULL;
1361 	}
1362 
1363 	return pkcs11_fetch_rsa_pubkey(p, slotidx, &pubKey);
1364 }
1365 
1366 static int
pkcs11_decode_hex(const char * hex,unsigned char ** dest,size_t * rlen)1367 pkcs11_decode_hex(const char *hex, unsigned char **dest, size_t *rlen)
1368 {
1369 	size_t	i, len;
1370 	char	ptr[3];
1371 
1372 	if (dest)
1373 		*dest = NULL;
1374 	if (rlen)
1375 		*rlen = 0;
1376 
1377 	if ((len = strlen(hex)) % 2)
1378 		return -1;
1379 	len /= 2;
1380 
1381 	*dest = xmalloc(len);
1382 
1383 	ptr[2] = '\0';
1384 	for (i = 0; i < len; i++) {
1385 		ptr[0] = hex[2 * i];
1386 		ptr[1] = hex[(2 * i) + 1];
1387 		if (!isxdigit(ptr[0]) || !isxdigit(ptr[1]))
1388 			return -1;
1389 		(*dest)[i] = (unsigned char)strtoul(ptr, NULL, 16);
1390 	}
1391 
1392 	if (rlen)
1393 		*rlen = len;
1394 
1395 	return 0;
1396 }
1397 
1398 static struct ec_curve_info {
1399 	const char	*name;
1400 	const char	*oid;
1401 	const char	*oid_encoded;
1402 	size_t		 size;
1403 } ec_curve_infos[] = {
1404 	{"prime256v1",	"1.2.840.10045.3.1.7",	"06082A8648CE3D030107", 256},
1405 	{"secp384r1",	"1.3.132.0.34",		"06052B81040022",	384},
1406 	{"secp521r1",	"1.3.132.0.35",		"06052B81040023",	521},
1407 	{NULL,		NULL,			NULL,			0},
1408 };
1409 
1410 static struct sshkey *
pkcs11_ecdsa_generate_private_key(struct pkcs11_provider * p,CK_ULONG slotidx,char * label,CK_ULONG bits,CK_BYTE keyid,u_int32_t * err)1411 pkcs11_ecdsa_generate_private_key(struct pkcs11_provider *p, CK_ULONG slotidx,
1412     char *label, CK_ULONG bits, CK_BYTE keyid, u_int32_t *err)
1413 {
1414 	struct pkcs11_slotinfo	*si;
1415 	char			*plabel = label ? label : "";
1416 	int			 i;
1417 	size_t			 ecparams_size;
1418 	unsigned char		*ecparams = NULL;
1419 	int			 npub = 0, npriv = 0;
1420 	CK_RV			 rv;
1421 	CK_FUNCTION_LIST	*f;
1422 	CK_SESSION_HANDLE	 session;
1423 	CK_BBOOL		 true_val = CK_TRUE, false_val = CK_FALSE;
1424 	CK_OBJECT_HANDLE	 pubKey, privKey;
1425 	CK_MECHANISM		 mech = {
1426 	    CKM_EC_KEY_PAIR_GEN, NULL_PTR, 0
1427 	};
1428 	CK_ATTRIBUTE		 tpub[16], tpriv[16];
1429 
1430 	*err = 0;
1431 
1432 	for (i = 0; ec_curve_infos[i].name; i++) {
1433 		if (ec_curve_infos[i].size == bits)
1434 			break;
1435 	}
1436 	if (!ec_curve_infos[i].name) {
1437 		error("%s: invalid key size %lu", __func__, bits);
1438 		return NULL;
1439 	}
1440 	if (pkcs11_decode_hex(ec_curve_infos[i].oid_encoded, &ecparams,
1441 	    &ecparams_size) == -1) {
1442 		error("%s: invalid oid", __func__);
1443 		return NULL;
1444 	}
1445 
1446 	FILL_ATTR(tpub, npub, CKA_TOKEN, &true_val, sizeof(true_val));
1447 	FILL_ATTR(tpub, npub, CKA_LABEL, plabel, strlen(plabel));
1448 	FILL_ATTR(tpub, npub, CKA_ENCRYPT, &false_val, sizeof(false_val));
1449 	FILL_ATTR(tpub, npub, CKA_VERIFY, &true_val, sizeof(true_val));
1450 	FILL_ATTR(tpub, npub, CKA_VERIFY_RECOVER, &false_val,
1451 	    sizeof(false_val));
1452 	FILL_ATTR(tpub, npub, CKA_WRAP, &false_val, sizeof(false_val));
1453 	FILL_ATTR(tpub, npub, CKA_DERIVE, &false_val, sizeof(false_val));
1454 	FILL_ATTR(tpub, npub, CKA_EC_PARAMS, ecparams, ecparams_size);
1455 	FILL_ATTR(tpub, npub, CKA_ID, &keyid, sizeof(keyid));
1456 
1457 	FILL_ATTR(tpriv, npriv, CKA_TOKEN, &true_val, sizeof(true_val));
1458 	FILL_ATTR(tpriv, npriv, CKA_LABEL, plabel, strlen(plabel));
1459 	FILL_ATTR(tpriv, npriv, CKA_PRIVATE, &true_val, sizeof(true_val));
1460 	FILL_ATTR(tpriv, npriv, CKA_SENSITIVE, &true_val, sizeof(true_val));
1461 	FILL_ATTR(tpriv, npriv, CKA_DECRYPT, &false_val, sizeof(false_val));
1462 	FILL_ATTR(tpriv, npriv, CKA_SIGN, &true_val, sizeof(true_val));
1463 	FILL_ATTR(tpriv, npriv, CKA_SIGN_RECOVER, &false_val,
1464 	    sizeof(false_val));
1465 	FILL_ATTR(tpriv, npriv, CKA_UNWRAP, &false_val, sizeof(false_val));
1466 	FILL_ATTR(tpriv, npriv, CKA_DERIVE, &false_val, sizeof(false_val));
1467 	FILL_ATTR(tpriv, npriv, CKA_ID, &keyid, sizeof(keyid));
1468 
1469 	f = p->function_list;
1470 	si = &p->slotinfo[slotidx];
1471 	session = si->session;
1472 
1473 	if ((rv = f->C_GenerateKeyPair(session, &mech, tpub, npub, tpriv, npriv,
1474 	    &pubKey, &privKey)) != CKR_OK) {
1475 		error("%s: key generation failed: error 0x%lx", __func__, rv);
1476 		*err = rv;
1477 		return NULL;
1478 	}
1479 
1480 	return pkcs11_fetch_ecdsa_pubkey(p, slotidx, &pubKey);
1481 }
1482 #endif /* WITH_PKCS11_KEYGEN */
1483 
1484 /*
1485  * register a new provider, fails if provider already exists. if
1486  * keyp is provided, fetch keys.
1487  */
1488 static int
pkcs11_register_provider(char * provider_id,char * pin,struct sshkey *** keyp,char *** labelsp,struct pkcs11_provider ** providerp,CK_ULONG user)1489 pkcs11_register_provider(char *provider_id, char *pin,
1490     struct sshkey ***keyp, char ***labelsp,
1491     struct pkcs11_provider **providerp, CK_ULONG user)
1492 {
1493 	int nkeys, need_finalize = 0;
1494 	int ret = -1;
1495 	struct pkcs11_provider *p = NULL;
1496 	void *handle = NULL;
1497 	CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
1498 	CK_RV rv;
1499 	CK_FUNCTION_LIST *f = NULL;
1500 	CK_TOKEN_INFO *token;
1501 	CK_ULONG i;
1502 
1503 	if (providerp == NULL)
1504 		goto fail;
1505 	*providerp = NULL;
1506 
1507 	if (keyp != NULL)
1508 		*keyp = NULL;
1509 	if (labelsp != NULL)
1510 		*labelsp = NULL;
1511 
1512 	if (pkcs11_provider_lookup(provider_id) != NULL) {
1513 		debug("%s: provider already registered: %s",
1514 		    __func__, provider_id);
1515 		goto fail;
1516 	}
1517 	/* open shared pkcs11-library */
1518 	if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
1519 		error("dlopen %s failed: %s", provider_id, dlerror());
1520 		goto fail;
1521 	}
1522 	if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
1523 		error("dlsym(C_GetFunctionList) failed: %s", dlerror());
1524 		goto fail;
1525 	}
1526 	p = xcalloc(1, sizeof(*p));
1527 	p->name = xstrdup(provider_id);
1528 	p->handle = handle;
1529 	/* setup the pkcs11 callbacks */
1530 	if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
1531 		error("C_GetFunctionList for provider %s failed: %lu",
1532 		    provider_id, rv);
1533 		goto fail;
1534 	}
1535 	p->function_list = f;
1536 	if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
1537 		error("C_Initialize for provider %s failed: %lu",
1538 		    provider_id, rv);
1539 		goto fail;
1540 	}
1541 	need_finalize = 1;
1542 	if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
1543 		error("C_GetInfo for provider %s failed: %lu",
1544 		    provider_id, rv);
1545 		goto fail;
1546 	}
1547 	rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
1548 	rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
1549 	debug("provider %s: manufacturerID <%s> cryptokiVersion %d.%d"
1550 	    " libraryDescription <%s> libraryVersion %d.%d",
1551 	    provider_id,
1552 	    p->info.manufacturerID,
1553 	    p->info.cryptokiVersion.major,
1554 	    p->info.cryptokiVersion.minor,
1555 	    p->info.libraryDescription,
1556 	    p->info.libraryVersion.major,
1557 	    p->info.libraryVersion.minor);
1558 	if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
1559 		error("C_GetSlotList failed: %lu", rv);
1560 		goto fail;
1561 	}
1562 	if (p->nslots == 0) {
1563 		debug("%s: provider %s returned no slots", __func__,
1564 		    provider_id);
1565 		ret = -SSH_PKCS11_ERR_NO_SLOTS;
1566 		goto fail;
1567 	}
1568 	p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
1569 	if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
1570 	    != CKR_OK) {
1571 		error("C_GetSlotList for provider %s failed: %lu",
1572 		    provider_id, rv);
1573 		goto fail;
1574 	}
1575 	p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
1576 	p->valid = 1;
1577 	nkeys = 0;
1578 	for (i = 0; i < p->nslots; i++) {
1579 		token = &p->slotinfo[i].token;
1580 		if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
1581 		    != CKR_OK) {
1582 			error("C_GetTokenInfo for provider %s slot %lu "
1583 			    "failed: %lu", provider_id, (unsigned long)i, rv);
1584 			continue;
1585 		}
1586 		if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
1587 			debug2("%s: ignoring uninitialised token in "
1588 			    "provider %s slot %lu", __func__,
1589 			    provider_id, (unsigned long)i);
1590 			continue;
1591 		}
1592 		rmspace(token->label, sizeof(token->label));
1593 		rmspace(token->manufacturerID, sizeof(token->manufacturerID));
1594 		rmspace(token->model, sizeof(token->model));
1595 		rmspace(token->serialNumber, sizeof(token->serialNumber));
1596 		debug("provider %s slot %lu: label <%s> manufacturerID <%s> "
1597 		    "model <%s> serial <%s> flags 0x%lx",
1598 		    provider_id, (unsigned long)i,
1599 		    token->label, token->manufacturerID, token->model,
1600 		    token->serialNumber, token->flags);
1601 		/*
1602 		 * open session, login with pin and retrieve public
1603 		 * keys (if keyp is provided)
1604 		 */
1605 		if ((ret = pkcs11_open_session(p, i, pin, user)) != 0 ||
1606 		    keyp == NULL)
1607 			continue;
1608 		pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
1609 		pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
1610 		if (nkeys == 0 && !p->slotinfo[i].logged_in &&
1611 		    pkcs11_interactive) {
1612 			/*
1613 			 * Some tokens require login before they will
1614 			 * expose keys.
1615 			 */
1616 			if (pkcs11_login_slot(p, &p->slotinfo[i],
1617 			    CKU_USER) < 0) {
1618 				error("login failed");
1619 				continue;
1620 			}
1621 			pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
1622 			pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
1623 		}
1624 	}
1625 
1626 	/* now owned by caller */
1627 	*providerp = p;
1628 
1629 	TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
1630 	p->refcount++;	/* add to provider list */
1631 
1632 	return (nkeys);
1633 fail:
1634 	if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
1635 		error("C_Finalize for provider %s failed: %lu",
1636 		    provider_id, rv);
1637 	if (p) {
1638 		free(p->name);
1639 		free(p->slotlist);
1640 		free(p->slotinfo);
1641 		free(p);
1642 	}
1643 	if (handle)
1644 		dlclose(handle);
1645 	if (ret > 0)
1646 		ret = -1;
1647 	return (ret);
1648 }
1649 
1650 /*
1651  * register a new provider and get number of keys hold by the token,
1652  * fails if provider already exists
1653  */
1654 int
pkcs11_add_provider(char * provider_id,char * pin,struct sshkey *** keyp,char *** labelsp)1655 pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp,
1656     char ***labelsp)
1657 {
1658 	struct pkcs11_provider *p = NULL;
1659 	int nkeys;
1660 
1661 	nkeys = pkcs11_register_provider(provider_id, pin, keyp, labelsp,
1662 	    &p, CKU_USER);
1663 
1664 	/* no keys found or some other error, de-register provider */
1665 	if (nkeys <= 0 && p != NULL) {
1666 		TAILQ_REMOVE(&pkcs11_providers, p, next);
1667 		pkcs11_provider_finalize(p);
1668 		pkcs11_provider_unref(p);
1669 	}
1670 	if (nkeys == 0)
1671 		debug("%s: provider %s returned no keys", __func__,
1672 		    provider_id);
1673 
1674 	return (nkeys);
1675 }
1676 
1677 #ifdef WITH_PKCS11_KEYGEN
1678 struct sshkey *
pkcs11_gakp(char * provider_id,char * pin,unsigned int slotidx,char * label,unsigned int type,unsigned int bits,unsigned char keyid,u_int32_t * err)1679 pkcs11_gakp(char *provider_id, char *pin, unsigned int slotidx, char *label,
1680     unsigned int type, unsigned int bits, unsigned char keyid, u_int32_t *err)
1681 {
1682 	struct pkcs11_provider	*p = NULL;
1683 	struct pkcs11_slotinfo	*si;
1684 	CK_FUNCTION_LIST	*f;
1685 	CK_SESSION_HANDLE	 session;
1686 	struct sshkey		*k = NULL;
1687 	int			 ret = -1, reset_pin = 0, reset_provider = 0;
1688 	CK_RV			 rv;
1689 
1690 	*err = 0;
1691 
1692 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL)
1693 		debug("%s: provider \"%s\" available", __func__, provider_id);
1694 	else if ((ret = pkcs11_register_provider(provider_id, pin, NULL, NULL,
1695 	    &p, CKU_SO)) < 0) {
1696 		debug("%s: could not register provider %s", __func__,
1697 		    provider_id);
1698 		goto out;
1699 	} else
1700 		reset_provider = 1;
1701 
1702 	f = p->function_list;
1703 	si = &p->slotinfo[slotidx];
1704 	session = si->session;
1705 
1706 	if ((rv = f->C_SetOperationState(session , pin, strlen(pin),
1707 	    CK_INVALID_HANDLE, CK_INVALID_HANDLE)) != CKR_OK) {
1708 		debug("%s: could not supply SO pin: %lu", __func__, rv);
1709 		reset_pin = 0;
1710 	} else
1711 		reset_pin = 1;
1712 
1713 	switch (type) {
1714 	case KEY_RSA:
1715 		if ((k = pkcs11_rsa_generate_private_key(p, slotidx, label,
1716 		    bits, keyid, err)) == NULL) {
1717 			debug("%s: failed to generate RSA key", __func__);
1718 			goto out;
1719 		}
1720 		break;
1721 	case KEY_ECDSA:
1722 		if ((k = pkcs11_ecdsa_generate_private_key(p, slotidx, label,
1723 		    bits, keyid, err)) == NULL) {
1724 			debug("%s: failed to generate ECDSA key", __func__);
1725 			goto out;
1726 		}
1727 		break;
1728 	default:
1729 		*err = SSH_PKCS11_ERR_GENERIC;
1730 		debug("%s: unknown type %d", __func__, type);
1731 		goto out;
1732 	}
1733 
1734 out:
1735 	if (reset_pin)
1736 		f->C_SetOperationState(session , NULL, 0, CK_INVALID_HANDLE,
1737 		    CK_INVALID_HANDLE);
1738 
1739 	if (reset_provider)
1740 		pkcs11_del_provider(provider_id);
1741 
1742 	return (k);
1743 }
1744 
1745 struct sshkey *
pkcs11_destroy_keypair(char * provider_id,char * pin,unsigned long slotidx,unsigned char keyid,u_int32_t * err)1746 pkcs11_destroy_keypair(char *provider_id, char *pin, unsigned long slotidx,
1747     unsigned char keyid, u_int32_t *err)
1748 {
1749 	struct pkcs11_provider	*p = NULL;
1750 	struct pkcs11_slotinfo	*si;
1751 	struct sshkey		*k = NULL;
1752 	int			 reset_pin = 0, reset_provider = 0;
1753 	CK_ULONG		 nattrs;
1754 	CK_FUNCTION_LIST	*f;
1755 	CK_SESSION_HANDLE	 session;
1756 	CK_ATTRIBUTE		 attrs[16];
1757 	CK_OBJECT_CLASS		 key_class;
1758 	CK_KEY_TYPE		 key_type;
1759 	CK_OBJECT_HANDLE	 obj = CK_INVALID_HANDLE;
1760 	CK_RV			 rv;
1761 
1762 	*err = 0;
1763 
1764 	if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
1765 		debug("%s: using provider \"%s\"", __func__, provider_id);
1766 	} else if (pkcs11_register_provider(provider_id, pin, NULL, NULL, &p,
1767 	    CKU_SO) < 0) {
1768 		debug("%s: could not register provider %s", __func__,
1769 		    provider_id);
1770 		goto out;
1771 	} else
1772 		reset_provider = 1;
1773 
1774 	f = p->function_list;
1775 	si = &p->slotinfo[slotidx];
1776 	session = si->session;
1777 
1778 	if ((rv = f->C_SetOperationState(session , pin, strlen(pin),
1779 	    CK_INVALID_HANDLE, CK_INVALID_HANDLE)) != CKR_OK) {
1780 		debug("%s: could not supply SO pin: %lu", __func__, rv);
1781 		reset_pin = 0;
1782 	} else
1783 		reset_pin = 1;
1784 
1785 	/* private key */
1786 	nattrs = 0;
1787 	key_class = CKO_PRIVATE_KEY;
1788 	FILL_ATTR(attrs, nattrs, CKA_CLASS, &key_class, sizeof(key_class));
1789 	FILL_ATTR(attrs, nattrs, CKA_ID, &keyid, sizeof(keyid));
1790 
1791 	if (pkcs11_find(p, slotidx, attrs, nattrs, &obj) == 0 &&
1792 	    obj != CK_INVALID_HANDLE) {
1793 		if ((rv = f->C_DestroyObject(session, obj)) != CKR_OK) {
1794 			debug("%s: could not destroy private key 0x%hhx",
1795 			    __func__, keyid);
1796 			*err = rv;
1797 			goto out;
1798 		}
1799 	}
1800 
1801 	/* public key */
1802 	nattrs = 0;
1803 	key_class = CKO_PUBLIC_KEY;
1804 	FILL_ATTR(attrs, nattrs, CKA_CLASS, &key_class, sizeof(key_class));
1805 	FILL_ATTR(attrs, nattrs, CKA_ID, &keyid, sizeof(keyid));
1806 
1807 	if (pkcs11_find(p, slotidx, attrs, nattrs, &obj) == 0 &&
1808 	    obj != CK_INVALID_HANDLE) {
1809 
1810 		/* get key type */
1811 		nattrs = 0;
1812 		FILL_ATTR(attrs, nattrs, CKA_KEY_TYPE, &key_type,
1813 		    sizeof(key_type));
1814 		rv = f->C_GetAttributeValue(session, obj, attrs, nattrs);
1815 		if (rv != CKR_OK) {
1816 			debug("%s: could not get key type of public key 0x%hhx",
1817 			    __func__, keyid);
1818 			*err = rv;
1819 			key_type = -1;
1820 		}
1821 		if (key_type == CKK_RSA)
1822 			k = pkcs11_fetch_rsa_pubkey(p, slotidx, &obj);
1823 		else if (key_type == CKK_ECDSA)
1824 			k = pkcs11_fetch_ecdsa_pubkey(p, slotidx, &obj);
1825 
1826 		if ((rv = f->C_DestroyObject(session, obj)) != CKR_OK) {
1827 			debug("%s: could not destroy public key 0x%hhx",
1828 			    __func__, keyid);
1829 			*err = rv;
1830 			goto out;
1831 		}
1832 	}
1833 
1834 out:
1835 	if (reset_pin)
1836 		f->C_SetOperationState(session , NULL, 0, CK_INVALID_HANDLE,
1837 		    CK_INVALID_HANDLE);
1838 
1839 	if (reset_provider)
1840 		pkcs11_del_provider(provider_id);
1841 
1842 	return (k);
1843 }
1844 #endif /* WITH_PKCS11_KEYGEN */
1845 #else /* ENABLE_PKCS11 */
1846 
1847 #include <sys/types.h>
1848 #include <stdarg.h>
1849 #include <stdio.h>
1850 
1851 #include "log.h"
1852 #include "sshkey.h"
1853 
1854 int
pkcs11_init(int interactive)1855 pkcs11_init(int interactive)
1856 {
1857 	error("%s: dlopen() not supported", __func__);
1858 	return (-1);
1859 }
1860 
1861 int
pkcs11_add_provider(char * provider_id,char * pin,struct sshkey *** keyp)1862 pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
1863 {
1864 	error("%s: dlopen() not supported", __func__);
1865 	return (-1);
1866 }
1867 
1868 void
pkcs11_terminate(void)1869 pkcs11_terminate(void)
1870 {
1871 	error("%s: dlopen() not supported", __func__);
1872 }
1873 #endif /* ENABLE_PKCS11 */
1874