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
557
558
559
560
561
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <unistd.h>
#include <string.h>
#include <cryptoutil.h>
#include <pthread.h>
#include <security/cryptoki.h>
#include "pkcs11Global.h"
#include "pkcs11Slot.h"
#include "pkcs11Conf.h"
#include "pkcs11Session.h"
#include "metaGlobal.h"
#pragma init(pkcs11_init)
#pragma fini(pkcs11_fini)
static struct CK_FUNCTION_LIST functionList = {
{ 2, 20 }, /* version */
C_Initialize,
C_Finalize,
C_GetInfo,
C_GetFunctionList,
C_GetSlotList,
C_GetSlotInfo,
C_GetTokenInfo,
C_GetMechanismList,
C_GetMechanismInfo,
C_InitToken,
C_InitPIN,
C_SetPIN,
C_OpenSession,
C_CloseSession,
C_CloseAllSessions,
C_GetSessionInfo,
C_GetOperationState,
C_SetOperationState,
C_Login,
C_Logout,
C_CreateObject,
C_CopyObject,
C_DestroyObject,
C_GetObjectSize,
C_GetAttributeValue,
C_SetAttributeValue,
C_FindObjectsInit,
C_FindObjects,
C_FindObjectsFinal,
C_EncryptInit,
C_Encrypt,
C_EncryptUpdate,
C_EncryptFinal,
C_DecryptInit,
C_Decrypt,
C_DecryptUpdate,
C_DecryptFinal,
C_DigestInit,
C_Digest,
C_DigestUpdate,
C_DigestKey,
C_DigestFinal,
C_SignInit,
C_Sign,
C_SignUpdate,
C_SignFinal,
C_SignRecoverInit,
C_SignRecover,
C_VerifyInit,
C_Verify,
C_VerifyUpdate,
C_VerifyFinal,
C_VerifyRecoverInit,
C_VerifyRecover,
C_DigestEncryptUpdate,
C_DecryptDigestUpdate,
C_SignEncryptUpdate,
C_DecryptVerifyUpdate,
C_GenerateKey,
C_GenerateKeyPair,
C_WrapKey,
C_UnwrapKey,
C_DeriveKey,
C_SeedRandom,
C_GenerateRandom,
C_GetFunctionStatus,
C_CancelFunction,
C_WaitForSlotEvent
};
boolean_t pkcs11_initialized = B_FALSE;
boolean_t pkcs11_cant_create_threads = B_FALSE;
boolean_t fini_called = B_FALSE;
static boolean_t pkcs11_atfork_initialized = B_FALSE;
static pid_t pkcs11_pid = 0;
/* protects pkcs11_[initialized|pid], and fastpath */
static pthread_mutex_t globalmutex = PTHREAD_MUTEX_INITIALIZER;
static CK_RV finalize_common(CK_VOID_PTR pReserved);
static void pkcs11_init();
static void pkcs11_fini();
/*
* Ensure that before a fork, all mutexes are taken.
* We cannot acquire globalmutex, because it can cause deadlock when
* atfork() and fork() are called in parallel. It can happen when
* C_Ininitialize() tries to dlopen() a provider. The dlopen() operation
* is protected by globalmutex and when another thread calls fork()
* pkcs11_fork_prepare cannot acquire the mutex again and thus it must wait.
* When a provider tries to register its atfork handler, atfork() must
* wait on fork(). See the comment in fork() libc function for more details.
*
* Order:
* 1. slottable->st_mutex
* 2. all slottable->st_slots' mutexes
*/
static void
pkcs11_fork_prepare(void)
{
int i;
if (pkcs11_initialized) {
if (slottable != NULL) {
(void) pthread_mutex_lock(&slottable->st_mutex);
/* Take the sl_mutex of all slots */
for (i = slottable->st_first;
i <= slottable->st_last; i++) {
if (slottable->st_slots[i] != NULL) {
(void) pthread_mutex_lock(
&slottable->st_slots[i]->sl_mutex);
}
}
}
}
}
/*
* Ensure that after a fork, in the parent, all mutexes are released in opposite
* order to pkcs11_fork_prepare().
*/
static void
pkcs11_fork_parent(void)
{
int i;
if (pkcs11_initialized) {
if (slottable != NULL) {
/* Release the sl_mutex of all slots */
for (i = slottable->st_first;
i <= slottable->st_last; i++) {
if (slottable->st_slots[i] != NULL) {
(void) pthread_mutex_unlock(
&slottable->st_slots[i]->sl_mutex);
}
}
}
(void) pthread_mutex_unlock(&slottable->st_mutex);
}
}
/*
* Ensure that after a fork, in the child, all mutexes are released in opposite
* order to pkcs11_fork_prepare() and cleanup is done.
* Because we need to handle fork correctly before library is initialized two
* handlers are necessary.
*
* 1) pkcs11_fork_child() - unlock mutexes
* 2) pkcs11_fork_child_fini() - cleanup library after fork, it is registered in
* C_Initialize() after providers initialization.
*/
static void
pkcs11_fork_child(void)
{
int i;
if (pkcs11_initialized) {
if (slottable != NULL) {
/* Release the sl_mutex of all slots */
for (i = slottable->st_first;
i <= slottable->st_last; i++) {
if (slottable->st_slots[i] != NULL) {
(void) pthread_mutex_unlock(
&slottable->st_slots[i]->sl_mutex);
}
}
}
(void) pthread_mutex_unlock(&slottable->st_mutex);
}
(void) pthread_mutex_destroy(&globalmutex);
(void) pthread_mutex_init(&globalmutex, NULL);
}
/* Library cleanup have to be last afterfork child handler. */
static void
pkcs11_fork_child_fini(void)
{
pkcs11_fini();
}
CK_RV
C_Initialize(CK_VOID_PTR pInitArgs)
{
CK_RV rv;
uentrylist_t *pliblist = NULL;
int initialize_pid;
/*
* Grab lock to insure only one thread enters
* this function at a time.
*/
(void) pthread_mutex_lock(&globalmutex);
initialize_pid = getpid();
/* Make sure function hasn't been called twice */
if (pkcs11_initialized) {
if (initialize_pid == pkcs11_pid) {
(void) pthread_mutex_unlock(&globalmutex);
return (CKR_CRYPTOKI_ALREADY_INITIALIZED);
} else {
/*
* A fork has happened and the child is
* reinitializing. Do a finalize_common() to close
* out any state from the parent, and then
* continue on.
*/
(void) finalize_common(NULL);
}
}
/* Check if application has provided mutex-handling functions */
if (pInitArgs != NULL) {
CK_C_INITIALIZE_ARGS_PTR initargs =
(CK_C_INITIALIZE_ARGS_PTR) pInitArgs;
/* pReserved should not be set */
if (initargs->pReserved != NULL) {
rv = CKR_ARGUMENTS_BAD;
goto errorexit;
}
/*
* Make sure function pointers are either all NULL or
* all set.
*/
if (!(((initargs->CreateMutex != NULL) &&
(initargs->LockMutex != NULL) &&
(initargs->UnlockMutex != NULL) &&
(initargs->DestroyMutex != NULL)) ||
((initargs->CreateMutex == NULL) &&
(initargs->LockMutex == NULL) &&
(initargs->UnlockMutex == NULL) &&
(initargs->DestroyMutex == NULL)))) {
rv = CKR_ARGUMENTS_BAD;
goto errorexit;
}
if (!(initargs->flags & CKF_OS_LOCKING_OK)) {
if (initargs->CreateMutex != NULL) {
/*
* Do not accept application supplied
* locking primitives.
*/
rv = CKR_CANT_LOCK;
goto errorexit;
}
}
if (initargs->flags & CKF_LIBRARY_CANT_CREATE_OS_THREADS) {
/*
* Calling application does not want the library
* to create threads. This will effect
* C_WaitForSlotEvent().
*/
pkcs11_cant_create_threads = B_TRUE;
}
}
/* Initialize slot table */
rv = pkcs11_slottable_initialize();
if (rv != CKR_OK)
goto errorexit;
/* Get the list of providers */
if (get_pkcs11conf_info(&pliblist) != SUCCESS) {
rv = CKR_FUNCTION_FAILED;
goto errorexit;
}
/*
* Load each provider, check for accessible slots,
* and populate slottable. If metaslot is enabled,
* it will be initialized as well.
*/
rv = pkcs11_slot_mapping(pliblist, pInitArgs);
if (rv != CKR_OK)
goto errorexit;
pkcs11_initialized = B_TRUE;
pkcs11_pid = initialize_pid;
/* Children inherit parent's atfork handlers */
if (!pkcs11_atfork_initialized) {
(void) pthread_atfork(NULL, NULL, pkcs11_fork_child_fini);
pkcs11_atfork_initialized = B_TRUE;
}
(void) pthread_mutex_unlock(&globalmutex);
/* Cleanup data structures no longer needed */
free_uentrylist(pliblist);
return (CKR_OK);
errorexit:
/* Cleanup any data structures that have already been allocated */
if (slottable)
(void) pkcs11_slottable_delete();
if (pliblist)
(void) free_uentrylist(pliblist);
(void) pthread_mutex_unlock(&globalmutex);
return (rv);
}
/*
* C_Finalize is a wrapper around finalize_common. The
* globalmutex should be locked by C_Finalize().
*
* When an explicit C_Finalize() call is received, all
* plugins currently in the slottable will also be
* finalized. This must occur, even if libpkcs11(3lib)
* was not the first one to initialize the plugins, since it
* is the only way in PKCS#11 to force a refresh of the
* slot listings (ie to get new hardware devices).
*/
CK_RV
C_Finalize(CK_VOID_PTR pReserved)
{
CK_RV rv;
(void) pthread_mutex_lock(&globalmutex);
rv = finalize_common(pReserved);
(void) pthread_mutex_unlock(&globalmutex);
return (rv);
}
/*
* finalize_common() does the work for C_Finalize. globalmutex
* must be held before calling this function.
*/
static CK_RV
finalize_common(CK_VOID_PTR pReserved)
{
CK_RV rv;
if (!pkcs11_initialized) {
return (CKR_CRYPTOKI_NOT_INITIALIZED);
}
if (pReserved != NULL) {
return (CKR_ARGUMENTS_BAD);
}
purefastpath = B_FALSE;
policyfastpath = B_FALSE;
fast_funcs = NULL;
fast_slot = 0;
pkcs11_initialized = B_FALSE;
pkcs11_cant_create_threads = B_FALSE;
pkcs11_pid = 0;
/* Check if C_WaitForSlotEvent() is currently active */
(void) pthread_mutex_lock(&slottable->st_mutex);
if (slottable->st_wfse_active) {
/*
* Wait for this thread to proceed far enough to block or
* end on its own. Otherwise, teardown of slottable may
* occurr before this active function completes.
*/
while (slottable->st_wfse_active) {
/*
* If C_WaitForSlotEvent is blocking, wake it up and
* return error to calling application.
*/
if (slottable->st_blocking) {
slottable->st_list_signaled = B_TRUE;
(void) pthread_cond_signal(
&slottable->st_wait_cond);
(void) pthread_mutex_unlock(
&slottable->st_mutex);
(void) pthread_join(slottable->st_tid, NULL);
}
}
} else {
(void) pthread_mutex_unlock(&slottable->st_mutex);
}
rv = pkcs11_slottable_delete();
return (rv);
}
static void
pkcs11_init()
{
(void) pthread_atfork(pkcs11_fork_prepare,
pkcs11_fork_parent, pkcs11_fork_child);
}
/*
* pkcs11_fini() function required to make sure complete cleanup
* is done of plugins if the framework is ever unloaded without
* a C_Finalize() call. This would be common when applications
* load and unload other libraries that use libpkcs11(3lib), since
* shared libraries should not call C_Finalize().
*
* If pkcs11_fini() is used, we set fini_called to B_TRUE so that
* pkcs11_slottable_delete() will not call C_Finalize() on the plugins.
*
* This is to protect in cases where the application has dlopened
* an object (for example, dlobj) that links to libpkcs11(3lib), but
* the application is unaware that the object is doing PKCS#11 calls
* underneath. This application may later directly dlopen one of the
* plugins (like pkcs11_softtoken.so, or any other 3rd party provided
* plugin) in order to directly perform PKCS#11 operations.
*
* While it is still actively using the PKCS#11 plugin directly,
* the application may finish with dlobj and dlclose it. As the
* reference count for libpkcs11(3lib) has become 0, pkcs11_fini()
* will be run by the linker. Even though libpkcs11(3lib) was the
* first to initialize the plugin in this case, it is not safe for
* libpkcs11(3lib) to finalize the plugin, as the application would
* lose state.
*/
static void
pkcs11_fini()
{
(void) pthread_mutex_lock(&globalmutex);
/* if we're not initilized, do not attempt to finalize */
if (!pkcs11_initialized) {
(void) pthread_mutex_unlock(&globalmutex);
return;
}
fini_called = B_TRUE;
(void) finalize_common(NULL_PTR);
(void) pthread_mutex_unlock(&globalmutex);
}
CK_RV
C_GetInfo(CK_INFO_PTR pInfo)
{
/* Check for a fastpath */
if (purefastpath || policyfastpath) {
return (fast_funcs->C_GetInfo(pInfo));
}
if (!pkcs11_initialized)
return (CKR_CRYPTOKI_NOT_INITIALIZED);
if (pInfo == NULL) {
return (CKR_ARGUMENTS_BAD);
}
/*
* Copy data into the provided buffer, use strncpy() instead
* of strlcpy() so that the strings are NOT NULL terminated,
* as required by the PKCS#11 standard
*/
(void) strncpy((char *)pInfo->manufacturerID, MANUFACTURER_ID,
PKCS11_STRING_LENGTH);
(void) strncpy((char *)pInfo->libraryDescription,
LIBRARY_DESCRIPTION, PKCS11_STRING_LENGTH);
pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
pInfo->flags = 0;
pInfo->libraryVersion.major = LIBRARY_VERSION_MAJOR;
pInfo->libraryVersion.minor = LIBRARY_VERSION_MINOR;
return (CKR_OK);
}
/*
* This function is unaffected by the fast-path, since it is likely
* called before C_Initialize is, so we will not yet know the status
* of the fast-path. Additionally, policy will still need to be
* enforced if applicable.
*/
CK_RV
C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
{
if (ppFunctionList == NULL) {
return (CKR_ARGUMENTS_BAD);
}
*ppFunctionList = &functionList;
return (CKR_OK);
}
/*
* This function is no longer supported in this revision of the PKCS#11
* standard. It is maintained for backwards compatibility only.
*/
/*ARGSUSED*/
CK_RV
C_GetFunctionStatus(CK_SESSION_HANDLE hSession)
{
return (CKR_FUNCTION_NOT_PARALLEL);
}
/*
* This function is no longer supported in this revision of the PKCS#11
* standard. It is maintained for backwards compatibility only.
*/
/*ARGSUSED*/
CK_RV
C_CancelFunction(CK_SESSION_HANDLE hSession)
{
return (CKR_FUNCTION_NOT_PARALLEL);
}
|