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 2006 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 
116 static pid_t softtoken_pid = 0;
117 
118 /* This mutex protects soft_session_list, all_sessions_closing */
119 pthread_mutex_t soft_sessionlist_mutex;
120 soft_session_t *soft_session_list = NULL;
121 
122 int all_sessions_closing = 0;
123 
124 int soft_urandom_fd = -1;
125 int soft_urandom_seed_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 	soft_slot.keystore_load_status = KEYSTORE_UNINITIALIZED;
228 
229 	if ((rv = soft_init_token_session()) != CKR_OK) {
230 		(void) pthread_mutex_unlock(&soft_giant_mutex);
231 		return (rv);
232 	}
233 
234 	/* Initialize the slot lock */
235 	if (pthread_mutex_init(&soft_slot.slot_mutex, NULL) != 0) {
236 		(void) soft_destroy_token_session();
237 		(void) pthread_mutex_unlock(&soft_giant_mutex);
238 		return (CKR_CANT_LOCK);
239 	}
240 
241 	/* Initialize the keystore lock */
242 	if (pthread_mutex_init(&soft_slot.keystore_mutex, NULL) != 0) {
243 		(void) pthread_mutex_unlock(&soft_giant_mutex);
244 		return (CKR_CANT_LOCK);
245 	}
246 
247 	(void) pthread_mutex_unlock(&soft_giant_mutex);
248 
249 	/* Initialize the object_to_be_freed list */
250 	(void) pthread_mutex_init(&obj_delay_freed.obj_to_be_free_mutex, NULL);
251 	obj_delay_freed.count = 0;
252 	obj_delay_freed.first = NULL;
253 	obj_delay_freed.last = NULL;
254 
255 	(void) pthread_mutex_init(&ses_delay_freed.ses_to_be_free_mutex, NULL);
256 	ses_delay_freed.count = 0;
257 	ses_delay_freed.first = NULL;
258 	ses_delay_freed.last = NULL;
259 	return (CKR_OK);
260 
261 }
262 
263 /*
264  * C_Finalize is a wrapper around finalize_common. The
265  * soft_giant_mutex should be locked by C_Finalize().
266  */
267 CK_RV
268 C_Finalize(CK_VOID_PTR pReserved)
269 {
270 
271 	CK_RV rv;
272 
273 	(void) pthread_mutex_lock(&soft_giant_mutex);
274 
275 	rv = finalize_common(B_FALSE, pReserved);
276 
277 	(void) pthread_mutex_unlock(&soft_giant_mutex);
278 
279 	return (rv);
280 
281 }
282 
283 /*
284  * finalize_common() does the work for C_Finalize.  soft_giant_mutex
285  * must be held before calling this function.
286  */
287 static CK_RV
288 finalize_common(boolean_t force, CK_VOID_PTR pReserved) {
289 
290 	CK_RV rv = CKR_OK;
291 	struct object *delay_free_obj, *tmpo;
292 	struct session *delay_free_ses, *tmps;
293 
294 	if (!softtoken_initialized) {
295 		return (CKR_CRYPTOKI_NOT_INITIALIZED);
296 	}
297 
298 	/* Check to see if pReseved is NULL */
299 	if (pReserved != NULL) {
300 		return (CKR_ARGUMENTS_BAD);
301 	}
302 
303 	(void) pthread_mutex_lock(&soft_sessionlist_mutex);
304 	/*
305 	 * Set all_sessions_closing flag so any access to any
306 	 * existing sessions will be rejected.
307 	 */
308 	all_sessions_closing = 1;
309 	(void) pthread_mutex_unlock(&soft_sessionlist_mutex);
310 
311 	/* Delete all the sessions and release the allocated resources */
312 	rv = soft_delete_all_sessions(force);
313 
314 	(void) pthread_mutex_lock(&soft_sessionlist_mutex);
315 	/* Reset all_sessions_closing flag. */
316 	all_sessions_closing = 0;
317 	(void) pthread_mutex_unlock(&soft_sessionlist_mutex);
318 
319 	softtoken_initialized = B_FALSE;
320 	softtoken_pid = 0;
321 
322 	if (soft_urandom_fd > 0) {
323 		(void) close(soft_urandom_fd);
324 		soft_urandom_fd = -1;
325 	}
326 
327 	if (soft_urandom_seed_fd > 0) {
328 		(void) close(soft_urandom_seed_fd);
329 		soft_urandom_seed_fd = -1;
330 	}
331 
332 	if (soft_random_fd > 0) {
333 		(void) close(soft_random_fd);
334 		soft_random_fd = -1;
335 	}
336 
337 	/* Destroy the session list lock here */
338 	(void) pthread_mutex_destroy(&soft_sessionlist_mutex);
339 
340 	/*
341 	 * Destroy token object related stuffs
342 	 * 1. Clean up the token object list
343 	 * 2. Destroy slot mutex
344 	 * 3. Destroy mutex in token_session
345 	 */
346 	soft_delete_all_in_core_token_objects(ALL_TOKEN);
347 	(void) pthread_mutex_destroy(&soft_slot.slot_mutex);
348 	(void) pthread_mutex_destroy(&soft_slot.keystore_mutex);
349 	(void) soft_destroy_token_session();
350 
351 	/*
352 	 * free all entries in the delay_freed list
353 	 */
354 	delay_free_obj = obj_delay_freed.first;
355 	while (delay_free_obj != NULL) {
356 		tmpo = delay_free_obj->next;
357 		free(delay_free_obj);
358 		delay_free_obj = tmpo;
359 	}
360 
361 	soft_slot.keystore_load_status = KEYSTORE_UNINITIALIZED;
362 	(void) pthread_mutex_destroy(&obj_delay_freed.obj_to_be_free_mutex);
363 
364 	delay_free_ses = ses_delay_freed.first;
365 	while (delay_free_ses != NULL) {
366 		tmps = delay_free_ses->next;
367 		free(delay_free_ses);
368 		delay_free_ses = tmps;
369 	}
370 	(void) pthread_mutex_destroy(&ses_delay_freed.ses_to_be_free_mutex);
371 
372 	return (rv);
373 }
374 
375 /*
376  * softtoken_fini() function required to make sure complete cleanup
377  * is done if softtoken is ever unloaded without a C_Finalize() call.
378  */
379 static void
380 softtoken_fini()
381 {
382 	(void) pthread_mutex_lock(&soft_giant_mutex);
383 
384 	/* if we're not initilized, do not attempt to finalize */
385 	if (!softtoken_initialized) {
386 		(void) pthread_mutex_unlock(&soft_giant_mutex);
387 		return;
388 	}
389 
390 	(void) finalize_common(B_TRUE, NULL_PTR);
391 
392 	(void) pthread_mutex_unlock(&soft_giant_mutex);
393 }
394 
395 CK_RV
396 C_GetInfo(CK_INFO_PTR pInfo)
397 {
398 	if (!softtoken_initialized)
399 		return (CKR_CRYPTOKI_NOT_INITIALIZED);
400 
401 	if (pInfo == NULL) {
402 		return (CKR_ARGUMENTS_BAD);
403 	}
404 
405 	/* Provide general information in the provided buffer */
406 	pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
407 	pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
408 	(void) strncpy((char *)pInfo->manufacturerID,
409 	    SOFT_MANUFACTURER_ID, 32);
410 	pInfo->flags = 0;
411 	(void) strncpy((char *)pInfo->libraryDescription,
412 	    LIBRARY_DESCRIPTION, 32);
413 	pInfo->libraryVersion.major = LIBRARY_VERSION_MAJOR;
414 	pInfo->libraryVersion.major = LIBRARY_VERSION_MINOR;
415 
416 	return (CKR_OK);
417 }
418 
419 CK_RV
420 C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList)
421 {
422 	if (ppFunctionList == NULL) {
423 		return (CKR_ARGUMENTS_BAD);
424 	}
425 
426 	*ppFunctionList = &functionList;
427 
428 	return (CKR_OK);
429 }
430 
431 /*
432  * PKCS#11 states that C_GetFunctionStatus should always return
433  * CKR_FUNCTION_NOT_PARALLEL
434  */
435 /*ARGSUSED*/
436 CK_RV
437 C_GetFunctionStatus(CK_SESSION_HANDLE hSession)
438 {
439 	return (CKR_FUNCTION_NOT_PARALLEL);
440 }
441 
442 /*
443  * PKCS#11 states that C_CancelFunction should always return
444  * CKR_FUNCTION_NOT_PARALLEL
445  */
446 /*ARGSUSED*/
447 CK_RV
448 C_CancelFunction(CK_SESSION_HANDLE hSession)
449 {
450 	return (CKR_FUNCTION_NOT_PARALLEL);
451 }
452 
453 /*
454  * Perform a write that can handle EINTR.
455  */
456 int
457 looping_write(int fd, void *buf, int len)
458 {
459 	char *p = buf;
460 	int cc, len2 = 0;
461 
462 	if (len == 0)
463 		return (0);
464 
465 	do {
466 		cc = write(fd, p, len);
467 		if (cc < 0) {
468 			if (errno == EINTR)
469 				continue;
470 			return (cc);
471 		} else if (cc == 0) {
472 			return (len2);
473 		} else {
474 			p += cc;
475 			len2 += cc;
476 			len -= cc;
477 		}
478 	} while (len > 0);
479 	return (len2);
480 }
481 
482 /*
483  * Perform a read that can handle EINTR.
484  */
485 int
486 looping_read(int fd, void *buf, int len)
487 {
488 	char *p = buf;
489 	int cc, len2 = 0;
490 
491 	do {
492 		cc = read(fd, p, len);
493 		if (cc < 0) {
494 			if (errno == EINTR)
495 				continue;
496 			return (cc);	/* errno is already set */
497 		} else if (cc == 0) {
498 			return (len2);
499 		} else {
500 			p += cc;
501 			len2 += cc;
502 			len -= cc;
503 		}
504 	} while (len > 0);
505 	return (len2);
506 }
507