xref: /illumos-gate/usr/src/lib/pkcs11/pkcs11_softtoken/common/softKeysUtil.c (revision 6e375c8351497b82ffa4f33cbf61d712999b4605)
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 <pthread.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <sys/types.h>
33 #include <security/cryptoki.h>
34 #include <sys/crypto/common.h>
35 #include <aes_impl.h>
36 #include <blowfish_impl.h>
37 #include <des_impl.h>
38 #include <arcfour.h>
39 #include "softGlobal.h"
40 #include "softSession.h"
41 #include "softObject.h"
42 #include "softDSA.h"
43 #include "softRSA.h"
44 #include "softDH.h"
45 #include "softEC.h"
46 #include "softRandom.h"
47 #include "softMAC.h"
48 #include "softOps.h"
49 #include "softKeys.h"
50 #include "softKeystore.h"
51 #include "softSSL.h"
52 #include "softASN1.h"
53 
54 
55 #define	local_min(a, b)	((a) < (b) ? (a) : (b))
56 
57 static CK_RV
58 soft_pkcs12_pbe(soft_session_t *, CK_MECHANISM_PTR, soft_object_t *);
59 
60 /*
61  * Create a temporary key object struct by filling up its template attributes.
62  */
63 CK_RV
64 soft_gen_keyobject(CK_ATTRIBUTE_PTR pTemplate,  CK_ULONG ulCount,
65     CK_ULONG *objecthandle_p, soft_session_t *sp,
66     CK_OBJECT_CLASS class, CK_KEY_TYPE key_type, CK_ULONG keylen, CK_ULONG mode,
67     boolean_t internal)
68 {
69 
70 	CK_RV rv;
71 	soft_object_t *new_objp = NULL;
72 
73 	new_objp = calloc(1, sizeof (soft_object_t));
74 	if (new_objp == NULL) {
75 		return (CKR_HOST_MEMORY);
76 	}
77 
78 	new_objp->extra_attrlistp = NULL;
79 
80 	/*
81 	 * Validate attribute template and fill in the attributes
82 	 * in the soft_object_t.
83 	 */
84 	rv = soft_build_key(pTemplate, ulCount, new_objp, class, key_type,
85 	    keylen, mode);
86 	if (rv != CKR_OK) {
87 		goto fail_cleanup1;
88 	}
89 
90 	/*
91 	 * If generating a key is an internal request (i.e. not a C_XXX
92 	 * API request), then skip the following checks.
93 	 */
94 	if (!internal) {
95 		rv = soft_pin_expired_check(new_objp);
96 		if (rv != CKR_OK) {
97 			goto fail_cleanup2;
98 		}
99 
100 		rv = soft_object_write_access_check(sp, new_objp);
101 		if (rv != CKR_OK) {
102 			goto fail_cleanup2;
103 		}
104 	}
105 
106 	/* Initialize the rest of stuffs in soft_object_t. */
107 	(void) pthread_mutex_init(&new_objp->object_mutex, NULL);
108 	new_objp->magic_marker = SOFTTOKEN_OBJECT_MAGIC;
109 
110 	/* Write the new token object to the keystore */
111 	if (IS_TOKEN_OBJECT(new_objp)) {
112 		new_objp->version = 1;
113 		new_objp->session_handle = (CK_SESSION_HANDLE)NULL;
114 		soft_add_token_object_to_slot(new_objp);
115 		/*
116 		 * Type casting the address of an object struct to
117 		 * an object handle.
118 		 */
119 		*objecthandle_p = (CK_ULONG)new_objp;
120 
121 		return (CKR_OK);
122 	}
123 
124 	new_objp->session_handle = (CK_SESSION_HANDLE)sp;
125 
126 	/* Add the new object to the session's object list. */
127 	soft_add_object_to_session(new_objp, sp);
128 
129 	/* Type casting the address of an object struct to an object handle. */
130 	*objecthandle_p =  (CK_ULONG)new_objp;
131 
132 	return (CKR_OK);
133 
134 fail_cleanup2:
135 	/*
136 	 * When any error occurs after soft_build_key(), we will need to
137 	 * clean up the memory allocated by the soft_build_key().
138 	 */
139 	soft_cleanup_object(new_objp);
140 
141 fail_cleanup1:
142 	if (new_objp) {
143 		/*
144 		 * The storage allocated inside of this object should have
145 		 * been cleaned up by the soft_build_key() if it failed.
146 		 * Therefore, we can safely free the object.
147 		 */
148 		free(new_objp);
149 	}
150 
151 	return (rv);
152 }
153 
154 CK_RV
155 soft_genkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
156     CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey)
157 {
158 
159 	CK_RV rv = CKR_OK;
160 	soft_object_t *secret_key;
161 	CK_KEY_TYPE key_type;
162 	CK_ULONG keylen = 0;
163 	CK_ULONG i;
164 	int des_strength = 0;
165 	int retry = 0;
166 	int keyfound = 0;
167 	boolean_t is_ssl_mech = B_FALSE;
168 
169 	switch (pMechanism->mechanism) {
170 	case CKM_DES_KEY_GEN:
171 		key_type = CKK_DES;
172 		break;
173 
174 	case CKM_DES3_KEY_GEN:
175 		key_type = CKK_DES3;
176 		break;
177 
178 	case CKM_AES_KEY_GEN:
179 		key_type = CKK_AES;
180 		break;
181 
182 	case CKM_BLOWFISH_KEY_GEN:
183 		key_type = CKK_BLOWFISH;
184 		break;
185 
186 	case CKM_RC4_KEY_GEN:
187 		key_type = CKK_RC4;
188 		break;
189 
190 	case CKM_SSL3_PRE_MASTER_KEY_GEN:
191 	case CKM_TLS_PRE_MASTER_KEY_GEN:
192 		if (pMechanism->pParameter == NULL ||
193 		    pMechanism->ulParameterLen != sizeof (CK_VERSION))
194 			return (CKR_TEMPLATE_INCOMPLETE);
195 		is_ssl_mech = B_TRUE;
196 		key_type = CKK_GENERIC_SECRET;
197 		keylen = 48;
198 		break;
199 
200 	case CKM_PKCS5_PBKD2:
201 		keyfound = 0;
202 		for (i = 0; i < ulCount && !keyfound; i++) {
203 			if (pTemplate[i].type == CKA_KEY_TYPE &&
204 			    pTemplate[i].pValue != NULL) {
205 				key_type = *((CK_KEY_TYPE*)pTemplate[i].pValue);
206 				keyfound = 1;
207 			}
208 		}
209 		if (!keyfound)
210 			return (CKR_TEMPLATE_INCOMPLETE);
211 		/*
212 		 * Make sure that parameters were given for this
213 		 * mechanism.
214 		 */
215 		if (pMechanism->pParameter == NULL ||
216 		    pMechanism->ulParameterLen !=
217 		    sizeof (CK_PKCS5_PBKD2_PARAMS))
218 			return (CKR_TEMPLATE_INCOMPLETE);
219 		break;
220 
221 	case CKM_PBE_SHA1_RC4_128:
222 		keyfound = 0;
223 		for (i = 0; i < ulCount; i++) {
224 			if (pTemplate[i].type == CKA_KEY_TYPE &&
225 			    pTemplate[i].pValue != NULL) {
226 				key_type = *((CK_KEY_TYPE*)pTemplate[i].pValue);
227 				keyfound = 1;
228 			}
229 			if (pTemplate[i].type == CKA_VALUE_LEN &&
230 			    pTemplate[i].pValue != NULL) {
231 				keylen = *((CK_ULONG*)pTemplate[i].pValue);
232 			}
233 		}
234 		/* If a keytype was specified, it had better be CKK_RC4 */
235 		if (keyfound && key_type != CKK_RC4)
236 			return (CKR_TEMPLATE_INCONSISTENT);
237 		else if (!keyfound)
238 			key_type = CKK_RC4;
239 
240 		/* If key length was specified, it better be 16 bytes */
241 		if (keylen != 0 && keylen != 16)
242 			return (CKR_TEMPLATE_INCONSISTENT);
243 
244 		/*
245 		 * Make sure that parameters were given for this
246 		 * mechanism.
247 		 */
248 		if (pMechanism->pParameter == NULL ||
249 		    pMechanism->ulParameterLen !=
250 		    sizeof (CK_PBE_PARAMS))
251 			return (CKR_TEMPLATE_INCOMPLETE);
252 		break;
253 	default:
254 		return (CKR_MECHANISM_INVALID);
255 	}
256 
257 	/* Create a new object for secret key. */
258 	rv = soft_gen_keyobject(pTemplate, ulCount, phKey, session_p,
259 	    CKO_SECRET_KEY, key_type, keylen, SOFT_GEN_KEY, B_FALSE);
260 
261 	if (rv != CKR_OK) {
262 		return (rv);
263 	}
264 
265 	/* Obtain the secret object pointer. */
266 	secret_key = (soft_object_t *)*phKey;
267 
268 	switch (pMechanism->mechanism) {
269 	case CKM_DES_KEY_GEN:
270 		/*
271 		 * Set up key value len since it is not a required
272 		 * attribute for C_GenerateKey.
273 		 */
274 		keylen = OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
275 		des_strength = DES;
276 		break;
277 
278 	case CKM_DES3_KEY_GEN:
279 		/*
280 		 * Set up key value len since it is not a required
281 		 * attribute for C_GenerateKey.
282 		 */
283 		keylen = OBJ_SEC_VALUE_LEN(secret_key) = DES3_KEYSIZE;
284 		des_strength = DES3;
285 		break;
286 
287 	case CKM_SSL3_PRE_MASTER_KEY_GEN:
288 	case CKM_TLS_PRE_MASTER_KEY_GEN:
289 		secret_key->bool_attr_mask |= DERIVE_BOOL_ON;
290 	/* FALLTHRU */
291 
292 	case CKM_AES_KEY_GEN:
293 	case CKM_BLOWFISH_KEY_GEN:
294 	case CKM_PBE_SHA1_RC4_128:
295 	case CKM_RC4_KEY_GEN:
296 		keylen = OBJ_SEC_VALUE_LEN(secret_key);
297 		break;
298 
299 	case CKM_PKCS5_PBKD2:
300 		/*
301 		 * PKCS#11 does not allow one to specify key
302 		 * sizes for DES and 3DES, so we must set it here
303 		 * when using PBKD2 algorithms.
304 		 */
305 		if (key_type == CKK_DES) {
306 			OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
307 			des_strength = DES;
308 		} else if (key_type == CKK_DES3) {
309 			OBJ_SEC_VALUE_LEN(secret_key) = DES3_KEYSIZE;
310 			des_strength = DES3;
311 		}
312 
313 		keylen = OBJ_SEC_VALUE_LEN(secret_key);
314 		break;
315 	}
316 
317 	if ((OBJ_SEC_VALUE(secret_key) = malloc(keylen)) == NULL) {
318 		if (IS_TOKEN_OBJECT(secret_key))
319 			soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
320 		else
321 			soft_delete_object(session_p, secret_key, B_FALSE);
322 
323 		return (CKR_HOST_MEMORY);
324 	}
325 	switch (pMechanism->mechanism) {
326 	case CKM_PBE_SHA1_RC4_128:
327 		/*
328 		 * Use the PBE algorithm described in PKCS#11 section
329 		 * 12.33 to derive the key.
330 		 */
331 		rv = soft_pkcs12_pbe(session_p, pMechanism, secret_key);
332 		break;
333 	case CKM_PKCS5_PBKD2:
334 		/* Generate keys using PKCS#5 PBKD2 algorithm */
335 		rv = soft_generate_pkcs5_pbkdf2_key(session_p, pMechanism,
336 		    secret_key);
337 		if (rv == CKR_OK && des_strength > 0) {
338 			/* Perform weak key checking for DES and DES3. */
339 			if (des_keycheck(OBJ_SEC_VALUE(secret_key),
340 			    des_strength, OBJ_SEC_VALUE(secret_key)) ==
341 			    B_FALSE) {
342 				/* We got a weak secret key. */
343 				rv = CKR_FUNCTION_FAILED;
344 			}
345 		}
346 		break;
347 	default:
348 		do {
349 			rv = soft_random_generator(
350 			    OBJ_SEC_VALUE(secret_key), keylen, B_FALSE);
351 
352 			/* If this fails, bail out */
353 			if (rv != CKR_OK)
354 				break;
355 
356 			/* Perform weak key checking for DES and DES3. */
357 			if (des_strength > 0) {
358 				rv = CKR_OK;
359 				if (des_keycheck(OBJ_SEC_VALUE(secret_key),
360 				    des_strength, OBJ_SEC_VALUE(secret_key)) ==
361 				    B_FALSE) {
362 					/* We got a weak key, retry! */
363 					retry++;
364 					rv = CKR_FUNCTION_FAILED;
365 				}
366 			}
367 			/*
368 			 * Copy over the SSL client version For SSL mechs
369 			 * The first two bytes of the key is the version
370 			 */
371 			if (is_ssl_mech)
372 				bcopy(pMechanism->pParameter,
373 				    OBJ_SEC_VALUE(secret_key),
374 				    sizeof (CK_VERSION));
375 
376 		} while (rv != CKR_OK && retry < KEYGEN_RETRY);
377 		if (retry == KEYGEN_RETRY)
378 			rv = CKR_FUNCTION_FAILED;
379 		break;
380 	}
381 
382 	if (rv != CKR_OK)
383 		if (IS_TOKEN_OBJECT(secret_key))
384 			soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
385 		else
386 			soft_delete_object(session_p, secret_key, B_FALSE);
387 
388 	if (IS_TOKEN_OBJECT(secret_key)) {
389 		/*
390 		 * All the info has been filled, so we can write to
391 		 * keystore now.
392 		 */
393 		rv = soft_put_object_to_keystore(secret_key);
394 		if (rv != CKR_OK)
395 			soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
396 	}
397 
398 	return (rv);
399 }
400 
401 CK_RV
402 soft_genkey_pair(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
403     CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicAttrCount,
404     CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateAttrCount,
405     CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey)
406 {
407 
408 	CK_RV rv;
409 	soft_object_t *public_key, *private_key;
410 	CK_KEY_TYPE key_type;
411 
412 	switch (pMechanism->mechanism) {
413 
414 	case CKM_RSA_PKCS_KEY_PAIR_GEN:
415 		key_type = CKK_RSA;
416 		break;
417 
418 	case CKM_DSA_KEY_PAIR_GEN:
419 		key_type = CKK_DSA;
420 		break;
421 
422 	case CKM_DH_PKCS_KEY_PAIR_GEN:
423 		key_type = CKK_DH;
424 		break;
425 
426 	case CKM_EC_KEY_PAIR_GEN:
427 		key_type = CKK_EC;
428 		break;
429 
430 	default:
431 		return (CKR_MECHANISM_INVALID);
432 	}
433 
434 	/* Create a new object for public key. */
435 	rv = soft_gen_keyobject(pPublicKeyTemplate, ulPublicAttrCount,
436 	    phPublicKey, session_p, CKO_PUBLIC_KEY, key_type, 0,
437 	    SOFT_GEN_KEY, B_FALSE);
438 
439 	if (rv != CKR_OK) {
440 		return (rv);
441 	}
442 
443 	/* Obtain the public object pointer. */
444 	public_key = (soft_object_t *)*phPublicKey;
445 
446 	/* Create a new object for private key. */
447 	rv = soft_gen_keyobject(pPrivateKeyTemplate, ulPrivateAttrCount,
448 	    phPrivateKey, session_p, CKO_PRIVATE_KEY, key_type, 0,
449 	    SOFT_GEN_KEY, B_FALSE);
450 
451 	if (rv != CKR_OK) {
452 		/*
453 		 * Both public key and private key must be successful.
454 		 */
455 		if (IS_TOKEN_OBJECT(public_key))
456 			soft_delete_token_object(public_key, B_FALSE, B_FALSE);
457 		else
458 			soft_delete_object(session_p, public_key, B_FALSE);
459 		return (rv);
460 	}
461 
462 	/* Obtain the private object pointer. */
463 	private_key = (soft_object_t *)*phPrivateKey;
464 
465 	/*
466 	 * At this point, both public key and private key objects
467 	 * are settled with the application specified attributes.
468 	 * We are ready to generate the rest of key attributes based
469 	 * on the existing attributes.
470 	 */
471 
472 	switch (key_type) {
473 	case CKK_RSA:
474 		rv = soft_rsa_genkey_pair(public_key, private_key);
475 		break;
476 
477 	case CKK_DSA:
478 		rv = soft_dsa_genkey_pair(public_key, private_key);
479 		break;
480 
481 	case CKK_DH:
482 		rv = soft_dh_genkey_pair(public_key, private_key);
483 		private_key->bool_attr_mask |= DERIVE_BOOL_ON;
484 		break;
485 	case CKK_EC:
486 		rv = soft_ec_genkey_pair(public_key, private_key);
487 		private_key->bool_attr_mask |= DERIVE_BOOL_ON;
488 		break;
489 	}
490 
491 	if (rv != CKR_OK) {
492 		if (IS_TOKEN_OBJECT(public_key)) {
493 			soft_delete_token_object(public_key, B_FALSE, B_FALSE);
494 			soft_delete_token_object(private_key, B_FALSE, B_FALSE);
495 		} else {
496 			soft_delete_object(session_p, public_key, B_FALSE);
497 			soft_delete_object(session_p, private_key, B_FALSE);
498 		}
499 	}
500 
501 	if (IS_TOKEN_OBJECT(public_key)) {
502 		/*
503 		 * All the info has been filled, so we can write to
504 		 * keystore now.
505 		 */
506 		rv = soft_put_object_to_keystore(public_key);
507 		if (rv != CKR_OK) {
508 			soft_delete_token_object(public_key, B_FALSE, B_FALSE);
509 			soft_delete_token_object(private_key, B_FALSE, B_FALSE);
510 		}
511 	}
512 
513 	if (IS_TOKEN_OBJECT(private_key)) {
514 		rv = soft_put_object_to_keystore(private_key);
515 		if (rv != CKR_OK) {
516 			/*
517 			 * We also need to delete the public token object
518 			 * from keystore.
519 			 */
520 			soft_delete_token_object(public_key, B_TRUE, B_FALSE);
521 			soft_delete_token_object(private_key, B_FALSE, B_FALSE);
522 		}
523 	}
524 
525 	return (rv);
526 }
527 
528 
529 CK_RV
530 soft_key_derive_check_length(soft_object_t *secret_key, CK_ULONG max_keylen)
531 {
532 
533 	switch (secret_key->key_type) {
534 	case CKK_GENERIC_SECRET:
535 		if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
536 			OBJ_SEC_VALUE_LEN(secret_key) = max_keylen;
537 			return (CKR_OK);
538 		} else if (OBJ_SEC_VALUE_LEN(secret_key) > max_keylen) {
539 			return (CKR_ATTRIBUTE_VALUE_INVALID);
540 		}
541 		break;
542 	case CKK_RC4:
543 	case CKK_AES:
544 	case CKK_BLOWFISH:
545 		if ((OBJ_SEC_VALUE_LEN(secret_key) == 0) ||
546 		    (OBJ_SEC_VALUE_LEN(secret_key) > max_keylen)) {
547 			/* RC4 and AES has variable key length */
548 			return (CKR_ATTRIBUTE_VALUE_INVALID);
549 		}
550 		break;
551 	case CKK_DES:
552 		if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
553 			/* DES has a well-defined length */
554 			OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
555 			return (CKR_OK);
556 		} else if (OBJ_SEC_VALUE_LEN(secret_key) != DES_KEYSIZE) {
557 			return (CKR_ATTRIBUTE_VALUE_INVALID);
558 		}
559 		break;
560 	case CKK_DES2:
561 		if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
562 			/* DES2 has a well-defined length */
563 			OBJ_SEC_VALUE_LEN(secret_key) = DES2_KEYSIZE;
564 			return (CKR_OK);
565 		} else if (OBJ_SEC_VALUE_LEN(secret_key) != DES2_KEYSIZE) {
566 			return (CKR_ATTRIBUTE_VALUE_INVALID);
567 		}
568 		break;
569 
570 	default:
571 		return (CKR_MECHANISM_INVALID);
572 	}
573 
574 	return (CKR_OK);
575 }
576 
577 /*
578  * PKCS#11 (12.33) says that v = 512 bits (64 bytes) for SHA1
579  * PBE methods.
580  */
581 #define	PKCS12_BUFFER_SIZE 64
582 /*
583  * PKCS#12 defines 3 different ID bytes to be used for
584  * deriving keys for different operations.
585  */
586 #define	PBE_ID_ENCRYPT	1
587 #define	PBE_ID_IV	2
588 #define	PBE_ID_MAC	3
589 #define	PBE_CEIL(a, b)	(((a)/(b)) + (((a)%(b)) > 0))
590 
591 static CK_RV
592 soft_pkcs12_pbe(soft_session_t *session_p,
593 		CK_MECHANISM_PTR pMechanism,
594 		soft_object_t *derived_key)
595 {
596 	CK_RV rv = CKR_OK;
597 	CK_PBE_PARAMS *params = pMechanism->pParameter;
598 	CK_ULONG c, i, j, k;
599 	CK_ULONG hashSize;
600 	CK_ULONG buffSize;
601 	/*
602 	 * Terse variable names are used to make following
603 	 * the PKCS#12 spec easier.
604 	 */
605 	CK_BYTE *A = NULL;
606 	CK_BYTE *Ai = NULL;
607 	CK_BYTE *B = NULL;
608 	CK_BYTE *D = NULL;
609 	CK_BYTE *I = NULL, *S, *P;
610 	CK_BYTE *keybuf = NULL;
611 	CK_ULONG Alen, Ilen, Slen, Plen, AiLen, Blen, Dlen;
612 	CK_ULONG keysize = OBJ_SEC_VALUE_LEN(derived_key);
613 	CK_MECHANISM digest_mech;
614 
615 	/* U = hash function output bits */
616 	if (pMechanism->mechanism == CKM_PBE_SHA1_RC4_128) {
617 		hashSize = SHA1_HASH_SIZE;
618 		buffSize = PKCS12_BUFFER_SIZE;
619 		digest_mech.mechanism = CKM_SHA_1;
620 		digest_mech.pParameter = NULL;
621 		digest_mech.ulParameterLen = 0;
622 	} else {
623 		/* we only support 1 PBE mech for now */
624 		return (CKR_MECHANISM_INVALID);
625 	}
626 	keybuf = OBJ_SEC_VALUE(derived_key);
627 
628 	Blen = Dlen = buffSize;
629 	D = (CK_BYTE *)malloc(Dlen);
630 	if (D == NULL) {
631 		rv = CKR_HOST_MEMORY;
632 		goto cleanup;
633 	}
634 
635 	B = (CK_BYTE *)malloc(Blen);
636 	if (B == NULL) {
637 		rv = CKR_HOST_MEMORY;
638 		goto cleanup;
639 	}
640 
641 	/*
642 	 * Initialize some values and create some buffers
643 	 * that we need later.
644 	 *
645 	 * Slen = buffSize * CEIL(SaltLength/buffSize)
646 	 */
647 	Slen = buffSize * PBE_CEIL(params->ulSaltLen, buffSize);
648 
649 	/*
650 	 * Plen = buffSize * CEIL(PasswordLength/buffSize)
651 	 */
652 	Plen = buffSize * PBE_CEIL(params->ulPasswordLen, buffSize);
653 
654 	/*
655 	 * From step 4: I = S + P, so: Ilen = Slen + Plen
656 	 */
657 	Ilen = Slen + Plen;
658 	I = (CK_BYTE *)malloc(Ilen);
659 	if (I == NULL) {
660 		rv = CKR_HOST_MEMORY;
661 		goto cleanup;
662 	}
663 
664 	S = I;
665 	P = I + Slen;
666 
667 	/*
668 	 * Step 1.
669 	 * We are only interested in deriving keys for encrypt/decrypt
670 	 * for now, so construct the "D"iversifier accordingly.
671 	 */
672 	(void) memset(D, PBE_ID_ENCRYPT, Dlen);
673 
674 	/*
675 	 * Step 2.
676 	 * Concatenate copies of the salt together to make S.
677 	 */
678 	for (i = 0; i < Slen; i += params->ulSaltLen) {
679 		(void) memcpy(S+i, params->pSalt,
680 		    ((Slen - i) > params->ulSaltLen ?
681 		    params->ulSaltLen : (Slen - i)));
682 	}
683 
684 	/*
685 	 * Step 3.
686 	 * Concatenate copies of the password together to make
687 	 * a string P.
688 	 */
689 	for (i = 0; i < Plen; i += params->ulPasswordLen) {
690 		(void) memcpy(P+i, params->pPassword,
691 		    ((Plen - i) > params->ulPasswordLen ?
692 		    params->ulPasswordLen : (Plen - i)));
693 	}
694 
695 	/*
696 	 * Step 4.
697 	 * I = S+P - this is now done because S and P are
698 	 * pointers into I.
699 	 *
700 	 * Step 5.
701 	 * c= CEIL[n/u]
702 	 * where n = pseudorandom bits of output desired.
703 	 */
704 	c = PBE_CEIL(keysize, hashSize);
705 
706 	/*
707 	 * Step 6.
708 	 */
709 	Alen = c * hashSize;
710 	A = (CK_BYTE *)malloc(Alen);
711 	if (A == NULL) {
712 		rv = CKR_HOST_MEMORY;
713 		goto cleanup;
714 	}
715 	AiLen = hashSize;
716 	Ai = (CK_BYTE *)malloc(AiLen);
717 	if (Ai == NULL) {
718 		rv = CKR_HOST_MEMORY;
719 		goto cleanup;
720 	}
721 
722 	/*
723 	 * Step 6a.
724 	 * Ai = Hr(D+I)
725 	 */
726 	for (i = 0; i < c; i++) {
727 		(void) pthread_mutex_lock(&session_p->session_mutex);
728 
729 		if (session_p->sign.flags & CRYPTO_OPERATION_ACTIVE) {
730 			(void) pthread_mutex_unlock(&session_p->session_mutex);
731 			rv = CKR_OPERATION_ACTIVE;
732 			goto cleanup;
733 		}
734 		session_p->sign.flags |= CRYPTO_OPERATION_ACTIVE;
735 		(void) pthread_mutex_unlock(&session_p->session_mutex);
736 
737 		for (j = 0; j < params->ulIteration; j++) {
738 			rv = soft_digest_init(session_p, &digest_mech);
739 			if (rv != CKR_OK)
740 				goto digest_done;
741 
742 			if (j == 0) {
743 				rv = soft_digest_update(session_p, D, Dlen);
744 				if (rv != CKR_OK)
745 					goto digest_done;
746 
747 				rv = soft_digest_update(session_p, I, Ilen);
748 			} else {
749 				rv = soft_digest_update(session_p, Ai, AiLen);
750 			}
751 			if (rv != CKR_OK)
752 				goto digest_done;
753 
754 			rv = soft_digest_final(session_p, Ai, &AiLen);
755 			if (rv != CKR_OK)
756 				goto digest_done;
757 		}
758 digest_done:
759 		(void) pthread_mutex_lock(&session_p->session_mutex);
760 		session_p->sign.flags &= ~CRYPTO_OPERATION_ACTIVE;
761 		(void) pthread_mutex_unlock(&session_p->session_mutex);
762 
763 		if (rv != CKR_OK)
764 			goto cleanup;
765 		/*
766 		 * Step 6b.
767 		 * Concatenate Ai to make B
768 		 */
769 		for (j = 0; j < Blen; j += hashSize) {
770 			(void) memcpy(B+j, Ai, ((Blen - j > hashSize) ?
771 			    hashSize : Blen - j));
772 		}
773 
774 		/*
775 		 * Step 6c.
776 		 */
777 		k = Ilen / Blen;
778 		for (j = 0; j < k; j++) {
779 			uchar_t idx;
780 			CK_ULONG m, q = 1, cbit = 0;
781 
782 			for (m = Blen - 1; m >= (CK_ULONG)0; m--, q = 0) {
783 				idx = m + j*Blen;
784 
785 				q += (CK_ULONG)I[idx] + (CK_ULONG)B[m];
786 				q += cbit;
787 				I[idx] = (CK_BYTE)(q & 0xff);
788 				cbit = (q > 0xff);
789 			}
790 		}
791 
792 		/*
793 		 * Step 7.
794 		 *  A += Ai
795 		 */
796 		(void) memcpy(A + i*hashSize, Ai, AiLen);
797 	}
798 
799 	/*
800 	 * Step 8.
801 	 * The final output of this process is the A buffer
802 	 */
803 	(void) memcpy(keybuf, A, keysize);
804 
805 cleanup:
806 	if (A) {
807 		bzero(A, Alen);
808 		free(A);
809 	}
810 	if (Ai) {
811 		bzero(Ai, AiLen);
812 		free(Ai);
813 	}
814 	if (B) {
815 		bzero(B, Blen);
816 		free(B);
817 	}
818 	if (D) {
819 		bzero(D, Dlen);
820 		free(D);
821 	}
822 	if (I) {
823 		bzero(I, Ilen);
824 		free(I);
825 	}
826 	return (rv);
827 }
828 
829 CK_RV
830 soft_derivekey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
831     soft_object_t *basekey_p, CK_ATTRIBUTE_PTR pTemplate,
832     CK_ULONG ulAttributeCount, CK_OBJECT_HANDLE_PTR phKey)
833 {
834 
835 	CK_RV rv = CKR_OK;
836 	soft_object_t *secret_key;
837 	CK_MECHANISM digest_mech;
838 	CK_BYTE hash[SHA512_DIGEST_LENGTH]; /* space enough for all mechs */
839 	CK_ULONG hash_len = SHA512_DIGEST_LENGTH;
840 	CK_ULONG secret_key_len;
841 	CK_ULONG hash_size;
842 
843 	switch (pMechanism->mechanism) {
844 	case CKM_DH_PKCS_DERIVE:
845 		/*
846 		 * Create a new object for secret key. The key type should
847 		 * be provided in the template.
848 		 */
849 		rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
850 		    phKey, session_p, CKO_SECRET_KEY, (CK_KEY_TYPE)~0UL, 0,
851 		    SOFT_DERIVE_KEY_DH, B_FALSE);
852 
853 		if (rv != CKR_OK) {
854 			return (rv);
855 		}
856 
857 		/* Obtain the secret object pointer. */
858 		secret_key = (soft_object_t *)*phKey;
859 
860 		rv = soft_dh_key_derive(basekey_p, secret_key,
861 		    (CK_BYTE *)pMechanism->pParameter,
862 		    pMechanism->ulParameterLen);
863 
864 		if (rv != CKR_OK) {
865 			if (IS_TOKEN_OBJECT(secret_key))
866 				soft_delete_token_object(secret_key, B_FALSE,
867 				    B_FALSE);
868 			else
869 				soft_delete_object(session_p, secret_key,
870 				    B_FALSE);
871 			return (rv);
872 		}
873 
874 		break;
875 
876 	case CKM_ECDH1_DERIVE:
877 		/*
878 		 * Create a new object for secret key. The key type should
879 		 * be provided in the template.
880 		 */
881 		rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
882 		    phKey, session_p, CKO_SECRET_KEY, (CK_KEY_TYPE)~0UL, 0,
883 		    SOFT_DERIVE_KEY_DH, B_FALSE);
884 
885 		if (rv != CKR_OK) {
886 			return (rv);
887 		}
888 
889 		/* Obtain the secret object pointer. */
890 		secret_key = (soft_object_t *)*phKey;
891 
892 		rv = soft_ec_key_derive(basekey_p, secret_key,
893 		    (CK_BYTE *)pMechanism->pParameter,
894 		    pMechanism->ulParameterLen);
895 
896 		if (rv != CKR_OK) {
897 			if (IS_TOKEN_OBJECT(secret_key))
898 				soft_delete_token_object(secret_key, B_FALSE,
899 				    B_FALSE);
900 			else
901 				soft_delete_object(session_p, secret_key,
902 				    B_FALSE);
903 			return (rv);
904 		}
905 
906 		break;
907 
908 	case CKM_SHA1_KEY_DERIVATION:
909 		hash_size = SHA1_HASH_SIZE;
910 		digest_mech.mechanism = CKM_SHA_1;
911 		goto common;
912 
913 	case CKM_MD5_KEY_DERIVATION:
914 		hash_size = MD5_HASH_SIZE;
915 		digest_mech.mechanism = CKM_MD5;
916 		goto common;
917 
918 	case CKM_SHA256_KEY_DERIVATION:
919 		hash_size = SHA256_DIGEST_LENGTH;
920 		digest_mech.mechanism = CKM_SHA256;
921 		goto common;
922 
923 	case CKM_SHA384_KEY_DERIVATION:
924 		hash_size = SHA384_DIGEST_LENGTH;
925 		digest_mech.mechanism = CKM_SHA384;
926 		goto common;
927 
928 	case CKM_SHA512_KEY_DERIVATION:
929 		hash_size = SHA512_DIGEST_LENGTH;
930 		digest_mech.mechanism = CKM_SHA512;
931 		goto common;
932 
933 common:
934 		/*
935 		 * Create a new object for secret key. The key type is optional
936 		 * to be provided in the template. If it is not specified in
937 		 * the template, the default is CKK_GENERIC_SECRET.
938 		 */
939 		rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
940 		    phKey, session_p, CKO_SECRET_KEY,
941 		    (CK_KEY_TYPE)CKK_GENERIC_SECRET, 0,
942 		    SOFT_DERIVE_KEY_OTHER, B_FALSE);
943 
944 		if (rv != CKR_OK) {
945 			return (rv);
946 		}
947 
948 		/* Obtain the secret object pointer. */
949 		secret_key = (soft_object_t *)*phKey;
950 
951 		/* Validate the key type and key length */
952 		rv = soft_key_derive_check_length(secret_key, hash_size);
953 		if (rv != CKR_OK) {
954 			if (IS_TOKEN_OBJECT(secret_key))
955 				soft_delete_token_object(secret_key, B_FALSE,
956 				    B_FALSE);
957 			else
958 				soft_delete_object(session_p, secret_key,
959 				    B_FALSE);
960 			return (rv);
961 		}
962 
963 		/*
964 		 * Derive the secret key by digesting the value of another
965 		 * secret key (base key) with SHA-1 or MD5.
966 		 */
967 		rv = soft_digest_init_internal(session_p, &digest_mech);
968 		if (rv != CKR_OK) {
969 			if (IS_TOKEN_OBJECT(secret_key))
970 				soft_delete_token_object(secret_key, B_FALSE,
971 				    B_FALSE);
972 			else
973 				soft_delete_object(session_p, secret_key,
974 				    B_FALSE);
975 			return (rv);
976 		}
977 
978 		rv = soft_digest(session_p, OBJ_SEC_VALUE(basekey_p),
979 		    OBJ_SEC_VALUE_LEN(basekey_p), hash, &hash_len);
980 
981 		(void) pthread_mutex_lock(&session_p->session_mutex);
982 		/* soft_digest_common() has freed the digest context */
983 		session_p->digest.flags = 0;
984 		(void) pthread_mutex_unlock(&session_p->session_mutex);
985 
986 		if (rv != CKR_OK) {
987 			if (IS_TOKEN_OBJECT(secret_key))
988 				soft_delete_token_object(secret_key, B_FALSE,
989 				    B_FALSE);
990 			else
991 				soft_delete_object(session_p, secret_key,
992 				    B_FALSE);
993 			return (rv);
994 		}
995 
996 		secret_key_len = OBJ_SEC_VALUE_LEN(secret_key);
997 
998 		if ((OBJ_SEC_VALUE(secret_key) = malloc(secret_key_len)) ==
999 		    NULL) {
1000 			if (IS_TOKEN_OBJECT(secret_key))
1001 				soft_delete_token_object(secret_key, B_FALSE,
1002 				    B_FALSE);
1003 			else
1004 				soft_delete_object(session_p, secret_key,
1005 				    B_FALSE);
1006 			return (CKR_HOST_MEMORY);
1007 		}
1008 
1009 		/*
1010 		 * The key produced by this mechanism will be of the
1011 		 * specified type and length.
1012 		 * The truncation removes extra bytes from the leading
1013 		 * of the digested key value.
1014 		 */
1015 		(void) memcpy(OBJ_SEC_VALUE(secret_key),
1016 		    (hash + hash_len - secret_key_len),
1017 		    secret_key_len);
1018 
1019 		break;
1020 
1021 	/*
1022 	 * The key sensitivity and extractability rules for the generated
1023 	 * keys will be enforced inside soft_ssl_master_key_derive() and
1024 	 * soft_ssl_key_and_mac_derive()
1025 	 */
1026 	case CKM_SSL3_MASTER_KEY_DERIVE:
1027 	case CKM_SSL3_MASTER_KEY_DERIVE_DH:
1028 	case CKM_TLS_MASTER_KEY_DERIVE:
1029 	case CKM_TLS_MASTER_KEY_DERIVE_DH:
1030 		if (phKey == NULL_PTR)
1031 			return (CKR_ARGUMENTS_BAD);
1032 		return (soft_ssl_master_key_derive(session_p, pMechanism,
1033 		    basekey_p, pTemplate, ulAttributeCount, phKey));
1034 
1035 	case CKM_SSL3_KEY_AND_MAC_DERIVE:
1036 	case CKM_TLS_KEY_AND_MAC_DERIVE:
1037 		return (soft_ssl_key_and_mac_derive(session_p, pMechanism,
1038 		    basekey_p, pTemplate, ulAttributeCount));
1039 
1040 	case CKM_TLS_PRF:
1041 		if (pMechanism->pParameter == NULL ||
1042 		    pMechanism->ulParameterLen != sizeof (CK_TLS_PRF_PARAMS) ||
1043 		    phKey != NULL)
1044 			return (CKR_ARGUMENTS_BAD);
1045 
1046 		if (pTemplate != NULL)
1047 			return (CKR_TEMPLATE_INCONSISTENT);
1048 
1049 		return (derive_tls_prf(
1050 		    (CK_TLS_PRF_PARAMS_PTR)pMechanism->pParameter, basekey_p));
1051 
1052 	default:
1053 		return (CKR_MECHANISM_INVALID);
1054 	}
1055 
1056 	soft_derive_enforce_flags(basekey_p, secret_key);
1057 
1058 	if (IS_TOKEN_OBJECT(secret_key)) {
1059 		/*
1060 		 * All the info has been filled, so we can write to
1061 		 * keystore now.
1062 		 */
1063 		rv = soft_put_object_to_keystore(secret_key);
1064 		if (rv != CKR_OK)
1065 			soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
1066 	}
1067 
1068 	return (rv);
1069 }
1070 
1071 
1072 /*
1073  * Perform key derivation rules on key's sensitivity and extractability.
1074  */
1075 void
1076 soft_derive_enforce_flags(soft_object_t *basekey, soft_object_t *newkey)
1077 {
1078 
1079 	boolean_t new_sensitive = B_FALSE;
1080 	boolean_t new_extractable = B_FALSE;
1081 
1082 	/*
1083 	 * The sensitive and extractable bits have been set when
1084 	 * the newkey was built.
1085 	 */
1086 	if (newkey->bool_attr_mask & SENSITIVE_BOOL_ON) {
1087 		new_sensitive = B_TRUE;
1088 	}
1089 
1090 	if (newkey->bool_attr_mask & EXTRACTABLE_BOOL_ON) {
1091 		new_extractable = B_TRUE;
1092 	}
1093 
1094 	/* Derive the CKA_ALWAYS_SENSITIVE flag */
1095 	if (!basekey->bool_attr_mask & ALWAYS_SENSITIVE_BOOL_ON) {
1096 		/*
1097 		 * If the base key has its CKA_ALWAYS_SENSITIVE set to
1098 		 * FALSE, then the derived key will as well.
1099 		 */
1100 		newkey->bool_attr_mask &= ~ALWAYS_SENSITIVE_BOOL_ON;
1101 	} else {
1102 		/*
1103 		 * If the base key has its CKA_ALWAYS_SENSITIVE set to TRUE,
1104 		 * then the derived key has the CKA_ALWAYS_SENSITIVE set to
1105 		 * the same value as its CKA_SENSITIVE;
1106 		 */
1107 		if (new_sensitive) {
1108 			newkey->bool_attr_mask |= ALWAYS_SENSITIVE_BOOL_ON;
1109 		} else {
1110 			newkey->bool_attr_mask &= ~ALWAYS_SENSITIVE_BOOL_ON;
1111 		}
1112 	}
1113 
1114 	/* Derive the CKA_NEVER_EXTRACTABLE flag */
1115 	if (!basekey->bool_attr_mask & NEVER_EXTRACTABLE_BOOL_ON) {
1116 		/*
1117 		 * If the base key has its CKA_NEVER_EXTRACTABLE set to
1118 		 * FALSE, then the derived key will as well.
1119 		 */
1120 		newkey->bool_attr_mask &= ~NEVER_EXTRACTABLE_BOOL_ON;
1121 	} else {
1122 		/*
1123 		 * If the base key has its CKA_NEVER_EXTRACTABLE set to TRUE,
1124 		 * then the derived key has the CKA_NEVER_EXTRACTABLE set to
1125 		 * the opposite value from its CKA_EXTRACTABLE;
1126 		 */
1127 		if (new_extractable) {
1128 			newkey->bool_attr_mask &= ~NEVER_EXTRACTABLE_BOOL_ON;
1129 		} else {
1130 			newkey->bool_attr_mask |= NEVER_EXTRACTABLE_BOOL_ON;
1131 		}
1132 	}
1133 
1134 	/* Set the CKA_LOCAL flag to false */
1135 	newkey->bool_attr_mask &= ~LOCAL_BOOL_ON;
1136 }
1137 
1138 
1139 /*
1140  * do_prf
1141  *
1142  * This routine implements Step 3. of the PBKDF2 function
1143  * defined in PKCS#5 for generating derived keys from a
1144  * password.
1145  *
1146  * Currently, PRF is always SHA_1_HMAC.
1147  */
1148 static CK_RV
1149 do_prf(soft_session_t *session_p,
1150 	CK_PKCS5_PBKD2_PARAMS_PTR params,
1151 	soft_object_t *hmac_key,
1152 	CK_BYTE *newsalt, CK_ULONG saltlen,
1153 	CK_BYTE *blockdata, CK_ULONG blocklen)
1154 {
1155 	CK_RV rv = CKR_OK;
1156 	CK_MECHANISM digest_mech = {CKM_SHA_1_HMAC, NULL, 0};
1157 	CK_BYTE buffer[2][SHA1_HASH_SIZE];
1158 	CK_ULONG hmac_outlen = SHA1_HASH_SIZE;
1159 	CK_ULONG inlen;
1160 	CK_BYTE *input, *output;
1161 	CK_ULONG i, j;
1162 
1163 	input = newsalt;
1164 	inlen = saltlen;
1165 
1166 	output = buffer[1];
1167 	(void) pthread_mutex_lock(&session_p->session_mutex);
1168 
1169 	if (session_p->sign.flags & CRYPTO_OPERATION_ACTIVE) {
1170 		(void) pthread_mutex_unlock(&session_p->session_mutex);
1171 		return (CKR_OPERATION_ACTIVE);
1172 	}
1173 	session_p->sign.flags |= CRYPTO_OPERATION_ACTIVE;
1174 	(void) pthread_mutex_unlock(&session_p->session_mutex);
1175 
1176 	for (i = 0; i < params->iterations; i++) {
1177 		/*
1178 		 * The key doesn't change, its always the
1179 		 * password iniitally given.
1180 		 */
1181 		rv = soft_sign_init(session_p, &digest_mech, hmac_key);
1182 
1183 		if (rv != CKR_OK) {
1184 			goto cleanup;
1185 		}
1186 
1187 		/* Call PRF function (SHA1_HMAC for now). */
1188 		rv = soft_sign(session_p, input, inlen, output, &hmac_outlen);
1189 
1190 		if (rv != CKR_OK) {
1191 			goto cleanup;
1192 		}
1193 		/*
1194 		 * The first time, initialize the output buffer
1195 		 * with the HMAC signature.
1196 		 */
1197 		if (i == 0) {
1198 			(void) memcpy(blockdata, output,
1199 			    local_min(blocklen, hmac_outlen));
1200 		} else {
1201 			/*
1202 			 * XOR the existing data with output from PRF.
1203 			 *
1204 			 * Only XOR up to the length of the blockdata,
1205 			 * it may be less than a full hmac buffer when
1206 			 * the final block is being computed.
1207 			 */
1208 			for (j = 0; j < hmac_outlen && j < blocklen; j++)
1209 				blockdata[j] ^= output[j];
1210 		}
1211 		/* Output from previous PRF is input for next round */
1212 		input = output;
1213 		inlen = hmac_outlen;
1214 
1215 		/*
1216 		 * Switch buffers to avoid overuse of memcpy.
1217 		 * Initially we used buffer[1], so after the end of
1218 		 * the first iteration (i==0), we switch to buffer[0]
1219 		 * and continue swapping with each iteration.
1220 		 */
1221 		output = buffer[i%2];
1222 	}
1223 cleanup:
1224 	(void) pthread_mutex_lock(&session_p->session_mutex);
1225 	session_p->sign.flags &= ~CRYPTO_OPERATION_ACTIVE;
1226 	(void) pthread_mutex_unlock(&session_p->session_mutex);
1227 
1228 	return (rv);
1229 }
1230 
1231 static CK_RV
1232 soft_create_hmac_key(soft_session_t *session_p,  CK_BYTE *passwd,
1233 		CK_ULONG passwd_len, CK_OBJECT_HANDLE_PTR phKey)
1234 {
1235 	CK_RV rv = CKR_OK;
1236 	CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
1237 	CK_KEY_TYPE keytype = CKK_GENERIC_SECRET;
1238 	CK_BBOOL True = TRUE;
1239 	CK_ATTRIBUTE keytemplate[4];
1240 	/*
1241 	 * We must initialize each template member individually
1242 	 * because at the time of initial coding for ON10, the
1243 	 * compiler was using the "-xc99=%none" option
1244 	 * which prevents us from being able to declare the whole
1245 	 * template in place as usual.
1246 	 */
1247 	keytemplate[0].type = CKA_CLASS;
1248 	keytemplate[0].pValue = &keyclass;
1249 	keytemplate[0].ulValueLen =  sizeof (keyclass);
1250 
1251 	keytemplate[1].type = CKA_KEY_TYPE;
1252 	keytemplate[1].pValue = &keytype;
1253 	keytemplate[1].ulValueLen =  sizeof (keytype);
1254 
1255 	keytemplate[2].type = CKA_SIGN;
1256 	keytemplate[2].pValue = &True;
1257 	keytemplate[2].ulValueLen =  sizeof (True);
1258 
1259 	keytemplate[3].type = CKA_VALUE;
1260 	keytemplate[3].pValue = passwd;
1261 	keytemplate[3].ulValueLen = passwd_len;
1262 	/*
1263 	 * Create a generic key object to be used for HMAC operations.
1264 	 * The "value" for this key is the password from the
1265 	 * mechanism parameter structure.
1266 	 */
1267 	rv = soft_gen_keyobject(keytemplate,
1268 	    sizeof (keytemplate)/sizeof (CK_ATTRIBUTE), phKey, session_p,
1269 	    CKO_SECRET_KEY, (CK_KEY_TYPE)CKK_GENERIC_SECRET, 0,
1270 	    SOFT_CREATE_OBJ, B_TRUE);
1271 
1272 	return (rv);
1273 }
1274 
1275 CK_RV
1276 soft_generate_pkcs5_pbkdf2_key(soft_session_t *session_p,
1277 		CK_MECHANISM_PTR pMechanism,
1278 		soft_object_t *secret_key)
1279 {
1280 	CK_RV rv = CKR_OK;
1281 	CK_PKCS5_PBKD2_PARAMS	*params =
1282 	    (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter;
1283 	CK_ULONG hLen = SHA1_HASH_SIZE;
1284 	CK_ULONG dkLen, i;
1285 	CK_ULONG blocks, remainder;
1286 	CK_OBJECT_HANDLE phKey = 0;
1287 	soft_object_t *hmac_key = NULL;
1288 	CK_BYTE *salt = NULL;
1289 	CK_BYTE *keydata = NULL;
1290 
1291 	params = (CK_PKCS5_PBKD2_PARAMS_PTR) pMechanism->pParameter;
1292 
1293 	if (params->prf != CKP_PKCS5_PBKD2_HMAC_SHA1)
1294 		return (CKR_MECHANISM_PARAM_INVALID);
1295 
1296 	if (params->pPrfData != NULL || params->ulPrfDataLen != 0)
1297 		return (CKR_DATA_INVALID);
1298 
1299 	if (params->saltSource != CKZ_SALT_SPECIFIED ||
1300 	    params->iterations == 0)
1301 		return (CKR_MECHANISM_PARAM_INVALID);
1302 
1303 	/*
1304 	 * Create a key object to use for HMAC operations.
1305 	 */
1306 	rv = soft_create_hmac_key(session_p, params->pPassword,
1307 	    *params->ulPasswordLen, &phKey);
1308 
1309 	if (rv != CKR_OK)
1310 		return (rv);
1311 
1312 	hmac_key = (soft_object_t *)phKey;
1313 
1314 	/* Step 1. */
1315 	dkLen = OBJ_SEC_VALUE_LEN(secret_key);  /* length of desired key */
1316 
1317 	if (dkLen > ((((u_longlong_t)1)<<32)-1)*hLen) {
1318 		(void) soft_delete_object(session_p, hmac_key, B_FALSE);
1319 		return (CKR_KEY_SIZE_RANGE);
1320 	}
1321 
1322 	/* Step 2. */
1323 	blocks = dkLen / hLen;
1324 
1325 	/* crude "Ceiling" function to adjust the number of blocks to use */
1326 	if (blocks * hLen != dkLen)
1327 		blocks++;
1328 
1329 	remainder = dkLen - ((blocks - 1) * hLen);
1330 
1331 	/* Step 3 */
1332 	salt = (CK_BYTE *)malloc(params->ulSaltSourceDataLen + 4);
1333 	if (salt == NULL) {
1334 		(void) soft_delete_object(session_p, hmac_key, B_FALSE);
1335 		return (CKR_HOST_MEMORY);
1336 	}
1337 	/*
1338 	 * Nothing in PKCS#5 says you cannot pass an empty
1339 	 * salt, so we will allow for this and not return error
1340 	 * if the salt is not specified.
1341 	 */
1342 	if (params->pSaltSourceData != NULL && params->ulSaltSourceDataLen > 0)
1343 		(void) memcpy(salt, params->pSaltSourceData,
1344 		    params->ulSaltSourceDataLen);
1345 
1346 	/*
1347 	 * Get pointer to the data section of the key,
1348 	 * this will be used below as output from the
1349 	 * PRF iteration/concatenations so that when the
1350 	 * blocks are all iterated, the secret_key will
1351 	 * have the resulting derived key value.
1352 	 */
1353 	keydata = (CK_BYTE *)OBJ_SEC_VALUE(secret_key);
1354 
1355 	/* Step 4. */
1356 	for (i = 0; i < blocks && (rv == CKR_OK); i++) {
1357 		CK_BYTE *s;
1358 
1359 		s = salt + params->ulSaltSourceDataLen;
1360 
1361 		/*
1362 		 * Append the block index to the salt as input
1363 		 * to the PRF.  Block index should start at 1
1364 		 * not 0.
1365 		 */
1366 		*s++ = ((i+1) >> 24) & 0xff;
1367 		*s++ = ((i+1) >> 16) & 0xff;
1368 		*s++ = ((i+1) >> 8) & 0xff;
1369 		*s   = ((i+1)) & 0xff;
1370 
1371 		/*
1372 		 * Adjust the key pointer so we always append the
1373 		 * PRF output to the current key.
1374 		 */
1375 		rv = do_prf(session_p, params, hmac_key,
1376 		    salt, params->ulSaltSourceDataLen + 4, keydata,
1377 		    ((i + 1) == blocks ? remainder : hLen));
1378 
1379 		keydata += hLen;
1380 	}
1381 	(void) soft_delete_object(session_p, hmac_key, B_FALSE);
1382 	free(salt);
1383 
1384 	return (rv);
1385 }
1386 
1387 CK_RV
1388 soft_wrapkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
1389 		soft_object_t *wrappingKey_p, soft_object_t *hkey_p,
1390 		CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen)
1391 {
1392 	CK_RV		rv = CKR_OK;
1393 	CK_ULONG	plain_len = 0;
1394 	CK_BYTE_PTR	plain_data = NULL;
1395 	CK_ULONG	padded_len = 0;
1396 	CK_BYTE_PTR	padded_data = NULL;
1397 	CK_ULONG	wkey_blksz = 1;		/* so modulo will work right */
1398 
1399 	/* Check if the mechanism is supported. */
1400 	switch (pMechanism->mechanism) {
1401 	case CKM_DES_CBC_PAD:
1402 	case CKM_DES3_CBC_PAD:
1403 	case CKM_AES_CBC_PAD:
1404 		/*
1405 		 * Secret key mechs with padding can be used to wrap secret
1406 		 * keys and private keys only.  See PKCS#11, * sec 11.14,
1407 		 * C_WrapKey and secs 12.* for each mechanism's wrapping/
1408 		 * unwrapping constraints.
1409 		 */
1410 		if (hkey_p->class != CKO_SECRET_KEY && hkey_p->class !=
1411 		    CKO_PRIVATE_KEY)
1412 			return (CKR_MECHANISM_INVALID);
1413 		break;
1414 	case CKM_RSA_PKCS:
1415 	case CKM_RSA_X_509:
1416 	case CKM_DES_ECB:
1417 	case CKM_DES3_ECB:
1418 	case CKM_AES_ECB:
1419 	case CKM_DES_CBC:
1420 	case CKM_DES3_CBC:
1421 	case CKM_AES_CBC:
1422 	case CKM_AES_CTR:
1423 	case CKM_BLOWFISH_CBC:
1424 		/*
1425 		 * Unpadded secret key mechs and private key mechs are only
1426 		 * defined for wrapping secret keys.  See PKCS#11 refs above.
1427 		 */
1428 		if (hkey_p->class != CKO_SECRET_KEY)
1429 			return (CKR_MECHANISM_INVALID);
1430 		break;
1431 	default:
1432 		return (CKR_MECHANISM_INVALID);
1433 	}
1434 
1435 	if (hkey_p->class == CKO_SECRET_KEY) {
1436 		plain_data = OBJ_SEC_VALUE(hkey_p);
1437 		plain_len = OBJ_SEC_VALUE_LEN(hkey_p);
1438 	} else {
1439 		/*
1440 		 * BER-encode the object to be wrapped:  call first with
1441 		 * plain_data = NULL to get the size needed, allocate that
1442 		 * much space, call again to fill space with actual data.
1443 		 */
1444 		rv = soft_object_to_asn1(hkey_p, NULL, &plain_len);
1445 		if (rv != CKR_OK)
1446 			return (rv);
1447 		if ((plain_data = malloc(plain_len)) == NULL)
1448 			return (CKR_HOST_MEMORY);
1449 		(void) memset(plain_data, 0x0, plain_len);
1450 		rv = soft_object_to_asn1(hkey_p, plain_data, &plain_len);
1451 		if (rv != CKR_OK)
1452 			goto cleanup_wrap;
1453 	}
1454 
1455 	/*
1456 	 * For unpadded ECB and CBC mechanisms, the object needs to be
1457 	 * padded to the wrapping key's blocksize prior to the encryption.
1458 	 */
1459 	padded_len = plain_len;
1460 	padded_data = plain_data;
1461 
1462 	switch (pMechanism->mechanism) {
1463 	case CKM_DES_ECB:
1464 	case CKM_DES3_ECB:
1465 	case CKM_AES_ECB:
1466 	case CKM_DES_CBC:
1467 	case CKM_DES3_CBC:
1468 	case CKM_AES_CBC:
1469 	case CKM_BLOWFISH_CBC:
1470 		/* Find the block size of the wrapping key. */
1471 		if (wrappingKey_p->class == CKO_SECRET_KEY) {
1472 			switch (wrappingKey_p->key_type) {
1473 			case CKK_DES:
1474 			case CKK_DES2:
1475 			case CKK_DES3:
1476 				wkey_blksz = DES_BLOCK_LEN;
1477 				break;
1478 			case CKK_AES:
1479 				wkey_blksz = AES_BLOCK_LEN;
1480 				break;
1481 			case CKK_BLOWFISH:
1482 				wkey_blksz = BLOWFISH_BLOCK_LEN;
1483 				break;
1484 			default:
1485 				break;
1486 			}
1487 		} else {
1488 			rv = CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
1489 			goto cleanup_wrap;
1490 		}
1491 
1492 		/* Extend the plain text data to block size boundary.  */
1493 		if ((padded_len % wkey_blksz) != 0) {
1494 			padded_len += (wkey_blksz - (plain_len % wkey_blksz));
1495 			if ((padded_data = malloc(padded_len)) == NULL) {
1496 				rv = CKR_HOST_MEMORY;
1497 				goto cleanup_wrap;
1498 			}
1499 			(void) memset(padded_data, 0x0, padded_len);
1500 			(void) memcpy(padded_data, plain_data, plain_len);
1501 		}
1502 		break;
1503 	default:
1504 		break;
1505 	}
1506 
1507 	rv = soft_encrypt_init(session_p, pMechanism, wrappingKey_p);
1508 	if (rv != CKR_OK)
1509 		goto cleanup_wrap;
1510 
1511 	rv = soft_encrypt(session_p, padded_data, padded_len,
1512 	    pWrappedKey, pulWrappedKeyLen);
1513 
1514 cleanup_wrap:
1515 	if (padded_data != NULL && padded_len != plain_len) {
1516 		/* Clear buffer before returning to memory pool. */
1517 		(void) memset(padded_data, 0x0, padded_len);
1518 		free(padded_data);
1519 	}
1520 
1521 	if ((hkey_p->class != CKO_SECRET_KEY) && (plain_data != NULL)) {
1522 		/* Clear buffer before returning to memory pool. */
1523 		(void) memset(plain_data, 0x0, plain_len);
1524 		free(plain_data);
1525 	}
1526 
1527 	return (rv);
1528 }
1529 
1530 /*
1531  * Quick check for whether unwrapped key length is appropriate for key type
1532  * and whether it needs to be truncated (in case the wrapping function had
1533  * to pad the key prior to wrapping).
1534  */
1535 static CK_RV
1536 soft_unwrap_secret_len_check(CK_KEY_TYPE keytype, CK_MECHANISM_TYPE mechtype,
1537 	CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount)
1538 {
1539 	CK_ULONG	i;
1540 	boolean_t	isValueLen = B_FALSE;
1541 
1542 	/*
1543 	 * Based on the key type and the mech used to unwrap, need to
1544 	 * determine if CKA_VALUE_LEN should or should not be specified.
1545 	 * PKCS#11 v2.11 restricts CKA_VALUE_LEN from being specified
1546 	 * for C_UnwrapKey for all mechs and key types, but v2.20 loosens
1547 	 * that restriction, perhaps because it makes it impossible to
1548 	 * determine the original length of unwrapped variable-length secret
1549 	 * keys, such as RC4, AES, and GENERIC_SECRET.  These variable-length
1550 	 * secret keys would have been padded with trailing null-bytes so
1551 	 * that they could be successfully wrapped with *_ECB and *_CBC
1552 	 * mechanisms.  Hence for unwrapping with these mechs, CKA_VALUE_LEN
1553 	 * must be specified.  For unwrapping with other mechs, such as
1554 	 * *_CBC_PAD, the CKA_VALUE_LEN is not needed.
1555 	 */
1556 
1557 	/* Find out if template has CKA_VALUE_LEN. */
1558 	for (i = 0; i < ulAttributeCount; i++) {
1559 		if (pTemplate[i].type == CKA_VALUE_LEN &&
1560 		    pTemplate[i].pValue != NULL) {
1561 			isValueLen = B_TRUE;
1562 			break;
1563 		}
1564 	}
1565 
1566 	/* Does its presence  conflict with the mech type and key type? */
1567 	switch (mechtype) {
1568 	case CKM_DES_ECB:
1569 	case CKM_DES3_ECB:
1570 	case CKM_AES_ECB:
1571 	case CKM_DES_CBC:
1572 	case CKM_DES3_CBC:
1573 	case CKM_AES_CBC:
1574 	case CKM_BLOWFISH_CBC:
1575 		/*
1576 		 * CKA_VALUE_LEN must be specified
1577 		 * if keytype is CKK_RC4, CKK_AES and CKK_GENERIC_SECRET
1578 		 * and must not be specified otherwise
1579 		 */
1580 		switch (keytype) {
1581 		case CKK_DES:
1582 		case CKK_DES2:
1583 		case CKK_DES3:
1584 			if (isValueLen)
1585 				return (CKR_TEMPLATE_INCONSISTENT);
1586 			break;
1587 		case CKK_GENERIC_SECRET:
1588 		case CKK_RC4:
1589 		case CKK_AES:
1590 		case CKK_BLOWFISH:
1591 			if (!isValueLen)
1592 				return (CKR_TEMPLATE_INCOMPLETE);
1593 			break;
1594 		default:
1595 			return (CKR_FUNCTION_NOT_SUPPORTED);
1596 		}
1597 		break;
1598 	default:
1599 		/* CKA_VALUE_LEN must not be specified */
1600 		if (isValueLen)
1601 			return (CKR_TEMPLATE_INCONSISTENT);
1602 		break;
1603 	}
1604 
1605 	return (CKR_OK);
1606 }
1607 
1608 CK_RV
1609 soft_unwrapkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
1610 		soft_object_t *unwrappingkey_p,
1611 		CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen,
1612 		CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount,
1613 		CK_OBJECT_HANDLE_PTR phKey)
1614 {
1615 	CK_RV			rv = CKR_OK;
1616 	CK_OBJECT_CLASS		new_obj_class = ~0UL;
1617 	int			i = 0;
1618 	soft_object_t		*new_objp = NULL;
1619 	boolean_t		persistent = B_FALSE;
1620 	CK_BYTE_PTR		plain_data = NULL;
1621 	CK_ULONG		plain_len = 0;
1622 	secret_key_obj_t	*sck = NULL;
1623 
1624 	/* Scan the attribute template for the object class. */
1625 	if (pTemplate != NULL && ulAttributeCount != 0) {
1626 		for (i = 0; i < ulAttributeCount; i++) {
1627 			if (pTemplate[i].type == CKA_CLASS) {
1628 				new_obj_class =
1629 				    *((CK_OBJECT_CLASS *)pTemplate[i].pValue);
1630 				break;
1631 			}
1632 		}
1633 		if (new_obj_class == ~0UL)
1634 			return (CKR_TEMPLATE_INCOMPLETE);
1635 	}
1636 
1637 	/*
1638 	 * Check if the mechanism is supported, and now that the new
1639 	 * object's class is known, the mechanism selected should be
1640 	 * capable of doing the unwrap.
1641 	 */
1642 	switch (pMechanism->mechanism) {
1643 	case CKM_RSA_PKCS:
1644 	case CKM_RSA_X_509:
1645 	case CKM_DES_ECB:
1646 	case CKM_DES3_ECB:
1647 	case CKM_AES_ECB:
1648 	case CKM_DES_CBC:
1649 	case CKM_DES3_CBC:
1650 	case CKM_AES_CBC:
1651 	case CKM_BLOWFISH_CBC:
1652 		if (new_obj_class != CKO_SECRET_KEY)
1653 			return (CKR_MECHANISM_INVALID);
1654 		break;
1655 	case CKM_DES_CBC_PAD:
1656 	case CKM_DES3_CBC_PAD:
1657 	case CKM_AES_CBC_PAD:
1658 		if (new_obj_class != CKO_SECRET_KEY && new_obj_class !=
1659 		    CKO_PRIVATE_KEY)
1660 			return (CKR_MECHANISM_INVALID);
1661 		break;
1662 	default:
1663 		return (CKR_MECHANISM_INVALID);
1664 	}
1665 
1666 	/* Create a new object based on the attribute template. */
1667 	rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
1668 	    (CK_ULONG *)&new_objp, session_p, (CK_OBJECT_CLASS)~0UL,
1669 	    (CK_KEY_TYPE)~0UL, 0, SOFT_UNWRAP_KEY, B_FALSE);
1670 	if (rv != CKR_OK)
1671 		return (rv);
1672 
1673 	/*
1674 	 * New key will have CKA_ALWAYS_SENSITIVE and CKA_NEVER_EXTRACTABLE
1675 	 * both set to FALSE.  CKA_EXTRACTABLE will be set _by_default_ to
1676 	 * true -- leaving the possibility that it may be set FALSE by the
1677 	 * supplied attribute template.  If the precise template cannot be
1678 	 * supported, unwrap fails.  PKCS#11 spec, Sec. 11.14, C_UnwrapKey.
1679 	 *
1680 	 * Therefore, check the new object's NEVER_EXTRACTABLE_BOOL_ON and
1681 	 * ALWAYS_SENSITVE_BOOL_ON; if they are TRUE, the template must
1682 	 * have supplied them and therefore we cannot honor the unwrap.
1683 	 */
1684 	if ((new_objp->bool_attr_mask & NEVER_EXTRACTABLE_BOOL_ON) ||
1685 	    (new_objp->bool_attr_mask & ALWAYS_SENSITIVE_BOOL_ON)) {
1686 		rv = CKR_TEMPLATE_INCONSISTENT;
1687 		goto cleanup_unwrap;
1688 	}
1689 
1690 	rv = soft_decrypt_init(session_p, pMechanism, unwrappingkey_p);
1691 	if (rv != CKR_OK)
1692 		goto cleanup_unwrap;
1693 
1694 	/* First get the length of the plain data */
1695 	rv = soft_decrypt(session_p, pWrappedKey, ulWrappedKeyLen, NULL,
1696 	    &plain_len);
1697 	if (rv != CKR_OK)
1698 		goto cleanup_unwrap;
1699 
1700 	/* Allocate space for the unwrapped data */
1701 	if ((plain_data = malloc(plain_len)) == NULL) {
1702 		rv = CKR_HOST_MEMORY;
1703 		goto cleanup_unwrap;
1704 	}
1705 	(void) memset(plain_data, 0x0, plain_len);
1706 
1707 	/* Perform actual decryption into the allocated space. */
1708 	rv = soft_decrypt(session_p, pWrappedKey, ulWrappedKeyLen, plain_data,
1709 	    &plain_len);
1710 	if (rv != CKR_OK)
1711 		goto cleanup_unwrap;
1712 
1713 	if (new_objp->class == CKO_SECRET_KEY) {
1714 		/*
1715 		 * Since no ASN.1 encoding is done for secret keys, check for
1716 		 * appropriateness and copy decrypted buffer to the key object.
1717 		 */
1718 
1719 		/* Check keytype and mechtype don't conflict with valuelen */
1720 		rv = soft_unwrap_secret_len_check(new_objp->key_type,
1721 		    pMechanism->mechanism, pTemplate, ulAttributeCount);
1722 		if (rv != CKR_OK)
1723 			goto cleanup_unwrap;
1724 
1725 		/*
1726 		 * Allocate the secret key structure if not already there;
1727 		 * it will exist for variable length keys since CKA_VALUE_LEN
1728 		 * is specified and saved, but not for fixed length keys.
1729 		 */
1730 		if (OBJ_SEC(new_objp) == NULL) {
1731 			if ((sck = calloc(1, sizeof (secret_key_obj_t))) ==
1732 			    NULL) {
1733 				rv = CKR_HOST_MEMORY;
1734 				goto cleanup_unwrap;
1735 			}
1736 			OBJ_SEC(new_objp) = sck;
1737 		}
1738 
1739 		switch (new_objp->key_type) {
1740 		/* Fixed length secret keys don't have CKA_VALUE_LEN */
1741 		case CKK_DES:
1742 			OBJ_SEC_VALUE_LEN(new_objp) = DES_KEYSIZE;
1743 			break;
1744 		case CKK_DES2:
1745 			OBJ_SEC_VALUE_LEN(new_objp) = DES2_KEYSIZE;
1746 			break;
1747 		case CKK_DES3:
1748 			OBJ_SEC_VALUE_LEN(new_objp) = DES3_KEYSIZE;
1749 			break;
1750 
1751 		/*
1752 		 * Variable length secret keys.  CKA_VALUE_LEN must be
1753 		 * provided by the template when mech is *_ECB or *_CBC, and
1754 		 * should already have been set during soft_gen_keyobject().
1755 		 * Otherwise we don't need CKA_VALUE_LEN.
1756 		 */
1757 		case CKK_GENERIC_SECRET:
1758 		case CKK_RC4:
1759 		case CKK_AES:
1760 		case CKK_BLOWFISH:
1761 			break;
1762 		default:
1763 			rv = CKR_WRAPPED_KEY_INVALID;
1764 			goto cleanup_unwrap;
1765 		};
1766 
1767 		if (OBJ_SEC_VALUE_LEN(new_objp) == 0) {
1768 			/* No CKA_VALUE_LEN set so set it now and save data */
1769 			OBJ_SEC_VALUE_LEN(new_objp) = plain_len;
1770 			OBJ_SEC_VALUE(new_objp) = plain_data;
1771 		} else if (OBJ_SEC_VALUE_LEN(new_objp) == plain_len) {
1772 			/* No need to truncate, just save the data */
1773 			OBJ_SEC_VALUE(new_objp) = plain_data;
1774 		} else if (OBJ_SEC_VALUE_LEN(new_objp) > plain_len) {
1775 			/* Length can't be bigger than what was decrypted */
1776 			rv = CKR_WRAPPED_KEY_LEN_RANGE;
1777 			goto cleanup_unwrap;
1778 		} else {	/* betw 0 and plain_len, hence padded */
1779 			/* Truncate the data before saving. */
1780 			OBJ_SEC_VALUE(new_objp) = realloc(plain_data,
1781 			    OBJ_SEC_VALUE_LEN(new_objp));
1782 			if (OBJ_SEC_VALUE(new_objp) == NULL) {
1783 				rv = CKR_HOST_MEMORY;
1784 				goto cleanup_unwrap;
1785 			}
1786 		}
1787 	} else {
1788 		/* BER-decode the object to be unwrapped. */
1789 		rv = soft_asn1_to_object(new_objp, plain_data, plain_len);
1790 		if (rv != CKR_OK)
1791 			goto cleanup_unwrap;
1792 	}
1793 
1794 	/* If it needs to be persistent, write it to the keystore */
1795 	if (IS_TOKEN_OBJECT(new_objp)) {
1796 		persistent = B_TRUE;
1797 		rv = soft_put_object_to_keystore(new_objp);
1798 		if (rv != CKR_OK)
1799 			goto cleanup_unwrap;
1800 	}
1801 
1802 	if (new_objp->class != CKO_SECRET_KEY) {
1803 		/* Clear buffer before returning to memory pool. */
1804 		(void) memset(plain_data, 0x0, plain_len);
1805 		free(plain_data);
1806 	}
1807 
1808 	*phKey = (CK_OBJECT_HANDLE)new_objp;
1809 
1810 	return (CKR_OK);
1811 
1812 cleanup_unwrap:
1813 	/* The decrypted private key buffer must be freed explicitly. */
1814 	if ((new_objp->class != CKO_SECRET_KEY) && (plain_data != NULL)) {
1815 		/* Clear buffer before returning to memory pool. */
1816 		(void) memset(plain_data, 0x0, plain_len);
1817 		free(plain_data);
1818 	}
1819 
1820 	/* sck and new_objp are indirectly free()d inside these functions */
1821 	if (IS_TOKEN_OBJECT(new_objp))
1822 		soft_delete_token_object(new_objp, persistent, B_FALSE);
1823 	else
1824 		soft_delete_object(session_p, new_objp, B_FALSE);
1825 
1826 	return (rv);
1827 }
1828