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