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