blob: ec0e91865ffe4aa7212f2899b4434599f4db6f9f [file] [log] [blame]
djm@openbsd.org1d892322020-03-13 04:16:27 +00001/* $OpenBSD: ssh-pkcs11.c,v 1.49 2020/03/13 04:16:27 djm Exp $ */
Damien Miller7ea845e2010-02-12 09:21:02 +11002/*
3 * Copyright (c) 2010 Markus Friedl. All rights reserved.
djm@openbsd.org93f02102019-01-20 22:51:37 +00004 * Copyright (c) 2014 Pedro Martelletto. All rights reserved.
Damien Miller7ea845e2010-02-12 09:21:02 +11005 *
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
Damien Miller8ad0fbd2010-02-12 09:49:06 +110019#include "includes.h"
20
Damien Millerdfa41562010-02-12 10:06:28 +110021#ifdef ENABLE_PKCS11
22
Damien Miller8ad0fbd2010-02-12 09:49:06 +110023#ifdef HAVE_SYS_TIME_H
24# include <sys/time.h>
25#endif
djm@openbsd.org93f02102019-01-20 22:51:37 +000026
27#include <sys/types.h>
Damien Miller7ea845e2010-02-12 09:21:02 +110028#include <stdarg.h>
29#include <stdio.h>
30
djm@openbsd.org93f02102019-01-20 22:51:37 +000031#include <ctype.h>
Damien Miller7ea845e2010-02-12 09:21:02 +110032#include <string.h>
33#include <dlfcn.h>
34
Damien Miller8ad0fbd2010-02-12 09:49:06 +110035#include "openbsd-compat/sys-queue.h"
Damien Miller48f54b92018-09-13 12:13:50 +100036#include "openbsd-compat/openssl-compat.h"
Damien Miller8ad0fbd2010-02-12 09:49:06 +110037
djm@openbsd.org93f02102019-01-20 22:51:37 +000038#include <openssl/ecdsa.h>
Damien Millerd2252c72013-11-04 07:41:48 +110039#include <openssl/x509.h>
djm@openbsd.org93f02102019-01-20 22:51:37 +000040#include <openssl/err.h>
Damien Millerd2252c72013-11-04 07:41:48 +110041
Damien Miller7ea845e2010-02-12 09:21:02 +110042#define CRYPTOKI_COMPAT
43#include "pkcs11.h"
44
45#include "log.h"
46#include "misc.h"
djm@openbsd.org1129dcf2015-01-15 09:40:00 +000047#include "sshkey.h"
Damien Miller7ea845e2010-02-12 09:21:02 +110048#include "ssh-pkcs11.h"
49#include "xmalloc.h"
50
51struct pkcs11_slotinfo {
52 CK_TOKEN_INFO token;
53 CK_SESSION_HANDLE session;
54 int logged_in;
55};
56
57struct 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
70TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
71
72struct pkcs11_key {
73 struct pkcs11_provider *provider;
74 CK_ULONG slotidx;
Damien Miller7ea845e2010-02-12 09:21:02 +110075 char *keyid;
76 int keyid_len;
77};
78
79int pkcs11_interactive = 0;
80
Damien Miller2efcf812019-01-21 11:57:21 +110081#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +000082static void
83ossl_error(const char *msg)
84{
djm@openbsd.org65294092019-01-20 23:11:11 +000085 unsigned long e;
djm@openbsd.org93f02102019-01-20 22:51:37 +000086
djm@openbsd.org662be402019-01-21 02:05:38 +000087 error("%s: %s", __func__, msg);
djm@openbsd.org65294092019-01-20 23:11:11 +000088 while ((e = ERR_get_error()) != 0)
djm@openbsd.org662be402019-01-21 02:05:38 +000089 error("%s: libcrypto error: %.100s", __func__,
djm@openbsd.org65294092019-01-20 23:11:11 +000090 ERR_error_string(e, NULL));
djm@openbsd.org93f02102019-01-20 22:51:37 +000091}
Damien Miller2efcf812019-01-21 11:57:21 +110092#endif /* HAVE_EC_KEY_METHOD_NEW */
djm@openbsd.org93f02102019-01-20 22:51:37 +000093
Damien Miller7ea845e2010-02-12 09:21:02 +110094int
95pkcs11_init(int interactive)
96{
97 pkcs11_interactive = interactive;
98 TAILQ_INIT(&pkcs11_providers);
99 return (0);
100}
101
102/*
djm@openbsd.org93f02102019-01-20 22:51:37 +0000103 * finalize a provider shared library, it's no longer usable.
Damien Miller7ea845e2010-02-12 09:21:02 +1100104 * however, there might still be keys referencing this provider,
djm@openbsd.org93f02102019-01-20 22:51:37 +0000105 * so the actual freeing of memory is handled by pkcs11_provider_unref().
Damien Miller7ea845e2010-02-12 09:21:02 +1100106 * this is called when a provider gets unregistered.
107 */
108static void
109pkcs11_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 */
135static void
136pkcs11_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);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000142 free(p->name);
Darren Tuckera627d422013-06-02 07:31:17 +1000143 free(p->slotlist);
144 free(p->slotinfo);
145 free(p);
Damien Miller7ea845e2010-02-12 09:21:02 +1100146 }
147}
148
149/* unregister all providers, keys might still point to the providers */
150void
151pkcs11_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 */
163static struct pkcs11_provider *
164pkcs11_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 */
177int
178pkcs11_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
djm@openbsd.orgce46c3a2019-01-21 02:01:03 +0000191static RSA_METHOD *rsa_method;
192static int rsa_idx = 0;
Damien Miller23490a62019-01-21 15:05:43 +1100193#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.orgce46c3a2019-01-21 02:01:03 +0000194static EC_KEY_METHOD *ec_key_method;
195static int ec_key_idx = 0;
Darren Tuckerb6dd3272019-01-21 13:50:17 +1100196#endif
djm@openbsd.orgce46c3a2019-01-21 02:01:03 +0000197
djm@openbsd.org58622a82019-01-20 23:10:33 +0000198/* release a wrapped object */
199static void
200pkcs11_k11_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
201 long argl, void *argp)
Damien Miller7ea845e2010-02-12 09:21:02 +1100202{
Darren Tucker5590f532019-04-26 18:22:10 +1000203 struct pkcs11_key *k11 = ptr;
Damien Miller7ea845e2010-02-12 09:21:02 +1100204
Darren Tucker5590f532019-04-26 18:22:10 +1000205 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);
Damien Miller7ea845e2010-02-12 09:21:02 +1100212}
213
Damien Miller031c9102010-04-16 15:54:44 +1000214/* find a single 'obj' for given attributes */
215static int
216pkcs11_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
Damien Miller7ea845e2010-02-12 09:21:02 +1100242static int
djm@openbsd.org7d6034b2019-09-05 10:05:51 +0000243pkcs11_login_slot(struct pkcs11_provider *provider, struct pkcs11_slotinfo *si,
244 CK_USER_TYPE type)
djm@openbsd.org21621712019-01-22 12:00:50 +0000245{
djm@openbsd.org21621712019-01-22 12:00:50 +0000246 char *pin = NULL, prompt[1024];
247 CK_RV rv;
248
djm@openbsd.org7d6034b2019-09-05 10:05:51 +0000249 if (provider == NULL || si == NULL || !provider->valid) {
djm@openbsd.org21621712019-01-22 12:00:50 +0000250 error("no pkcs11 (valid) provider found");
251 return (-1);
252 }
253
djm@openbsd.org21621712019-01-22 12:00:50 +0000254 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 }
djm@openbsd.org7d6034b2019-09-05 10:05:51 +0000270 rv = provider->function_list->C_Login(si->session, type, (u_char *)pin,
djm@openbsd.org21621712019-01-22 12:00:50 +0000271 (pin != NULL) ? strlen(pin) : 0);
272 if (pin != NULL)
273 freezero(pin, strlen(pin));
djm@openbsd.org1d892322020-03-13 04:16:27 +0000274
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;
djm@openbsd.org21621712019-01-22 12:00:50 +0000292 }
293 si->logged_in = 1;
294 return (0);
295}
296
297static int
djm@openbsd.org7d6034b2019-09-05 10:05:51 +0000298pkcs11_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
310static int
djm@openbsd.org21621712019-01-22 12:00:50 +0000311pkcs11_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
345static int
djm@openbsd.org93f02102019-01-20 22:51:37 +0000346pkcs11_get_key(struct pkcs11_key *k11, CK_MECHANISM_TYPE mech_type)
Damien Miller7ea845e2010-02-12 09:21:02 +1100347{
Damien Miller7ea845e2010-02-12 09:21:02 +1100348 struct pkcs11_slotinfo *si;
349 CK_FUNCTION_LIST *f;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000350 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];
djm@openbsd.org21621712019-01-22 12:00:50 +0000356 int always_auth = 0;
357 int did_login = 0;
Damien Miller7ea845e2010-02-12 09:21:02 +1100358
Damien Miller7ea845e2010-02-12 09:21:02 +1100359 if (!k11->provider || !k11->provider->valid) {
djm@openbsd.org93f02102019-01-20 22:51:37 +0000360 error("no pkcs11 (valid) provider found");
Damien Miller7ea845e2010-02-12 09:21:02 +1100361 return (-1);
362 }
djm@openbsd.org93f02102019-01-20 22:51:37 +0000363
Damien Miller7ea845e2010-02-12 09:21:02 +1100364 f = k11->provider->function_list;
365 si = &k11->provider->slotinfo[k11->slotidx];
djm@openbsd.org93f02102019-01-20 22:51:37 +0000366
Damien Miller7ea845e2010-02-12 09:21:02 +1100367 if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
djm@openbsd.org21621712019-01-22 12:00:50 +0000368 if (pkcs11_login(k11, CKU_USER) < 0) {
369 error("login failed");
Damien Miller7ea845e2010-02-12 09:21:02 +1100370 return (-1);
371 }
djm@openbsd.org21621712019-01-22 12:00:50 +0000372 did_login = 1;
Damien Miller7ea845e2010-02-12 09:21:02 +1100373 }
djm@openbsd.org93f02102019-01-20 22:51:37 +0000374
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;
Damien Miller7ea845e2010-02-12 09:21:02 +1100382 key_filter[1].pValue = k11->keyid;
383 key_filter[1].ulValueLen = k11->keyid_len;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000384
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
Damien Miller031c9102010-04-16 15:54:44 +1000390 /* 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");
djm@openbsd.org93f02102019-01-20 22:51:37 +0000394 return (-1);
Damien Miller7ea845e2010-02-12 09:21:02 +1100395 }
djm@openbsd.org93f02102019-01-20 22:51:37 +0000396
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
djm@openbsd.org21621712019-01-22 12:00:50 +0000407 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
djm@openbsd.org93f02102019-01-20 22:51:37 +0000417 return (0);
418}
419
420/* openssl callback doing the actual signing operation */
421static int
422pkcs11_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
djm@openbsd.orgce46c3a2019-01-21 02:01:03 +0000432 if ((k11 = RSA_get_ex_data(rsa, rsa_idx)) == NULL) {
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000433 error("RSA_get_ex_data failed for rsa %p", rsa);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000434 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
Damien Miller7ea845e2010-02-12 09:21:02 +1100453 return (rval);
454}
455
456static int
457pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
458 int padding)
459{
460 return (-1);
461}
462
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000463static int
464pkcs11_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);
djm@openbsd.org58622a82019-01-20 23:10:33 +0000471 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);
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000475 if (!RSA_meth_set1_name(rsa_method, "pkcs11") ||
476 !RSA_meth_set_priv_enc(rsa_method, pkcs11_rsa_private_encrypt) ||
djm@openbsd.org58622a82019-01-20 23:10:33 +0000477 !RSA_meth_set_priv_dec(rsa_method, pkcs11_rsa_private_decrypt)) {
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000478 error("%s: setup pkcs11 method failed", __func__);
479 return (-1);
480 }
481 return (0);
482}
483
Damien Miller7ea845e2010-02-12 09:21:02 +1100484/* redirect private key operations for rsa key to pkcs11 token */
485static int
486pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
487 CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
488{
489 struct pkcs11_key *k11;
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000490
491 if (pkcs11_rsa_start_wrapper() == -1)
492 return (-1);
Damien Miller7ea845e2010-02-12 09:21:02 +1100493
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;
djm@openbsd.orgd2d772f2016-02-12 00:20:30 +0000500 if (k11->keyid_len > 0) {
501 k11->keyid = xmalloc(k11->keyid_len);
502 memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
503 }
djm@openbsd.orgf1185422019-01-20 23:08:24 +0000504
djm@openbsd.orgfcb1b092019-01-20 23:12:35 +0000505 RSA_set_method(rsa, rsa_method);
djm@openbsd.org58622a82019-01-20 23:10:33 +0000506 RSA_set_ex_data(rsa, rsa_idx, k11);
Damien Miller7ea845e2010-02-12 09:21:02 +1100507 return (0);
508}
509
Damien Millere2cb4452019-01-21 11:32:28 +1100510#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +0000511/* openssl callback doing the actual signing operation */
512static ECDSA_SIG *
513ecdsa_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;
djm@openbsd.org63297642019-01-21 00:47:34 +0000523 BIGNUM *r = NULL, *s = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000524
djm@openbsd.orgce46c3a2019-01-21 02:01:03 +0000525 if ((k11 = EC_KEY_get_ex_data(ec, ec_key_idx)) == NULL) {
djm@openbsd.org93f02102019-01-20 22:51:37 +0000526 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 }
djm@openbsd.org749aef32019-01-20 23:00:12 +0000547 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 }
djm@openbsd.org63297642019-01-21 00:47:34 +0000556 if ((r = BN_bin2bn(sig, bnlen, NULL)) == NULL ||
557 (s = BN_bin2bn(sig+bnlen, bnlen, NULL)) == NULL) {
djm@openbsd.org749aef32019-01-20 23:00:12 +0000558 ossl_error("d2i_ECDSA_SIG failed");
559 ECDSA_SIG_free(ret);
560 ret = NULL;
561 goto done;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000562 }
djm@openbsd.org63297642019-01-21 00:47:34 +0000563 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 */
djm@openbsd.org93f02102019-01-20 22:51:37 +0000571 done:
djm@openbsd.org63297642019-01-21 00:47:34 +0000572 BN_free(r);
573 BN_free(s);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000574 free(sig);
575
576 return (ret);
577}
578
djm@openbsd.org93f02102019-01-20 22:51:37 +0000579static int
580pkcs11_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);
djm@openbsd.org445cfce2019-01-20 23:05:52 +0000587 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);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000591 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
599static int
600pkcs11_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);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000616
djm@openbsd.orgfcb1b092019-01-20 23:12:35 +0000617 EC_KEY_set_method(ec, ec_key_method);
djm@openbsd.org445cfce2019-01-20 23:05:52 +0000618 EC_KEY_set_ex_data(ec, ec_key_idx, k11);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000619
620 return (0);
621}
Damien Millere2cb4452019-01-21 11:32:28 +1100622#endif /* HAVE_EC_KEY_METHOD_NEW */
djm@openbsd.org93f02102019-01-20 22:51:37 +0000623
Damien Miller7ea845e2010-02-12 09:21:02 +1100624/* remove trailing spaces */
625static void
Damien Miller746d1a62013-07-18 16:13:02 +1000626rmspace(u_char *buf, size_t len)
Damien Miller7ea845e2010-02-12 09:21:02 +1100627{
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 */
643static int
djm@openbsd.org93f02102019-01-20 22:51:37 +0000644pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin,
645 CK_ULONG user)
Damien Miller7ea845e2010-02-12 09:21:02 +1100646{
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000647 struct pkcs11_slotinfo *si;
Damien Miller7ea845e2010-02-12 09:21:02 +1100648 CK_FUNCTION_LIST *f;
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000649 CK_RV rv;
Damien Miller7ea845e2010-02-12 09:21:02 +1100650 CK_SESSION_HANDLE session;
djm@openbsd.org08468272019-10-01 10:22:53 +0000651 int login_required, ret;
Damien Miller7ea845e2010-02-12 09:21:02 +1100652
653 f = p->function_list;
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000654 si = &p->slotinfo[slotidx];
655
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000656 login_required = si->token.flags & CKF_LOGIN_REQUIRED;
657
658 /* fail early before opening session */
djm@openbsd.org08468272019-10-01 10:22:53 +0000659 if (login_required && !pkcs11_interactive &&
djm@openbsd.org7a7fdca2019-02-04 23:37:54 +0000660 (pin == NULL || strlen(pin) == 0)) {
Damien Miller7ea845e2010-02-12 09:21:02 +1100661 error("pin required");
djm@openbsd.org93f02102019-01-20 22:51:37 +0000662 return (-SSH_PKCS11_ERR_PIN_REQUIRED);
Damien Miller7ea845e2010-02-12 09:21:02 +1100663 }
664 if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000665 CKF_SERIAL_SESSION, NULL, NULL, &session)) != CKR_OK) {
Damien Miller7ea845e2010-02-12 09:21:02 +1100666 error("C_OpenSession failed: %lu", rv);
667 return (-1);
668 }
djm@openbsd.org08468272019-10-01 10:22:53 +0000669 if (login_required && pin != NULL && strlen(pin) != 0) {
670 rv = f->C_Login(session, user, (u_char *)pin, strlen(pin));
djm@openbsd.orgcb3bde32015-02-02 22:48:53 +0000671 if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
Damien Miller7ea845e2010-02-12 09:21:02 +1100672 error("C_Login failed: %lu", rv);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000673 ret = (rv == CKR_PIN_LOCKED) ?
674 -SSH_PKCS11_ERR_PIN_LOCKED :
675 -SSH_PKCS11_ERR_LOGIN_FAIL;
Damien Miller7ea845e2010-02-12 09:21:02 +1100676 if ((rv = f->C_CloseSession(session)) != CKR_OK)
677 error("C_CloseSession failed: %lu", rv);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000678 return (ret);
Damien Miller7ea845e2010-02-12 09:21:02 +1100679 }
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000680 si->logged_in = 1;
Damien Miller7ea845e2010-02-12 09:21:02 +1100681 }
djm@openbsd.org41923ce2019-01-22 12:03:58 +0000682 si->session = session;
Damien Miller7ea845e2010-02-12 09:21:02 +1100683 return (0);
684}
685
Damien Millerd2252c72013-11-04 07:41:48 +1100686static int
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000687pkcs11_key_included(struct sshkey ***keysp, int *nkeys, struct sshkey *key)
Damien Millerd2252c72013-11-04 07:41:48 +1100688{
689 int i;
690
691 for (i = 0; i < *nkeys; i++)
djm@openbsd.org1129dcf2015-01-15 09:40:00 +0000692 if (sshkey_equal(key, (*keysp)[i]))
Damien Millerd2252c72013-11-04 07:41:48 +1100693 return (1);
694 return (0);
695}
696
Damien Millere2cb4452019-01-21 11:32:28 +1100697#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +0000698static struct sshkey *
699pkcs11_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;
djm@openbsd.org24757c12019-01-20 23:01:59 +0000706 ASN1_OCTET_STRING *octet = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000707 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
djm@openbsd.org24757c12019-01-20 23:01:59 +0000775 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;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000785 }
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
808fail:
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);
djm@openbsd.org24757c12019-01-20 23:01:59 +0000815 if (octet)
816 ASN1_OCTET_STRING_free(octet);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000817
818 return (key);
819}
Damien Millere2cb4452019-01-21 11:32:28 +1100820#endif /* HAVE_EC_KEY_METHOD_NEW */
djm@openbsd.org93f02102019-01-20 22:51:37 +0000821
822static struct sshkey *
823pkcs11_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
903fail:
904 for (i = 0; i < 3; i++)
905 free(key_attr[i].pValue);
906 RSA_free(rsa);
907
908 return (key);
909}
910
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000911static int
djm@openbsd.org93f02102019-01-20 22:51:37 +0000912pkcs11_fetch_x509_pubkey(struct pkcs11_provider *p, CK_ULONG slotidx,
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000913 CK_OBJECT_HANDLE *obj, struct sshkey **keyp, char **labelp)
djm@openbsd.org93f02102019-01-20 22:51:37 +0000914{
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;
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000920 X509_NAME *x509_name = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000921 EVP_PKEY *evp;
922 RSA *rsa = NULL;
Darren Tucker97370f62019-05-17 10:54:51 +1000923#ifdef OPENSSL_HAS_ECC
djm@openbsd.org93f02102019-01-20 22:51:37 +0000924 EC_KEY *ec = NULL;
Darren Tucker97370f62019-05-17 10:54:51 +1000925#endif
djm@openbsd.org93f02102019-01-20 22:51:37 +0000926 struct sshkey *key = NULL;
927 int i;
Damien Millere2cb4452019-01-21 11:32:28 +1100928#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +0000929 int nid;
Damien Millere2cb4452019-01-21 11:32:28 +1100930#endif
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000931 const u_char *cp;
932 char *subject = NULL;
933
934 *keyp = NULL;
935 *labelp = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000936
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);
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000949 return -1;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000950 }
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");
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000960 return -1;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000961 }
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);
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000972 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000973 }
974
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000975 /* 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);
djm@openbsd.org93f02102019-01-20 22:51:37 +0000982
983 cp = cert_attr[2].pValue;
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000984 if ((x509 = d2i_X509(NULL, &cp, cert_attr[2].ulValueLen)) == NULL) {
djm@openbsd.org93f02102019-01-20 22:51:37 +0000985 error("d2i_x509 failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000986 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000987 }
988
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000989 if ((evp = X509_get_pubkey(x509)) == NULL) {
djm@openbsd.org93f02102019-01-20 22:51:37 +0000990 error("X509_get_pubkey failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000991 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000992 }
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");
djm@openbsd.org89a8d452020-01-25 00:03:36 +0000997 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +0000998 }
999 if ((rsa = RSAPublicKey_dup(EVP_PKEY_get0_RSA(evp))) == NULL) {
1000 error("RSAPublicKey_dup failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001001 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001002 }
1003
1004 if (pkcs11_rsa_wrap(p, slotidx, &cert_attr[0], rsa))
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001005 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001006
1007 key = sshkey_new(KEY_UNSPEC);
1008 if (key == NULL) {
1009 error("sshkey_new failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001010 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001011 }
1012
1013 key->rsa = rsa;
1014 key->type = KEY_RSA;
1015 key->flags |= SSHKEY_FLAG_EXT;
1016 rsa = NULL; /* now owned by key */
Damien Millere2cb4452019-01-21 11:32:28 +11001017#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +00001018 } else if (EVP_PKEY_base_id(evp) == EVP_PKEY_EC) {
djm@openbsd.org8a246752019-01-20 23:03:26 +00001019 if (EVP_PKEY_get0_EC_KEY(evp) == NULL) {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001020 error("invalid x509; no ec key");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001021 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001022 }
djm@openbsd.org8a246752019-01-20 23:03:26 +00001023 if ((ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(evp))) == NULL) {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001024 error("EC_KEY_dup failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001025 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001026 }
1027
1028 nid = sshkey_ecdsa_key_to_nid(ec);
1029 if (nid < 0) {
1030 error("couldn't get curve nid");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001031 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001032 }
1033
1034 if (pkcs11_ecdsa_wrap(p, slotidx, &cert_attr[0], ec))
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001035 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001036
1037 key = sshkey_new(KEY_UNSPEC);
1038 if (key == NULL) {
1039 error("sshkey_new failed");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001040 goto out;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001041 }
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 */
Damien Millere2cb4452019-01-21 11:32:28 +11001048#endif /* HAVE_EC_KEY_METHOD_NEW */
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001049 } else {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001050 error("unknown certificate key type");
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001051 goto out;
1052 }
1053 out:
djm@openbsd.org93f02102019-01-20 22:51:37 +00001054 for (i = 0; i < 3; i++)
1055 free(cert_attr[i].pValue);
1056 X509_free(x509);
1057 RSA_free(rsa);
Darren Tucker97370f62019-05-17 10:54:51 +10001058#ifdef OPENSSL_HAS_ECC
djm@openbsd.org93f02102019-01-20 22:51:37 +00001059 EC_KEY_free(ec);
Darren Tucker97370f62019-05-17 10:54:51 +10001060#endif
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001061 if (key == NULL) {
1062 free(subject);
1063 return -1;
1064 }
1065 /* success */
1066 *keyp = key;
1067 *labelp = subject;
1068 return 0;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001069}
1070
1071#if 0
Damien Millerd2252c72013-11-04 07:41:48 +11001072static int
djm@openbsd.org482d23b2018-09-13 02:08:33 +00001073have_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}
djm@openbsd.org93f02102019-01-20 22:51:37 +00001080#endif
djm@openbsd.org482d23b2018-09-13 02:08:33 +00001081
djm@openbsd.org93f02102019-01-20 22:51:37 +00001082/*
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 */
djm@openbsd.org482d23b2018-09-13 02:08:33 +00001087static int
djm@openbsd.org93f02102019-01-20 22:51:37 +00001088pkcs11_fetch_certs(struct pkcs11_provider *p, CK_ULONG slotidx,
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001089 struct sshkey ***keysp, char ***labelsp, int *nkeys)
Damien Miller7ea845e2010-02-12 09:21:02 +11001090{
djm@openbsd.org93f02102019-01-20 22:51:37 +00001091 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;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001100 char *label;
Tim Rice179eee02010-03-04 12:48:05 -08001101
djm@openbsd.org93f02102019-01-20 22:51:37 +00001102 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
Damien Miller7ea845e2010-02-12 09:21:02 +11001110 session = p->slotinfo[slotidx].session;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001111 f = p->function_list;
1112
1113 rv = f->C_FindObjectsInit(session, key_attr, 1);
1114 if (rv != CKR_OK) {
Damien Miller7ea845e2010-02-12 09:21:02 +11001115 error("C_FindObjectsInit failed: %lu", rv);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001116 goto fail;
Damien Miller7ea845e2010-02-12 09:21:02 +11001117 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001118
Damien Miller7ea845e2010-02-12 09:21:02 +11001119 while (1) {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001120 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;
Damien Miller7ea845e2010-02-12 09:21:02 +11001126 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001127 if (n == 0)
Damien Miller7ea845e2010-02-12 09:21:02 +11001128 break;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001129
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) {
Damien Miller7ea845e2010-02-12 09:21:02 +11001138 error("C_GetAttributeValue failed: %lu", rv);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001139 goto fail;
djm@openbsd.org63ebcd02015-07-18 08:02:17 +00001140 }
1141
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001142 key = NULL;
1143 label = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001144 switch (ck_cert_type) {
1145 case CKC_X_509:
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001146 if (pkcs11_fetch_x509_pubkey(p, slotidx, &obj,
1147 &key, &label) != 0) {
1148 error("failed to fetch key");
1149 continue;
1150 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001151 break;
1152 default:
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001153 error("skipping unsupported certificate type %lu",
1154 ck_cert_type);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001155 continue;
1156 }
1157
1158 if (pkcs11_key_included(keysp, nkeys, key)) {
1159 sshkey_free(key);
Damien Miller7ea845e2010-02-12 09:21:02 +11001160 } else {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001161 /* expand key array and add key */
1162 *keysp = xrecallocarray(*keysp, *nkeys,
1163 *nkeys + 1, sizeof(struct sshkey *));
1164 (*keysp)[*nkeys] = key;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001165 if (labelsp != NULL) {
1166 *labelsp = xrecallocarray(*labelsp, *nkeys,
1167 *nkeys + 1, sizeof(char *));
1168 (*labelsp)[*nkeys] = xstrdup((char *)label);
1169 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001170 *nkeys = *nkeys + 1;
1171 debug("have %d keys", *nkeys);
Damien Millerd2252c72013-11-04 07:41:48 +11001172 }
Damien Miller7ea845e2010-02-12 09:21:02 +11001173 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001174
1175 ret = 0;
1176fail:
1177 rv = f->C_FindObjectsFinal(session);
1178 if (rv != CKR_OK) {
Damien Miller7ea845e2010-02-12 09:21:02 +11001179 error("C_FindObjectsFinal failed: %lu", rv);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001180 ret = -1;
1181 }
1182
1183 return (ret);
Damien Miller7ea845e2010-02-12 09:21:02 +11001184}
1185
djm@openbsd.org93f02102019-01-20 22:51:37 +00001186/*
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 */
1191static int
1192pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001193 struct sshkey ***keysp, char ***labelsp, int *nkeys)
djm@openbsd.org93f02102019-01-20 22:51:37 +00001194{
1195 struct sshkey *key = NULL;
1196 CK_OBJECT_CLASS key_class;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001197 CK_ATTRIBUTE key_attr[2];
djm@openbsd.org93f02102019-01-20 22:51:37 +00001198 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;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001224 CK_UTF8CHAR label[256];
djm@openbsd.org93f02102019-01-20 22:51:37 +00001225
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);
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001239 key_attr[1].type = CKA_LABEL;
1240 key_attr[1].pValue = &label;
1241 key_attr[1].ulValueLen = sizeof(label) - 1;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001242
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001243 rv = f->C_GetAttributeValue(session, obj, key_attr, 2);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001244 if (rv != CKR_OK) {
1245 error("C_GetAttributeValue failed: %lu", rv);
1246 goto fail;
1247 }
1248
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001249 label[key_attr[1].ulValueLen] = '\0';
1250
djm@openbsd.org93f02102019-01-20 22:51:37 +00001251 switch (ck_key_type) {
1252 case CKK_RSA:
1253 key = pkcs11_fetch_rsa_pubkey(p, slotidx, &obj);
1254 break;
Damien Millere2cb4452019-01-21 11:32:28 +11001255#ifdef HAVE_EC_KEY_METHOD_NEW
djm@openbsd.org93f02102019-01-20 22:51:37 +00001256 case CKK_ECDSA:
1257 key = pkcs11_fetch_ecdsa_pubkey(p, slotidx, &obj);
1258 break;
Damien Millere2cb4452019-01-21 11:32:28 +11001259#endif /* HAVE_EC_KEY_METHOD_NEW */
djm@openbsd.org93f02102019-01-20 22:51:37 +00001260 default:
1261 /* XXX print key type? */
markus@openbsd.org2aee9a42019-03-08 17:24:43 +00001262 key = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001263 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;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001278 if (labelsp != NULL) {
1279 *labelsp = xrecallocarray(*labelsp, *nkeys,
1280 *nkeys + 1, sizeof(char *));
1281 (*labelsp)[*nkeys] = xstrdup((char *)label);
1282 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001283 *nkeys = *nkeys + 1;
1284 debug("have %d keys", *nkeys);
1285 }
1286 }
1287
1288 ret = 0;
1289fail:
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
1303static struct sshkey *
1304pkcs11_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
1366static int
1367pkcs11_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
1398static 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},
djm@openbsd.org65294092019-01-20 23:11:11 +00001407 {NULL, NULL, NULL, 0},
djm@openbsd.org93f02102019-01-20 22:51:37 +00001408};
1409
1410static struct sshkey *
1411pkcs11_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 */
1488static int
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001489pkcs11_register_provider(char *provider_id, char *pin,
1490 struct sshkey ***keyp, char ***labelsp,
djm@openbsd.org93f02102019-01-20 22:51:37 +00001491 struct pkcs11_provider **providerp, CK_ULONG user)
Damien Miller7ea845e2010-02-12 09:21:02 +11001492{
1493 int nkeys, need_finalize = 0;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001494 int ret = -1;
Damien Miller7ea845e2010-02-12 09:21:02 +11001495 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
djm@openbsd.org93f02102019-01-20 22:51:37 +00001503 if (providerp == NULL)
1504 goto fail;
1505 *providerp = NULL;
1506
1507 if (keyp != NULL)
1508 *keyp = NULL;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001509 if (labelsp != NULL)
1510 *labelsp = NULL;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001511
Damien Miller7ea845e2010-02-12 09:21:02 +11001512 if (pkcs11_provider_lookup(provider_id) != NULL) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001513 debug("%s: provider already registered: %s",
1514 __func__, provider_id);
Damien Miller7ea845e2010-02-12 09:21:02 +11001515 goto fail;
1516 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001517 /* open shared pkcs11-library */
Damien Miller7ea845e2010-02-12 09:21:02 +11001518 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) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001531 error("C_GetFunctionList for provider %s failed: %lu",
1532 provider_id, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001533 goto fail;
1534 }
1535 p->function_list = f;
1536 if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001537 error("C_Initialize for provider %s failed: %lu",
1538 provider_id, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001539 goto fail;
1540 }
1541 need_finalize = 1;
1542 if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001543 error("C_GetInfo for provider %s failed: %lu",
1544 provider_id, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001545 goto fail;
1546 }
1547 rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
1548 rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001549 debug("provider %s: manufacturerID <%s> cryptokiVersion %d.%d"
Damien Miller7ea845e2010-02-12 09:21:02 +11001550 " libraryDescription <%s> libraryVersion %d.%d",
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001551 provider_id,
Damien Miller7ea845e2010-02-12 09:21:02 +11001552 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) {
djm@openbsd.orgb52c0c22019-09-02 00:19:25 +00001563 debug("%s: provider %s returned no slots", __func__,
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001564 provider_id);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001565 ret = -SSH_PKCS11_ERR_NO_SLOTS;
Damien Miller7ea845e2010-02-12 09:21:02 +11001566 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) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001571 error("C_GetSlotList for provider %s failed: %lu",
1572 provider_id, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001573 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) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001582 error("C_GetTokenInfo for provider %s slot %lu "
1583 "failed: %lu", provider_id, (unsigned long)i, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001584 continue;
1585 }
djm@openbsd.orgb15fd982015-07-18 08:00:21 +00001586 if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001587 debug2("%s: ignoring uninitialised token in "
1588 "provider %s slot %lu", __func__,
1589 provider_id, (unsigned long)i);
djm@openbsd.orgb15fd982015-07-18 08:00:21 +00001590 continue;
1591 }
Damien Miller7ea845e2010-02-12 09:21:02 +11001592 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));
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001596 debug("provider %s slot %lu: label <%s> manufacturerID <%s> "
1597 "model <%s> serial <%s> flags 0x%lx",
1598 provider_id, (unsigned long)i,
Damien Miller7ea845e2010-02-12 09:21:02 +11001599 token->label, token->manufacturerID, token->model,
1600 token->serialNumber, token->flags);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001601 /*
1602 * open session, login with pin and retrieve public
1603 * keys (if keyp is provided)
1604 */
djm@openbsd.org7d6034b2019-09-05 10:05:51 +00001605 if ((ret = pkcs11_open_session(p, i, pin, user)) != 0 ||
1606 keyp == NULL)
1607 continue;
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001608 pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
1609 pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
djm@openbsd.org7d6034b2019-09-05 10:05:51 +00001610 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");
djm@openbsd.org93f02102019-01-20 22:51:37 +00001619 continue;
djm@openbsd.org7d6034b2019-09-05 10:05:51 +00001620 }
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001621 pkcs11_fetch_keys(p, i, keyp, labelsp, &nkeys);
1622 pkcs11_fetch_certs(p, i, keyp, labelsp, &nkeys);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001623 }
Damien Miller7ea845e2010-02-12 09:21:02 +11001624 }
djm@openbsd.org93f02102019-01-20 22:51:37 +00001625
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);
Damien Miller7ea845e2010-02-12 09:21:02 +11001633fail:
1634 if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
djm@openbsd.orgefb494e2016-10-28 03:33:52 +00001635 error("C_Finalize for provider %s failed: %lu",
1636 provider_id, rv);
Damien Miller7ea845e2010-02-12 09:21:02 +11001637 if (p) {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001638 free(p->name);
Darren Tuckera627d422013-06-02 07:31:17 +10001639 free(p->slotlist);
1640 free(p->slotinfo);
1641 free(p);
Damien Miller7ea845e2010-02-12 09:21:02 +11001642 }
1643 if (handle)
1644 dlclose(handle);
markus@openbsd.org31c860a2020-03-06 18:14:13 +00001645 if (ret > 0)
1646 ret = -1;
djm@openbsd.org93f02102019-01-20 22:51:37 +00001647 return (ret);
Damien Miller7ea845e2010-02-12 09:21:02 +11001648}
Damien Millerdfa41562010-02-12 10:06:28 +11001649
djm@openbsd.org93f02102019-01-20 22:51:37 +00001650/*
1651 * register a new provider and get number of keys hold by the token,
1652 * fails if provider already exists
1653 */
1654int
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001655pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp,
1656 char ***labelsp)
djm@openbsd.org93f02102019-01-20 22:51:37 +00001657{
1658 struct pkcs11_provider *p = NULL;
1659 int nkeys;
Darren Tucker0dd24e02011-09-04 19:59:26 +10001660
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001661 nkeys = pkcs11_register_provider(provider_id, pin, keyp, labelsp,
1662 &p, CKU_USER);
djm@openbsd.org93f02102019-01-20 22:51:37 +00001663
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
1678struct sshkey *
1679pkcs11_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);
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001694 else if ((ret = pkcs11_register_provider(provider_id, pin, NULL, NULL,
1695 &p, CKU_SO)) < 0) {
djm@openbsd.org93f02102019-01-20 22:51:37 +00001696 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
1734out:
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
1745struct sshkey *
1746pkcs11_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);
djm@openbsd.org89a8d452020-01-25 00:03:36 +00001766 } else if (pkcs11_register_provider(provider_id, pin, NULL, NULL, &p,
djm@openbsd.org93f02102019-01-20 22:51:37 +00001767 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
1834out:
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 */
Damien Miller5de6ac22019-01-21 11:44:19 +11001845#else /* ENABLE_PKCS11 */
Darren Tucker9634ffb2019-07-23 22:25:44 +10001846
1847#include <sys/types.h>
1848#include <stdarg.h>
1849#include <stdio.h>
1850
1851#include "log.h"
1852#include "sshkey.h"
1853
Darren Tucker0dd24e02011-09-04 19:59:26 +10001854int
1855pkcs11_init(int interactive)
1856{
djm@openbsd.org93f02102019-01-20 22:51:37 +00001857 error("%s: dlopen() not supported", __func__);
1858 return (-1);
1859}
1860
1861int
1862pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
1863{
1864 error("%s: dlopen() not supported", __func__);
1865 return (-1);
Darren Tucker0dd24e02011-09-04 19:59:26 +10001866}
1867
1868void
1869pkcs11_terminate(void)
1870{
djm@openbsd.org93f02102019-01-20 22:51:37 +00001871 error("%s: dlopen() not supported", __func__);
Darren Tucker0dd24e02011-09-04 19:59:26 +10001872}
Damien Miller5de6ac22019-01-21 11:44:19 +11001873#endif /* ENABLE_PKCS11 */