xref: /titanic_44/usr/src/lib/pkcs11/pkcs11_softtoken/common/softGeneral.c (revision 28167c24ba5be8b7c1d05e02d053f4a55cd21cc9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <strings.h>
30 #include <errno.h>
31 #include <cryptoutil.h>
32 #include <unistd.h> /* for pid_t */
33 #include <pthread.h>
34 #include <security/cryptoki.h>
35 #include "softGlobal.h"
36 #include "softSession.h"
37 #include "softObject.h"
38 #include "softKeystore.h"
39 #include "softKeystoreUtil.h"
40 
41 #pragma fini(softtoken_fini)
42 
43 static struct CK_FUNCTION_LIST functionList = {
44 	{ 2, 20 },	/* version */
45 	C_Initialize,
46 	C_Finalize,
47 	C_GetInfo,
48 	C_GetFunctionList,
49 	C_GetSlotList,
50 	C_GetSlotInfo,
51 	C_GetTokenInfo,
52 	C_GetMechanismList,
53 	C_GetMechanismInfo,
54 	C_InitToken,
55 	C_InitPIN,
56 	C_SetPIN,
57 	C_OpenSession,
58 	C_CloseSession,
59 	C_CloseAllSessions,
60 	C_GetSessionInfo,
61 	C_GetOperationState,
62 	C_SetOperationState,
63 	C_Login,
64 	C_Logout,
65 	C_CreateObject,
66 	C_CopyObject,
67 	C_DestroyObject,
68 	C_GetObjectSize,
69 	C_GetAttributeValue,
70 	C_SetAttributeValue,
71 	C_FindObjectsInit,
72 	C_FindObjects,
73 	C_FindObjectsFinal,
74 	C_EncryptInit,
75 	C_Encrypt,
76 	C_EncryptUpdate,
77 	C_EncryptFinal,
78 	C_DecryptInit,
79 	C_Decrypt,
80 	C_DecryptUpdate,
81 	C_DecryptFinal,
82 	C_DigestInit,
83 	C_Digest,
84 	C_DigestUpdate,
85 	C_DigestKey,
86 	C_DigestFinal,
87 	C_SignInit,
88 	C_Sign,
89 	C_SignUpdate,
90 	C_SignFinal,
91 	C_SignRecoverInit,
92 	C_SignRecover,
93 	C_VerifyInit,
94 	C_Verify,
95 	C_VerifyUpdate,
96 	C_VerifyFinal,
97 	C_VerifyRecoverInit,
98 	C_VerifyRecover,
99 	C_DigestEncryptUpdate,
100 	C_DecryptDigestUpdate,
101 	C_SignEncryptUpdate,
102 	C_DecryptVerifyUpdate,
103 	C_GenerateKey,
104 	C_GenerateKeyPair,
105 	C_WrapKey,
106 	C_UnwrapKey,
107 	C_DeriveKey,
108 	C_SeedRandom,
109 	C_GenerateRandom,
110 	C_GetFunctionStatus,
111 	C_CancelFunction,
112 	C_WaitForSlotEvent
113 };
114 
115 boolean_t softtoken_initialized = B_FALSE;
116 
117 static pid_t softtoken_pid = 0;
118 
119 /* This mutex protects soft_session_list, all_sessions_closing */
120 pthread_mutex_t soft_sessionlist_mutex;
121 soft_session_t *soft_session_list = NULL;
122 
123 int all_sessions_closing = 0;
124 
125 int soft_urandom_fd = -1;
126 int soft_random_fd = -1;
127 
128 slot_t soft_slot;
129 obj_to_be_freed_list_t obj_delay_freed;
130 ses_to_be_freed_list_t ses_delay_freed;
131 
132 /* protects softtoken_initialized and access to C_Initialize/C_Finalize */
133 pthread_mutex_t soft_giant_mutex = PTHREAD_MUTEX_INITIALIZER;
134 
135 static CK_RV finalize_common(boolean_t force, CK_VOID_PTR pReserved);
136 static void softtoken_fini();
137 
138 CK_RV
139 C_Initialize(CK_VOID_PTR pInitArgs)
140 {
141 
142 	int initialize_pid;
143 	boolean_t supplied_ok;
144 	CK_RV rv;
145 
146 	/*
147 	 * Get lock to insure only one thread enters this
148 	 * function at a time.
149 	 */
150 	(void) pthread_mutex_lock(&soft_giant_mutex);
151 
152 	initialize_pid = getpid();
153 
154 	if (softtoken_initialized) {
155 		if (initialize_pid == softtoken_pid) {
156 			/*
157 			 * This process has called C_Initialize already
158 			 */
159 			(void) pthread_mutex_unlock(&soft_giant_mutex);
160 			return (CKR_CRYPTOKI_ALREADY_INITIALIZED);
161 		} else {
162 			/*
163 			 * A fork has happened and the child is
164 			 * reinitializing.  Do a finalize_common to close
165 			 * out any state from the parent, and then
166 			 * continue on.
167 			 */
168 			(void) finalize_common(B_TRUE, NULL);
169 		}
170 	}
171 
172 	if (pInitArgs != NULL) {
173 		CK_C_INITIALIZE_ARGS *initargs1 =
174 		    (CK_C_INITIALIZE_ARGS *) pInitArgs;
175 
176 		/* pReserved must be NULL */
177 		if (initargs1->pReserved != NULL) {
178 			(void) pthread_mutex_unlock(&soft_giant_mutex);
179 			return (CKR_ARGUMENTS_BAD);
180 		}
181 
182 		/*
183 		 * ALL supplied function pointers need to have the value
184 		 * either NULL or non-NULL.
185 		 */
186 		supplied_ok = (initargs1->CreateMutex == NULL &&
187 		    initargs1->DestroyMutex == NULL &&
188 		    initargs1->LockMutex == NULL &&
189 		    initargs1->UnlockMutex == NULL) ||
190 		    (initargs1->CreateMutex != NULL &&
191 		    initargs1->DestroyMutex != NULL &&
192 		    initargs1->LockMutex != NULL &&
193 		    initargs1->UnlockMutex != NULL);
194 
195 		if (!supplied_ok) {
196 			(void) pthread_mutex_unlock(&soft_giant_mutex);
197 			return (CKR_ARGUMENTS_BAD);
198 		}
199 
200 		/*
201 		 * When the CKF_OS_LOCKING_OK flag isn't set and mutex
202 		 * function pointers are supplied by an application,
203 		 * return an error.  We must be able to use our own primitives.
204 		 */
205 		if (!(initargs1->flags & CKF_OS_LOCKING_OK) &&
206 		    (initargs1->CreateMutex != NULL)) {
207 			(void) pthread_mutex_unlock(&soft_giant_mutex);
208 			return (CKR_CANT_LOCK);
209 		}
210 	}
211 
212 	/* Initialize the session list lock */
213 	if (pthread_mutex_init(&soft_sessionlist_mutex, NULL) != 0) {
214 		(void) pthread_mutex_unlock(&soft_giant_mutex);
215 		return (CKR_CANT_LOCK);
216 	}
217 
218 	softtoken_initialized = B_TRUE;
219 	softtoken_pid = initialize_pid;
220 
221 	/*
222 	 * token object related initialization
223 	 */
224 	soft_slot.authenticated = 0;
225 	soft_slot.userpin_change_needed = 0;
226 	soft_slot.token_object_list = NULL;
227 
228 	if ((rv = soft_init_token_session()) != CKR_OK) {
229 		(void) pthread_mutex_unlock(&soft_giant_mutex);
230 		return (rv);
231 	}
232 
233 	/* Initialize the slot lock */
234 	if (pthread_mutex_init(&soft_slot.slot_mutex, NULL) != 0) {
235 		(void) soft_destroy_token_session();
236 		(void) pthread_mutex_unlock(&soft_giant_mutex);
237 		return (CKR_CANT_LOCK);
238 	}
239 
240 	/* Get keystore version because it might not be 1 at this time */
241 	if (soft_keystore_get_version(&soft_slot.ks_version, B_FALSE) !=
242 	    0) {
243 		soft_token_present = B_FALSE;
244 	}
245 
246 	if (soft_token_present) {
247 		/* Load all the public token objects from keystore */
248 		if ((rv = soft_get_token_objects_from_keystore(
249 		    PUB_TOKENOBJS)) != CKR_OK) {
250 			(void) pthread_mutex_destroy(&soft_slot.slot_mutex);
251 			(void) soft_destroy_token_session();
252 			(void) pthread_mutex_unlock(&soft_giant_mutex);
253 			return (rv);
254 		} else {
255 			/*
256 			 * Invalidate public token objects until the
257 			 * C_OpenSession is called.
258 			 */
259 			soft_validate_token_objects(B_FALSE);
260 		}
261 	}
262 
263 	(void) pthread_mutex_unlock(&soft_giant_mutex);
264 
265 	/* Initialize the object_to_be_freed list */
266 	(void) pthread_mutex_init(&obj_delay_freed.obj_to_be_free_mutex, NULL);
267 	obj_delay_freed.count = 0;
268 	obj_delay_freed.first = NULL;
269 	obj_delay_freed.last = NULL;
270 
271 	(void) pthread_mutex_init(&ses_delay_freed.ses_to_be_free_mutex, NULL);
272 	ses_delay_freed.count = 0;
273 	ses_delay_freed.first = NULL;
274 	ses_delay_freed.last = NULL;
275 	return (CKR_OK);
276 
277 }
278 
279 /*
280  * C_Finalize is a wrapper around finalize_common. The
281  * soft_giant_mutex should be locked by C_Finalize().
282  */
283 CK_RV
284 C_Finalize(CK_VOID_PTR pReserved)
285 {
286 
287 	CK_RV rv;
288 
289 	(void) pthread_mutex_lock(&soft_giant_mutex);
290 
291 	rv = finalize_common(B_FALSE, pReserved);
292 
293 	(void) pthread_mutex_unlock(&soft_giant_mutex);
294 
295 	return (rv);
296 
297 }
298 
299 /*
300  * finalize_common() does the work for C_Finalize.  soft_giant_mutex
301  * must be held before calling this function.
302  */
303 static CK_RV
304 finalize_common(boolean_t force, CK_VOID_PTR pReserved) {
305 
306 	CK_RV rv = CKR_OK;
307 	struct object *delay_free_obj, *tmpo;
308 	struct session *delay_free_ses, *tmps;
309 
310 	if (!softtoken_initialized) {
311 		return (CKR_CRYPTOKI_NOT_INITIALIZED);
312 	}
313 
314 	/* Check to see if pReseved is NULL */
315 	if (pReserved != NULL) {
316 		return (CKR_ARGUMENTS_BAD);
317 	}
318 
319 	(void) pthread_mutex_lock(&soft_sessionlist_mutex);
320 	/*
321 	 * Set all_sessions_closing flag so any access to any
322 	 * existing sessions will be rejected.
323 	 */
324 	all_sessions_closing = 1;
325 	(void) pthread_mutex_unlock(&soft_sessionlist_mutex);
326 
327 	/* Delete all the sessions and release the allocated resources */
328 	rv = soft_delete_all_sessions(force);
329 
330 	(void) pthread_mutex_lock(&soft_sessionlist_mutex);
331 	/* Reset all_sessions_closing flag. */
332 	all_sessions_closing = 0;
333 	(void) pthread_mutex_unlock(&soft_sessionlist_mutex);
334 
335 	softtoken_initialized = B_FALSE;
336 	softtoken_pid = 0;
337 
338 	if (soft_urandom_fd > 0) {
339 		(void) close(soft_urandom_fd);
340 		soft_urandom_fd = -1;
341 	}
342 
343 	if (soft_random_fd > 0) {
344 		(void) close(soft_random_fd);
345 		soft_random_fd = -1;
346 	}
347 
348 	/* Destroy the session list lock here */
349 	(void) pthread_mutex_destroy(&soft_sessionlist_mutex);
350 
351 	/*
352 	 * Destroy token object related stuffs
353 	 * 1. Clean up the token object list
354 	 * 2. Destroy slot mutex
355 	 * 3. Destroy mutex in token_session
356 	 */
357 	soft_delete_all_in_core_token_objects(ALL_TOKEN);
358 	(void) pthread_mutex_destroy(&soft_slot.slot_mutex);
359 	(void) soft_destroy_token_session();
360 
361 	/*
362 	 * free all entries in the delay_freed list
363 	 */
364 	delay_free_obj = obj_delay_freed.first;
365 	while (delay_free_obj != NULL) {
366 		tmpo = delay_free_obj->next;
367 		free(delay_free_obj);
368 		delay_free_obj = tmpo;
369 	}
370 	(void) pthread_mutex_destroy(&obj_delay_freed.obj_to_be_free_mutex);
371 
372 	delay_free_ses = ses_delay_freed.first;
373 	while (delay_free_ses != NULL) {
374 		tmps = delay_free_ses->next;
375 		free(delay_free_ses);
376 		delay_free_ses = tmps;
377 	}
378 	(void) pthread_mutex_destroy(&ses_delay_freed.ses_to_be_free_mutex);
379 
380 	return (rv);
381 }
382 
383 /*
384  * softtoken_fini() function required to make sure complete cleanup
385  * is done if softtoken is ever unloaded without a C_Finalize() call.
386  */
387 static void
388 softtoken_fini()
389 {
390 	(void) pthread_mutex_lock(&soft_giant_mutex);
391 
392 	/* if we're not initilized, do not attempt to finalize */
393 	if (!softtoken_initialized) {
394 		(void) pthread_mutex_unlock(&soft_giant_mutex);
395 		return;
396 	}
397 
398 	(void) finalize_common(B_TRUE, NULL_PTR);
399 
400 	(void) pthread_mutex_unlock(&soft_giant_mutex);
401 }
402 
403 CK_RV
404 C_GetInfo(CK_INFO_PTR pInfo)
405 {
406 	if (!softtoken_initialized)
407 		return (CKR_CRYPTOKI_NOT_INITIALIZED);
408 
409 	if (pInfo == NULL) {
410 		return (CKR_ARGUMENTS_BAD);
411 	}
412 
413 	/* Provide general information in the provided buffer */
414 	pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
415 	pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
416 	(void) strncpy((char *)pInfo->manufacturerID,
417 	    SOFT_MANUFACTURER_ID, 32);
418 	pInfo->flags = 0;
419 	(void) strncpy((char *)pInfo->libraryDescription,
420 	    LIBRARY_DESCRIPTION, 32);
421 	pInfo->libraryVersion.major = LIBRARY_VERSION_MAJOR;
422 	pInfo->libraryVersion.major = LIBRARY_VERSION_MINOR;
423 
424 	return (CKR_OK);
425 }
426 
427 CK_RV
428 C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
429 {
430 	if (ppFunctionList == NULL) {
431 		return (CKR_ARGUMENTS_BAD);
432 	}
433 
434 	*ppFunctionList = &functionList;
435 
436 	return (CKR_OK);
437 }
438 
439 /*
440  * PKCS#11 states that C_GetFunctionStatus should always return
441  * CKR_FUNCTION_NOT_PARALLEL
442  */
443 /*ARGSUSED*/
444 CK_RV
445 C_GetFunctionStatus(CK_SESSION_HANDLE hSession)
446 {
447 	return (CKR_FUNCTION_NOT_PARALLEL);
448 }
449 
450 /*
451  * PKCS#11 states that C_CancelFunction should always return
452  * CKR_FUNCTION_NOT_PARALLEL
453  */
454 /*ARGSUSED*/
455 CK_RV
456 C_CancelFunction(CK_SESSION_HANDLE hSession)
457 {
458 	return (CKR_FUNCTION_NOT_PARALLEL);
459 }
460 
461 /*
462  * Perform a write that can handle EINTR.
463  */
464 int
465 looping_write(int fd, void *buf, int len)
466 {
467 	char *p = buf;
468 	int cc, len2 = 0;
469 
470 	if (len == 0)
471 		return (0);
472 
473 	do {
474 		cc = write(fd, p, len);
475 		if (cc < 0) {
476 			if (errno == EINTR)
477 				continue;
478 			return (cc);
479 		} else if (cc == 0) {
480 			return (len2);
481 		} else {
482 			p += cc;
483 			len2 += cc;
484 			len -= cc;
485 		}
486 	} while (len > 0);
487 	return (len2);
488 }
489 
490 /*
491  * Perform a read that can handle EINTR.
492  */
493 int
494 looping_read(int fd, void *buf, int len)
495 {
496 	char *p = buf;
497 	int cc, len2 = 0;
498 
499 	do {
500 		cc = read(fd, p, len);
501 		if (cc < 0) {
502 			if (errno == EINTR)
503 				continue;
504 			return (cc);	/* errno is already set */
505 		} else if (cc == 0) {
506 			return (len2);
507 		} else {
508 			p += cc;
509 			len2 += cc;
510 			len -= cc;
511 		}
512 	} while (len > 0);
513 	return (len2);
514 }
515