9642 PKCS#11 softtoken should use explicit_bzero
[unleashed.git] / usr / src / lib / pkcs11 / pkcs11_softtoken / common / softKeysUtil.c
blobcb06623498879dfce731a4866853aa71a923a0e9
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
22 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright (c) 2018, Joyent, Inc.
27 #include <pthread.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <strings.h>
31 #include <sys/types.h>
32 #include <security/cryptoki.h>
33 #include <sys/crypto/common.h>
34 #include <aes_impl.h>
35 #include <blowfish_impl.h>
36 #include <des_impl.h>
37 #include <arcfour.h>
38 #include <cryptoutil.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 "softMAC.h"
47 #include "softOps.h"
48 #include "softKeys.h"
49 #include "softKeystore.h"
50 #include "softSSL.h"
51 #include "softASN1.h"
54 #define local_min(a, b) ((a) < (b) ? (a) : (b))
56 static CK_RV
57 soft_pkcs12_pbe(soft_session_t *, CK_MECHANISM_PTR, soft_object_t *);
60 * Create a temporary key object struct by filling up its template attributes.
62 CK_RV
63 soft_gen_keyobject(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
64 CK_ULONG *objecthandle_p, soft_session_t *sp,
65 CK_OBJECT_CLASS class, CK_KEY_TYPE key_type, CK_ULONG keylen, CK_ULONG mode,
66 boolean_t internal)
69 CK_RV rv;
70 soft_object_t *new_objp = NULL;
72 new_objp = calloc(1, sizeof (soft_object_t));
73 if (new_objp == NULL) {
74 return (CKR_HOST_MEMORY);
77 new_objp->extra_attrlistp = NULL;
80 * Validate attribute template and fill in the attributes
81 * in the soft_object_t.
83 rv = soft_build_key(pTemplate, ulCount, new_objp, class, key_type,
84 keylen, mode);
85 if (rv != CKR_OK) {
86 goto fail_cleanup1;
90 * If generating a key is an internal request (i.e. not a C_XXX
91 * API request), then skip the following checks.
93 if (!internal) {
94 rv = soft_pin_expired_check(new_objp);
95 if (rv != CKR_OK) {
96 goto fail_cleanup2;
99 rv = soft_object_write_access_check(sp, new_objp);
100 if (rv != CKR_OK) {
101 goto fail_cleanup2;
105 /* Initialize the rest of stuffs in soft_object_t. */
106 (void) pthread_mutex_init(&new_objp->object_mutex, NULL);
107 new_objp->magic_marker = SOFTTOKEN_OBJECT_MAGIC;
109 /* Write the new token object to the keystore */
110 if (IS_TOKEN_OBJECT(new_objp)) {
111 new_objp->version = 1;
112 new_objp->session_handle = (CK_SESSION_HANDLE)NULL;
113 soft_add_token_object_to_slot(new_objp);
115 * Type casting the address of an object struct to
116 * an object handle.
118 *objecthandle_p = (CK_ULONG)new_objp;
120 return (CKR_OK);
123 new_objp->session_handle = (CK_SESSION_HANDLE)sp;
125 /* Add the new object to the session's object list. */
126 soft_add_object_to_session(new_objp, sp);
128 /* Type casting the address of an object struct to an object handle. */
129 *objecthandle_p = (CK_ULONG)new_objp;
131 return (CKR_OK);
133 fail_cleanup2:
135 * When any error occurs after soft_build_key(), we will need to
136 * clean up the memory allocated by the soft_build_key().
138 soft_cleanup_object(new_objp);
140 fail_cleanup1:
141 if (new_objp) {
143 * The storage allocated inside of this object should have
144 * been cleaned up by the soft_build_key() if it failed.
145 * Therefore, we can safely free the object.
147 free(new_objp);
150 return (rv);
153 CK_RV
154 soft_genkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
155 CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey)
158 CK_RV rv = CKR_OK;
159 soft_object_t *secret_key;
160 CK_KEY_TYPE key_type;
161 CK_ULONG keylen = 0;
162 CK_ULONG i;
163 int des_strength = 0;
164 int retry = 0;
165 int keyfound = 0;
166 boolean_t is_ssl_mech = B_FALSE;
168 switch (pMechanism->mechanism) {
169 case CKM_DES_KEY_GEN:
170 key_type = CKK_DES;
171 break;
173 case CKM_DES2_KEY_GEN:
174 key_type = CKK_DES2;
175 break;
177 case CKM_DES3_KEY_GEN:
178 key_type = CKK_DES3;
179 break;
181 case CKM_AES_KEY_GEN:
182 key_type = CKK_AES;
183 break;
185 case CKM_BLOWFISH_KEY_GEN:
186 key_type = CKK_BLOWFISH;
187 break;
189 case CKM_RC4_KEY_GEN:
190 key_type = CKK_RC4;
191 break;
193 case CKM_SSL3_PRE_MASTER_KEY_GEN:
194 case CKM_TLS_PRE_MASTER_KEY_GEN:
195 if (pMechanism->pParameter == NULL ||
196 pMechanism->ulParameterLen != sizeof (CK_VERSION))
197 return (CKR_TEMPLATE_INCOMPLETE);
198 is_ssl_mech = B_TRUE;
199 key_type = CKK_GENERIC_SECRET;
200 keylen = 48;
201 break;
203 case CKM_PKCS5_PBKD2:
204 keyfound = 0;
205 for (i = 0; i < ulCount && !keyfound; i++) {
206 if (pTemplate[i].type == CKA_KEY_TYPE &&
207 pTemplate[i].pValue != NULL) {
208 key_type = *((CK_KEY_TYPE*)pTemplate[i].pValue);
209 keyfound = 1;
212 if (!keyfound)
213 return (CKR_TEMPLATE_INCOMPLETE);
215 * Make sure that parameters were given for this
216 * mechanism.
218 if (pMechanism->pParameter == NULL ||
219 pMechanism->ulParameterLen !=
220 sizeof (CK_PKCS5_PBKD2_PARAMS))
221 return (CKR_TEMPLATE_INCOMPLETE);
222 break;
224 case CKM_PBE_SHA1_RC4_128:
225 keyfound = 0;
226 for (i = 0; i < ulCount; i++) {
227 if (pTemplate[i].type == CKA_KEY_TYPE &&
228 pTemplate[i].pValue != NULL) {
229 key_type = *((CK_KEY_TYPE*)pTemplate[i].pValue);
230 keyfound = 1;
232 if (pTemplate[i].type == CKA_VALUE_LEN &&
233 pTemplate[i].pValue != NULL) {
234 keylen = *((CK_ULONG*)pTemplate[i].pValue);
237 /* If a keytype was specified, it had better be CKK_RC4 */
238 if (keyfound && key_type != CKK_RC4)
239 return (CKR_TEMPLATE_INCONSISTENT);
240 else if (!keyfound)
241 key_type = CKK_RC4;
243 /* If key length was specified, it better be 16 bytes */
244 if (keylen != 0 && keylen != 16)
245 return (CKR_TEMPLATE_INCONSISTENT);
248 * Make sure that parameters were given for this
249 * mechanism.
251 if (pMechanism->pParameter == NULL ||
252 pMechanism->ulParameterLen !=
253 sizeof (CK_PBE_PARAMS))
254 return (CKR_TEMPLATE_INCOMPLETE);
255 break;
256 default:
257 return (CKR_MECHANISM_INVALID);
260 /* Create a new object for secret key. */
261 rv = soft_gen_keyobject(pTemplate, ulCount, phKey, session_p,
262 CKO_SECRET_KEY, key_type, keylen, SOFT_GEN_KEY, B_FALSE);
264 if (rv != CKR_OK) {
265 return (rv);
268 /* Obtain the secret object pointer. */
269 secret_key = (soft_object_t *)*phKey;
271 switch (pMechanism->mechanism) {
272 case CKM_DES_KEY_GEN:
274 * Set up key value len since it is not a required
275 * attribute for C_GenerateKey.
277 keylen = OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
278 des_strength = DES;
279 break;
281 case CKM_DES2_KEY_GEN:
283 * Set up key value len since it is not a required
284 * attribute for C_GenerateKey.
286 keylen = OBJ_SEC_VALUE_LEN(secret_key) = DES2_KEYSIZE;
287 des_strength = DES2;
288 break;
290 case CKM_DES3_KEY_GEN:
292 * Set up key value len since it is not a required
293 * attribute for C_GenerateKey.
295 keylen = OBJ_SEC_VALUE_LEN(secret_key) = DES3_KEYSIZE;
296 des_strength = DES3;
297 break;
299 case CKM_SSL3_PRE_MASTER_KEY_GEN:
300 case CKM_TLS_PRE_MASTER_KEY_GEN:
301 secret_key->bool_attr_mask |= DERIVE_BOOL_ON;
302 /* FALLTHRU */
304 case CKM_AES_KEY_GEN:
305 case CKM_BLOWFISH_KEY_GEN:
306 case CKM_PBE_SHA1_RC4_128:
307 case CKM_RC4_KEY_GEN:
308 keylen = OBJ_SEC_VALUE_LEN(secret_key);
309 break;
311 case CKM_PKCS5_PBKD2:
313 * PKCS#11 does not allow one to specify key
314 * sizes for DES and 3DES, so we must set it here
315 * when using PBKD2 algorithms.
317 if (key_type == CKK_DES) {
318 OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
319 des_strength = DES;
320 } else if (key_type == CKK_DES3) {
321 OBJ_SEC_VALUE_LEN(secret_key) = DES3_KEYSIZE;
322 des_strength = DES3;
325 keylen = OBJ_SEC_VALUE_LEN(secret_key);
326 break;
329 if ((OBJ_SEC_VALUE(secret_key) = malloc(keylen)) == NULL) {
330 if (IS_TOKEN_OBJECT(secret_key))
331 soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
332 else
333 soft_delete_object(session_p, secret_key,
334 B_FALSE, B_FALSE);
336 return (CKR_HOST_MEMORY);
338 switch (pMechanism->mechanism) {
339 case CKM_PBE_SHA1_RC4_128:
341 * Use the PBE algorithm described in PKCS#11 section
342 * 12.33 to derive the key.
344 rv = soft_pkcs12_pbe(session_p, pMechanism, secret_key);
345 break;
346 case CKM_PKCS5_PBKD2:
347 /* Generate keys using PKCS#5 PBKD2 algorithm */
348 rv = soft_generate_pkcs5_pbkdf2_key(session_p, pMechanism,
349 secret_key);
350 if (rv == CKR_OK && des_strength > 0) {
351 /* Perform weak key checking for DES and DES3. */
352 if (des_keycheck(OBJ_SEC_VALUE(secret_key),
353 des_strength, OBJ_SEC_VALUE(secret_key)) ==
354 B_FALSE) {
355 /* We got a weak secret key. */
356 rv = CKR_FUNCTION_FAILED;
359 break;
360 default:
361 do {
362 /* If this fails, bail out */
363 rv = CKR_OK;
364 if (pkcs11_get_urandom(
365 OBJ_SEC_VALUE(secret_key), keylen) < 0) {
366 rv = CKR_DEVICE_ERROR;
367 break;
370 /* Perform weak key checking for DES and DES3. */
371 if (des_strength > 0) {
372 rv = CKR_OK;
373 if (des_keycheck(OBJ_SEC_VALUE(secret_key),
374 des_strength, OBJ_SEC_VALUE(secret_key)) ==
375 B_FALSE) {
376 /* We got a weak key, retry! */
377 retry++;
378 rv = CKR_FUNCTION_FAILED;
382 * Copy over the SSL client version For SSL mechs
383 * The first two bytes of the key is the version
385 if (is_ssl_mech)
386 bcopy(pMechanism->pParameter,
387 OBJ_SEC_VALUE(secret_key),
388 sizeof (CK_VERSION));
390 } while (rv != CKR_OK && retry < KEYGEN_RETRY);
391 if (retry == KEYGEN_RETRY)
392 rv = CKR_FUNCTION_FAILED;
393 break;
396 if (rv != CKR_OK)
397 if (IS_TOKEN_OBJECT(secret_key))
398 soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
399 else
400 soft_delete_object(session_p, secret_key,
401 B_FALSE, B_FALSE);
403 if (IS_TOKEN_OBJECT(secret_key)) {
405 * All the info has been filled, so we can write to
406 * keystore now.
408 rv = soft_put_object_to_keystore(secret_key);
409 if (rv != CKR_OK)
410 soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
413 return (rv);
416 CK_RV
417 soft_genkey_pair(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
418 CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicAttrCount,
419 CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateAttrCount,
420 CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey)
423 CK_RV rv;
424 soft_object_t *public_key, *private_key;
425 CK_KEY_TYPE key_type;
427 switch (pMechanism->mechanism) {
429 case CKM_RSA_PKCS_KEY_PAIR_GEN:
430 key_type = CKK_RSA;
431 break;
433 case CKM_DSA_KEY_PAIR_GEN:
434 key_type = CKK_DSA;
435 break;
437 case CKM_DH_PKCS_KEY_PAIR_GEN:
438 key_type = CKK_DH;
439 break;
441 case CKM_EC_KEY_PAIR_GEN:
442 key_type = CKK_EC;
443 break;
445 default:
446 return (CKR_MECHANISM_INVALID);
449 /* Create a new object for public key. */
450 rv = soft_gen_keyobject(pPublicKeyTemplate, ulPublicAttrCount,
451 phPublicKey, session_p, CKO_PUBLIC_KEY, key_type, 0,
452 SOFT_GEN_KEY, B_FALSE);
454 if (rv != CKR_OK) {
455 return (rv);
458 /* Obtain the public object pointer. */
459 public_key = (soft_object_t *)*phPublicKey;
461 /* Create a new object for private key. */
462 rv = soft_gen_keyobject(pPrivateKeyTemplate, ulPrivateAttrCount,
463 phPrivateKey, session_p, CKO_PRIVATE_KEY, key_type, 0,
464 SOFT_GEN_KEY, B_FALSE);
466 if (rv != CKR_OK) {
468 * Both public key and private key must be successful.
470 if (IS_TOKEN_OBJECT(public_key))
471 soft_delete_token_object(public_key, B_FALSE, B_FALSE);
472 else
473 soft_delete_object(session_p, public_key,
474 B_FALSE, B_FALSE);
475 return (rv);
478 /* Obtain the private object pointer. */
479 private_key = (soft_object_t *)*phPrivateKey;
482 * At this point, both public key and private key objects
483 * are settled with the application specified attributes.
484 * We are ready to generate the rest of key attributes based
485 * on the existing attributes.
488 switch (key_type) {
489 case CKK_RSA:
490 rv = soft_rsa_genkey_pair(public_key, private_key);
491 break;
493 case CKK_DSA:
494 rv = soft_dsa_genkey_pair(public_key, private_key);
495 break;
497 case CKK_DH:
498 rv = soft_dh_genkey_pair(public_key, private_key);
499 private_key->bool_attr_mask |= DERIVE_BOOL_ON;
500 break;
501 case CKK_EC:
502 rv = soft_ec_genkey_pair(public_key, private_key);
503 private_key->bool_attr_mask |= DERIVE_BOOL_ON;
504 break;
507 if (rv != CKR_OK) {
508 if (IS_TOKEN_OBJECT(public_key)) {
509 soft_delete_token_object(public_key, B_FALSE, B_FALSE);
510 soft_delete_token_object(private_key, B_FALSE, B_FALSE);
511 } else {
512 soft_delete_object(session_p, public_key,
513 B_FALSE, B_FALSE);
514 soft_delete_object(session_p, private_key,
515 B_FALSE, B_FALSE);
517 return (rv);
520 if (IS_TOKEN_OBJECT(public_key)) {
522 * All the info has been filled, so we can write to
523 * keystore now.
525 rv = soft_put_object_to_keystore(public_key);
526 if (rv != CKR_OK) {
527 soft_delete_token_object(public_key, B_FALSE, B_FALSE);
528 soft_delete_token_object(private_key, B_FALSE, B_FALSE);
529 return (rv);
533 if (IS_TOKEN_OBJECT(private_key)) {
534 rv = soft_put_object_to_keystore(private_key);
535 if (rv != CKR_OK) {
537 * We also need to delete the public token object
538 * from keystore.
540 soft_delete_token_object(public_key, B_TRUE, B_FALSE);
541 soft_delete_token_object(private_key, B_FALSE, B_FALSE);
545 return (rv);
549 CK_RV
550 soft_key_derive_check_length(soft_object_t *secret_key, CK_ULONG max_keylen)
553 switch (secret_key->key_type) {
554 case CKK_GENERIC_SECRET:
555 if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
556 OBJ_SEC_VALUE_LEN(secret_key) = max_keylen;
557 return (CKR_OK);
558 } else if (OBJ_SEC_VALUE_LEN(secret_key) > max_keylen) {
559 return (CKR_ATTRIBUTE_VALUE_INVALID);
561 break;
562 case CKK_RC4:
563 case CKK_AES:
564 case CKK_BLOWFISH:
565 if ((OBJ_SEC_VALUE_LEN(secret_key) == 0) ||
566 (OBJ_SEC_VALUE_LEN(secret_key) > max_keylen)) {
567 /* RC4 and AES has variable key length */
568 return (CKR_ATTRIBUTE_VALUE_INVALID);
570 break;
571 case CKK_DES:
572 if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
573 /* DES has a well-defined length */
574 OBJ_SEC_VALUE_LEN(secret_key) = DES_KEYSIZE;
575 return (CKR_OK);
576 } else if (OBJ_SEC_VALUE_LEN(secret_key) != DES_KEYSIZE) {
577 return (CKR_ATTRIBUTE_VALUE_INVALID);
579 break;
580 case CKK_DES2:
581 if (OBJ_SEC_VALUE_LEN(secret_key) == 0) {
582 /* DES2 has a well-defined length */
583 OBJ_SEC_VALUE_LEN(secret_key) = DES2_KEYSIZE;
584 return (CKR_OK);
585 } else if (OBJ_SEC_VALUE_LEN(secret_key) != DES2_KEYSIZE) {
586 return (CKR_ATTRIBUTE_VALUE_INVALID);
588 break;
590 default:
591 return (CKR_MECHANISM_INVALID);
594 return (CKR_OK);
598 * PKCS#11 (12.33) says that v = 512 bits (64 bytes) for SHA1
599 * PBE methods.
601 #define PKCS12_BUFFER_SIZE 64
603 * PKCS#12 defines 3 different ID bytes to be used for
604 * deriving keys for different operations.
606 #define PBE_ID_ENCRYPT 1
607 #define PBE_ID_IV 2
608 #define PBE_ID_MAC 3
609 #define PBE_CEIL(a, b) (((a)/(b)) + (((a)%(b)) > 0))
611 static CK_RV
612 soft_pkcs12_pbe(soft_session_t *session_p,
613 CK_MECHANISM_PTR pMechanism, soft_object_t *derived_key)
615 CK_RV rv = CKR_OK;
616 CK_PBE_PARAMS *params = pMechanism->pParameter;
617 CK_ULONG c, i, j, k;
618 CK_ULONG hashSize;
619 CK_ULONG buffSize;
621 * Terse variable names are used to make following
622 * the PKCS#12 spec easier.
624 CK_BYTE *A = NULL;
625 CK_BYTE *Ai = NULL;
626 CK_BYTE *B = NULL;
627 CK_BYTE *D = NULL;
628 CK_BYTE *I = NULL, *S, *P;
629 CK_BYTE *keybuf = NULL;
630 CK_ULONG Alen, Ilen, Slen, Plen, AiLen, Blen, Dlen;
631 CK_ULONG keysize = OBJ_SEC_VALUE_LEN(derived_key);
632 CK_MECHANISM digest_mech;
634 /* U = hash function output bits */
635 if (pMechanism->mechanism == CKM_PBE_SHA1_RC4_128) {
636 hashSize = SHA1_HASH_SIZE;
637 buffSize = PKCS12_BUFFER_SIZE;
638 digest_mech.mechanism = CKM_SHA_1;
639 digest_mech.pParameter = NULL;
640 digest_mech.ulParameterLen = 0;
641 } else {
642 /* we only support 1 PBE mech for now */
643 return (CKR_MECHANISM_INVALID);
645 keybuf = OBJ_SEC_VALUE(derived_key);
647 Blen = Dlen = buffSize;
648 D = (CK_BYTE *)malloc(Dlen);
649 if (D == NULL) {
650 rv = CKR_HOST_MEMORY;
651 goto cleanup;
654 B = (CK_BYTE *)malloc(Blen);
655 if (B == NULL) {
656 rv = CKR_HOST_MEMORY;
657 goto cleanup;
661 * Initialize some values and create some buffers
662 * that we need later.
664 * Slen = buffSize * CEIL(SaltLength/buffSize)
666 Slen = buffSize * PBE_CEIL(params->ulSaltLen, buffSize);
669 * Plen = buffSize * CEIL(PasswordLength/buffSize)
671 Plen = buffSize * PBE_CEIL(params->ulPasswordLen, buffSize);
674 * From step 4: I = S + P, so: Ilen = Slen + Plen
676 Ilen = Slen + Plen;
677 I = (CK_BYTE *)malloc(Ilen);
678 if (I == NULL) {
679 rv = CKR_HOST_MEMORY;
680 goto cleanup;
683 S = I;
684 P = I + Slen;
687 * Step 1.
688 * We are only interested in deriving keys for encrypt/decrypt
689 * for now, so construct the "D"iversifier accordingly.
691 (void) memset(D, PBE_ID_ENCRYPT, Dlen);
694 * Step 2.
695 * Concatenate copies of the salt together to make S.
697 for (i = 0; i < Slen; i += params->ulSaltLen) {
698 (void) memcpy(S+i, params->pSalt,
699 ((Slen - i) > params->ulSaltLen ?
700 params->ulSaltLen : (Slen - i)));
704 * Step 3.
705 * Concatenate copies of the password together to make
706 * a string P.
708 for (i = 0; i < Plen; i += params->ulPasswordLen) {
709 (void) memcpy(P+i, params->pPassword,
710 ((Plen - i) > params->ulPasswordLen ?
711 params->ulPasswordLen : (Plen - i)));
715 * Step 4.
716 * I = S+P - this is now done because S and P are
717 * pointers into I.
719 * Step 5.
720 * c= CEIL[n/u]
721 * where n = pseudorandom bits of output desired.
723 c = PBE_CEIL(keysize, hashSize);
726 * Step 6.
728 Alen = c * hashSize;
729 A = (CK_BYTE *)malloc(Alen);
730 if (A == NULL) {
731 rv = CKR_HOST_MEMORY;
732 goto cleanup;
734 AiLen = hashSize;
735 Ai = (CK_BYTE *)malloc(AiLen);
736 if (Ai == NULL) {
737 rv = CKR_HOST_MEMORY;
738 goto cleanup;
742 * Step 6a.
743 * Ai = Hr(D+I)
745 for (i = 0; i < c; i++) {
746 (void) pthread_mutex_lock(&session_p->session_mutex);
748 if (session_p->sign.flags & CRYPTO_OPERATION_ACTIVE) {
749 (void) pthread_mutex_unlock(&session_p->session_mutex);
750 rv = CKR_OPERATION_ACTIVE;
751 goto cleanup;
753 session_p->sign.flags |= CRYPTO_OPERATION_ACTIVE;
754 (void) pthread_mutex_unlock(&session_p->session_mutex);
756 for (j = 0; j < params->ulIteration; j++) {
757 rv = soft_digest_init(session_p, &digest_mech);
758 if (rv != CKR_OK)
759 goto digest_done;
761 if (j == 0) {
762 rv = soft_digest_update(session_p, D, Dlen);
763 if (rv != CKR_OK)
764 goto digest_done;
766 rv = soft_digest_update(session_p, I, Ilen);
767 } else {
768 rv = soft_digest_update(session_p, Ai, AiLen);
770 if (rv != CKR_OK)
771 goto digest_done;
773 rv = soft_digest_final(session_p, Ai, &AiLen);
774 if (rv != CKR_OK)
775 goto digest_done;
777 digest_done:
778 (void) pthread_mutex_lock(&session_p->session_mutex);
779 session_p->sign.flags &= ~CRYPTO_OPERATION_ACTIVE;
780 (void) pthread_mutex_unlock(&session_p->session_mutex);
782 if (rv != CKR_OK)
783 goto cleanup;
785 * Step 6b.
786 * Concatenate Ai to make B
788 for (j = 0; j < Blen; j += hashSize) {
789 (void) memcpy(B+j, Ai, ((Blen - j > hashSize) ?
790 hashSize : Blen - j));
794 * Step 6c.
796 k = Ilen / Blen;
797 for (j = 0; j < k; j++) {
798 uchar_t idx;
799 CK_ULONG m, q = 1, cbit = 0;
801 for (m = Blen - 1; m >= (CK_ULONG)0; m--, q = 0) {
802 idx = m + j*Blen;
804 q += (CK_ULONG)I[idx] + (CK_ULONG)B[m];
805 q += cbit;
806 I[idx] = (CK_BYTE)(q & 0xff);
807 cbit = (q > 0xff);
812 * Step 7.
813 * A += Ai
815 (void) memcpy(A + i*hashSize, Ai, AiLen);
819 * Step 8.
820 * The final output of this process is the A buffer
822 (void) memcpy(keybuf, A, keysize);
824 cleanup:
825 freezero(A, Alen);
826 freezero(Ai, AiLen);
827 freezero(B, Blen);
828 freezero(D, Dlen);
829 freezero(I, Ilen);
830 return (rv);
833 CK_RV
834 soft_derivekey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
835 soft_object_t *basekey_p, CK_ATTRIBUTE_PTR pTemplate,
836 CK_ULONG ulAttributeCount, CK_OBJECT_HANDLE_PTR phKey)
839 CK_RV rv = CKR_OK;
840 soft_object_t *secret_key;
841 CK_MECHANISM digest_mech;
842 CK_BYTE hash[SHA512_DIGEST_LENGTH]; /* space enough for all mechs */
843 CK_ULONG hash_len = SHA512_DIGEST_LENGTH;
844 CK_ULONG secret_key_len;
845 CK_ULONG hash_size;
847 switch (pMechanism->mechanism) {
848 case CKM_DH_PKCS_DERIVE:
850 * Create a new object for secret key. The key type should
851 * be provided in the template.
853 rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
854 phKey, session_p, CKO_SECRET_KEY, (CK_KEY_TYPE)~0UL, 0,
855 SOFT_DERIVE_KEY_DH, B_FALSE);
857 if (rv != CKR_OK) {
858 return (rv);
861 /* Obtain the secret object pointer. */
862 secret_key = (soft_object_t *)*phKey;
864 rv = soft_dh_key_derive(basekey_p, secret_key,
865 (CK_BYTE *)pMechanism->pParameter,
866 pMechanism->ulParameterLen);
868 if (rv != CKR_OK) {
869 if (IS_TOKEN_OBJECT(secret_key))
870 soft_delete_token_object(secret_key, B_FALSE,
871 B_FALSE);
872 else
873 soft_delete_object(session_p, secret_key,
874 B_FALSE, B_FALSE);
875 return (rv);
878 break;
880 case CKM_ECDH1_DERIVE:
882 * Create a new object for secret key. The key type should
883 * be provided in the template.
885 rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
886 phKey, session_p, CKO_SECRET_KEY, (CK_KEY_TYPE)~0UL, 0,
887 SOFT_DERIVE_KEY_DH, B_FALSE);
889 if (rv != CKR_OK) {
890 return (rv);
893 /* Obtain the secret object pointer. */
894 secret_key = (soft_object_t *)*phKey;
896 rv = soft_ec_key_derive(basekey_p, secret_key,
897 (CK_BYTE *)pMechanism->pParameter,
898 pMechanism->ulParameterLen);
900 if (rv != CKR_OK) {
901 if (IS_TOKEN_OBJECT(secret_key))
902 soft_delete_token_object(secret_key, B_FALSE,
903 B_FALSE);
904 else
905 soft_delete_object(session_p, secret_key,
906 B_FALSE, B_FALSE);
907 return (rv);
910 break;
912 case CKM_SHA1_KEY_DERIVATION:
913 hash_size = SHA1_HASH_SIZE;
914 digest_mech.mechanism = CKM_SHA_1;
915 goto common;
917 case CKM_MD5_KEY_DERIVATION:
918 hash_size = MD5_HASH_SIZE;
919 digest_mech.mechanism = CKM_MD5;
920 goto common;
922 case CKM_SHA256_KEY_DERIVATION:
923 hash_size = SHA256_DIGEST_LENGTH;
924 digest_mech.mechanism = CKM_SHA256;
925 goto common;
927 case CKM_SHA384_KEY_DERIVATION:
928 hash_size = SHA384_DIGEST_LENGTH;
929 digest_mech.mechanism = CKM_SHA384;
930 goto common;
932 case CKM_SHA512_KEY_DERIVATION:
933 hash_size = SHA512_DIGEST_LENGTH;
934 digest_mech.mechanism = CKM_SHA512;
935 goto common;
937 common:
939 * Create a new object for secret key. The key type is optional
940 * to be provided in the template. If it is not specified in
941 * the template, the default is CKK_GENERIC_SECRET.
943 rv = soft_gen_keyobject(pTemplate, ulAttributeCount,
944 phKey, session_p, CKO_SECRET_KEY,
945 (CK_KEY_TYPE)CKK_GENERIC_SECRET, 0,
946 SOFT_DERIVE_KEY_OTHER, B_FALSE);
948 if (rv != CKR_OK) {
949 return (rv);
952 /* Obtain the secret object pointer. */
953 secret_key = (soft_object_t *)*phKey;
955 /* Validate the key type and key length */
956 rv = soft_key_derive_check_length(secret_key, hash_size);
957 if (rv != CKR_OK) {
958 if (IS_TOKEN_OBJECT(secret_key))
959 soft_delete_token_object(secret_key, B_FALSE,
960 B_FALSE);
961 else
962 soft_delete_object(session_p, secret_key,
963 B_FALSE, B_FALSE);
964 return (rv);
968 * Derive the secret key by digesting the value of another
969 * secret key (base key) with SHA-1 or MD5.
971 rv = soft_digest_init_internal(session_p, &digest_mech);
972 if (rv != CKR_OK) {
973 if (IS_TOKEN_OBJECT(secret_key))
974 soft_delete_token_object(secret_key, B_FALSE,
975 B_FALSE);
976 else
977 soft_delete_object(session_p, secret_key,
978 B_FALSE, B_FALSE);
979 return (rv);
982 rv = soft_digest(session_p, OBJ_SEC_VALUE(basekey_p),
983 OBJ_SEC_VALUE_LEN(basekey_p), hash, &hash_len);
985 (void) pthread_mutex_lock(&session_p->session_mutex);
986 /* soft_digest_common() has freed the digest context */
987 session_p->digest.flags = 0;
988 (void) pthread_mutex_unlock(&session_p->session_mutex);
990 if (rv != CKR_OK) {
991 if (IS_TOKEN_OBJECT(secret_key))
992 soft_delete_token_object(secret_key, B_FALSE,
993 B_FALSE);
994 else
995 soft_delete_object(session_p, secret_key,
996 B_FALSE, B_FALSE);
997 return (rv);
1000 secret_key_len = OBJ_SEC_VALUE_LEN(secret_key);
1002 if ((OBJ_SEC_VALUE(secret_key) = malloc(secret_key_len)) ==
1003 NULL) {
1004 if (IS_TOKEN_OBJECT(secret_key))
1005 soft_delete_token_object(secret_key, B_FALSE,
1006 B_FALSE);
1007 else
1008 soft_delete_object(session_p, secret_key,
1009 B_FALSE, B_FALSE);
1010 return (CKR_HOST_MEMORY);
1014 * The key produced by this mechanism will be of the
1015 * specified type and length.
1016 * The truncation removes extra bytes from the leading
1017 * of the digested key value.
1019 (void) memcpy(OBJ_SEC_VALUE(secret_key),
1020 (hash + hash_len - secret_key_len),
1021 secret_key_len);
1023 break;
1026 * The key sensitivity and extractability rules for the generated
1027 * keys will be enforced inside soft_ssl_master_key_derive() and
1028 * soft_ssl_key_and_mac_derive()
1030 case CKM_SSL3_MASTER_KEY_DERIVE:
1031 case CKM_SSL3_MASTER_KEY_DERIVE_DH:
1032 case CKM_TLS_MASTER_KEY_DERIVE:
1033 case CKM_TLS_MASTER_KEY_DERIVE_DH:
1034 if (phKey == NULL_PTR)
1035 return (CKR_ARGUMENTS_BAD);
1036 return (soft_ssl_master_key_derive(session_p, pMechanism,
1037 basekey_p, pTemplate, ulAttributeCount, phKey));
1039 case CKM_SSL3_KEY_AND_MAC_DERIVE:
1040 case CKM_TLS_KEY_AND_MAC_DERIVE:
1041 return (soft_ssl_key_and_mac_derive(session_p, pMechanism,
1042 basekey_p, pTemplate, ulAttributeCount));
1044 case CKM_TLS_PRF:
1045 if (pMechanism->pParameter == NULL ||
1046 pMechanism->ulParameterLen != sizeof (CK_TLS_PRF_PARAMS) ||
1047 phKey != NULL)
1048 return (CKR_ARGUMENTS_BAD);
1050 if (pTemplate != NULL)
1051 return (CKR_TEMPLATE_INCONSISTENT);
1053 return (derive_tls_prf(
1054 (CK_TLS_PRF_PARAMS_PTR)pMechanism->pParameter, basekey_p));
1056 default:
1057 return (CKR_MECHANISM_INVALID);
1060 soft_derive_enforce_flags(basekey_p, secret_key);
1062 if (IS_TOKEN_OBJECT(secret_key)) {
1064 * All the info has been filled, so we can write to
1065 * keystore now.
1067 rv = soft_put_object_to_keystore(secret_key);
1068 if (rv != CKR_OK)
1069 soft_delete_token_object(secret_key, B_FALSE, B_FALSE);
1072 return (rv);
1077 * Perform key derivation rules on key's sensitivity and extractability.
1079 void
1080 soft_derive_enforce_flags(soft_object_t *basekey, soft_object_t *newkey)
1083 boolean_t new_sensitive = B_FALSE;
1084 boolean_t new_extractable = B_FALSE;
1087 * The sensitive and extractable bits have been set when
1088 * the newkey was built.
1090 if (newkey->bool_attr_mask & SENSITIVE_BOOL_ON) {
1091 new_sensitive = B_TRUE;
1094 if (newkey->bool_attr_mask & EXTRACTABLE_BOOL_ON) {
1095 new_extractable = B_TRUE;
1098 /* Derive the CKA_ALWAYS_SENSITIVE flag */
1099 if (!basekey->bool_attr_mask & ALWAYS_SENSITIVE_BOOL_ON) {
1101 * If the base key has its CKA_ALWAYS_SENSITIVE set to
1102 * FALSE, then the derived key will as well.
1104 newkey->bool_attr_mask &= ~ALWAYS_SENSITIVE_BOOL_ON;
1105 } else {
1107 * If the base key has its CKA_ALWAYS_SENSITIVE set to TRUE,
1108 * then the derived key has the CKA_ALWAYS_SENSITIVE set to
1109 * the same value as its CKA_SENSITIVE;
1111 if (new_sensitive) {
1112 newkey->bool_attr_mask |= ALWAYS_SENSITIVE_BOOL_ON;
1113 } else {
1114 newkey->bool_attr_mask &= ~ALWAYS_SENSITIVE_BOOL_ON;
1118 /* Derive the CKA_NEVER_EXTRACTABLE flag */
1119 if (!basekey->bool_attr_mask & NEVER_EXTRACTABLE_BOOL_ON) {
1121 * If the base key has its CKA_NEVER_EXTRACTABLE set to
1122 * FALSE, then the derived key will as well.
1124 newkey->bool_attr_mask &= ~NEVER_EXTRACTABLE_BOOL_ON;
1125 } else {
1127 * If the base key has its CKA_NEVER_EXTRACTABLE set to TRUE,
1128 * then the derived key has the CKA_NEVER_EXTRACTABLE set to
1129 * the opposite value from its CKA_EXTRACTABLE;
1131 if (new_extractable) {
1132 newkey->bool_attr_mask &= ~NEVER_EXTRACTABLE_BOOL_ON;
1133 } else {
1134 newkey->bool_attr_mask |= NEVER_EXTRACTABLE_BOOL_ON;
1138 /* Set the CKA_LOCAL flag to false */
1139 newkey->bool_attr_mask &= ~LOCAL_BOOL_ON;
1144 * do_prf
1146 * This routine implements Step 3. of the PBKDF2 function
1147 * defined in PKCS#5 for generating derived keys from a
1148 * password.
1150 * Currently, PRF is always SHA_1_HMAC.
1152 static CK_RV
1153 do_prf(soft_session_t *session_p, CK_PKCS5_PBKD2_PARAMS_PTR params,
1154 soft_object_t *hmac_key, CK_BYTE *newsalt, CK_ULONG saltlen,
1155 CK_BYTE *blockdata, CK_ULONG blocklen)
1157 CK_RV rv = CKR_OK;
1158 CK_MECHANISM digest_mech = {CKM_SHA_1_HMAC, NULL, 0};
1159 CK_BYTE buffer[2][SHA1_HASH_SIZE];
1160 CK_ULONG hmac_outlen = SHA1_HASH_SIZE;
1161 CK_ULONG inlen;
1162 CK_BYTE *input, *output;
1163 CK_ULONG i, j;
1165 input = newsalt;
1166 inlen = saltlen;
1168 output = buffer[1];
1169 (void) pthread_mutex_lock(&session_p->session_mutex);
1171 if (session_p->sign.flags & CRYPTO_OPERATION_ACTIVE) {
1172 (void) pthread_mutex_unlock(&session_p->session_mutex);
1173 return (CKR_OPERATION_ACTIVE);
1175 session_p->sign.flags |= CRYPTO_OPERATION_ACTIVE;
1176 (void) pthread_mutex_unlock(&session_p->session_mutex);
1178 for (i = 0; i < params->iterations; i++) {
1180 * The key doesn't change, its always the
1181 * password iniitally given.
1183 rv = soft_sign_init(session_p, &digest_mech, hmac_key);
1185 if (rv != CKR_OK) {
1186 goto cleanup;
1189 /* Call PRF function (SHA1_HMAC for now). */
1190 rv = soft_sign(session_p, input, inlen, output, &hmac_outlen);
1192 if (rv != CKR_OK) {
1193 goto cleanup;
1196 * The first time, initialize the output buffer
1197 * with the HMAC signature.
1199 if (i == 0) {
1200 (void) memcpy(blockdata, output,
1201 local_min(blocklen, hmac_outlen));
1202 } else {
1204 * XOR the existing data with output from PRF.
1206 * Only XOR up to the length of the blockdata,
1207 * it may be less than a full hmac buffer when
1208 * the final block is being computed.
1210 for (j = 0; j < hmac_outlen && j < blocklen; j++)
1211 blockdata[j] ^= output[j];
1213 /* Output from previous PRF is input for next round */
1214 input = output;
1215 inlen = hmac_outlen;
1218 * Switch buffers to avoid overuse of memcpy.
1219 * Initially we used buffer[1], so after the end of
1220 * the first iteration (i==0), we switch to buffer[0]
1221 * and continue swapping with each iteration.
1223 output = buffer[i%2];
1225 cleanup:
1226 (void) pthread_mutex_lock(&session_p->session_mutex);
1227 session_p->sign.flags &= ~CRYPTO_OPERATION_ACTIVE;
1228 (void) pthread_mutex_unlock(&session_p->session_mutex);
1230 return (rv);
1233 static CK_RV
1234 soft_create_hmac_key(soft_session_t *session_p, CK_BYTE *passwd,
1235 CK_ULONG passwd_len, CK_OBJECT_HANDLE_PTR phKey)
1237 CK_RV rv = CKR_OK;
1238 CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
1239 CK_KEY_TYPE keytype = CKK_GENERIC_SECRET;
1240 CK_BBOOL True = TRUE;
1241 CK_ATTRIBUTE keytemplate[4];
1243 * We must initialize each template member individually
1244 * because at the time of initial coding for ON10, the
1245 * compiler was using the "-xc99=%none" option
1246 * which prevents us from being able to declare the whole
1247 * template in place as usual.
1249 keytemplate[0].type = CKA_CLASS;
1250 keytemplate[0].pValue = &keyclass;
1251 keytemplate[0].ulValueLen = sizeof (keyclass);
1253 keytemplate[1].type = CKA_KEY_TYPE;
1254 keytemplate[1].pValue = &keytype;
1255 keytemplate[1].ulValueLen = sizeof (keytype);
1257 keytemplate[2].type = CKA_SIGN;
1258 keytemplate[2].pValue = &True;
1259 keytemplate[2].ulValueLen = sizeof (True);
1261 keytemplate[3].type = CKA_VALUE;
1262 keytemplate[3].pValue = passwd;
1263 keytemplate[3].ulValueLen = passwd_len;
1265 * Create a generic key object to be used for HMAC operations.
1266 * The "value" for this key is the password from the
1267 * mechanism parameter structure.
1269 rv = soft_gen_keyobject(keytemplate,
1270 sizeof (keytemplate)/sizeof (CK_ATTRIBUTE), phKey, session_p,
1271 CKO_SECRET_KEY, (CK_KEY_TYPE)CKK_GENERIC_SECRET, 0,
1272 SOFT_CREATE_OBJ, B_TRUE);
1274 return (rv);
1277 CK_RV
1278 soft_generate_pkcs5_pbkdf2_key(soft_session_t *session_p,
1279 CK_MECHANISM_PTR pMechanism, soft_object_t *secret_key)
1281 CK_RV rv = CKR_OK;
1282 CK_PKCS5_PBKD2_PARAMS *params =
1283 (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter;
1284 CK_ULONG hLen = SHA1_HASH_SIZE;
1285 CK_ULONG dkLen, i;
1286 CK_ULONG blocks, remainder;
1287 CK_OBJECT_HANDLE phKey = 0;
1288 soft_object_t *hmac_key = NULL;
1289 CK_BYTE *salt = NULL;
1290 CK_BYTE *keydata = NULL;
1292 params = (CK_PKCS5_PBKD2_PARAMS_PTR) pMechanism->pParameter;
1294 if (params->prf != CKP_PKCS5_PBKD2_HMAC_SHA1)
1295 return (CKR_MECHANISM_PARAM_INVALID);
1297 if (params->pPrfData != NULL || params->ulPrfDataLen != 0)
1298 return (CKR_DATA_INVALID);
1300 if (params->saltSource != CKZ_SALT_SPECIFIED ||
1301 params->iterations == 0)
1302 return (CKR_MECHANISM_PARAM_INVALID);
1305 * Create a key object to use for HMAC operations.
1307 rv = soft_create_hmac_key(session_p, params->pPassword,
1308 *params->ulPasswordLen, &phKey);
1310 if (rv != CKR_OK)
1311 return (rv);
1313 hmac_key = (soft_object_t *)phKey;
1315 /* Step 1. */
1316 dkLen = OBJ_SEC_VALUE_LEN(secret_key); /* length of desired key */
1318 if (dkLen > ((((u_longlong_t)1)<<32)-1)*hLen) {
1319 (void) soft_delete_object(session_p, hmac_key, B_FALSE,
1320 B_FALSE);
1321 return (CKR_KEY_SIZE_RANGE);
1324 /* Step 2. */
1325 blocks = dkLen / hLen;
1327 /* crude "Ceiling" function to adjust the number of blocks to use */
1328 if (blocks * hLen != dkLen)
1329 blocks++;
1331 remainder = dkLen - ((blocks - 1) * hLen);
1333 /* Step 3 */
1334 salt = (CK_BYTE *)malloc(params->ulSaltSourceDataLen + 4);
1335 if (salt == NULL) {
1336 (void) soft_delete_object(session_p, hmac_key, B_FALSE,
1337 B_FALSE);
1338 return (CKR_HOST_MEMORY);
1341 * Nothing in PKCS#5 says you cannot pass an empty
1342 * salt, so we will allow for this and not return error
1343 * if the salt is not specified.
1345 if (params->pSaltSourceData != NULL && params->ulSaltSourceDataLen > 0)
1346 (void) memcpy(salt, params->pSaltSourceData,
1347 params->ulSaltSourceDataLen);
1350 * Get pointer to the data section of the key,
1351 * this will be used below as output from the
1352 * PRF iteration/concatenations so that when the
1353 * blocks are all iterated, the secret_key will
1354 * have the resulting derived key value.
1356 keydata = (CK_BYTE *)OBJ_SEC_VALUE(secret_key);
1358 /* Step 4. */
1359 for (i = 0; i < blocks && (rv == CKR_OK); i++) {
1360 CK_BYTE *s;
1362 s = salt + params->ulSaltSourceDataLen;
1365 * Append the block index to the salt as input
1366 * to the PRF. Block index should start at 1
1367 * not 0.
1369 *s++ = ((i+1) >> 24) & 0xff;
1370 *s++ = ((i+1) >> 16) & 0xff;
1371 *s++ = ((i+1) >> 8) & 0xff;
1372 *s = ((i+1)) & 0xff;
1375 * Adjust the key pointer so we always append the
1376 * PRF output to the current key.
1378 rv = do_prf(session_p, params, hmac_key,
1379 salt, params->ulSaltSourceDataLen + 4, keydata,
1380 ((i + 1) == blocks ? remainder : hLen));
1382 keydata += hLen;
1384 (void) soft_delete_object(session_p, hmac_key, B_FALSE, B_FALSE);
1385 freezero(salt, params->ulSaltSourceDataLen);
1387 return (rv);
1390 CK_RV
1391 soft_wrapkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
1392 soft_object_t *wrappingKey_p, soft_object_t *hkey_p,
1393 CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen)
1395 CK_RV rv = CKR_OK;
1396 CK_ULONG plain_len = 0;
1397 CK_BYTE_PTR plain_data = NULL;
1398 CK_ULONG padded_len = 0;
1399 CK_BYTE_PTR padded_data = NULL;
1400 CK_ULONG wkey_blksz = 1; /* so modulo will work right */
1402 /* Check if the mechanism is supported. */
1403 switch (pMechanism->mechanism) {
1404 case CKM_DES_CBC_PAD:
1405 case CKM_DES3_CBC_PAD:
1406 case CKM_AES_CBC_PAD:
1408 * Secret key mechs with padding can be used to wrap secret
1409 * keys and private keys only. See PKCS#11, * sec 11.14,
1410 * C_WrapKey and secs 12.* for each mechanism's wrapping/
1411 * unwrapping constraints.
1413 if (hkey_p->class != CKO_SECRET_KEY && hkey_p->class !=
1414 CKO_PRIVATE_KEY)
1415 return (CKR_MECHANISM_INVALID);
1416 break;
1417 case CKM_RSA_PKCS:
1418 case CKM_RSA_X_509:
1419 case CKM_DES_ECB:
1420 case CKM_DES3_ECB:
1421 case CKM_AES_ECB:
1422 case CKM_DES_CBC:
1423 case CKM_DES3_CBC:
1424 case CKM_AES_CBC:
1425 case CKM_AES_CTR:
1426 case CKM_BLOWFISH_CBC:
1428 * Unpadded secret key mechs and private key mechs are only
1429 * defined for wrapping secret keys. See PKCS#11 refs above.
1431 if (hkey_p->class != CKO_SECRET_KEY)
1432 return (CKR_MECHANISM_INVALID);
1433 break;
1434 default:
1435 return (CKR_MECHANISM_INVALID);
1438 if (hkey_p->class == CKO_SECRET_KEY) {
1439 plain_data = OBJ_SEC_VALUE(hkey_p);
1440 plain_len = OBJ_SEC_VALUE_LEN(hkey_p);
1441 } else {
1443 * BER-encode the object to be wrapped: call first with
1444 * plain_data = NULL to get the size needed, allocate that
1445 * much space, call again to fill space with actual data.
1447 rv = soft_object_to_asn1(hkey_p, NULL, &plain_len);
1448 if (rv != CKR_OK)
1449 return (rv);
1450 if ((plain_data = malloc(plain_len)) == NULL)
1451 return (CKR_HOST_MEMORY);
1452 (void) memset(plain_data, 0x0, plain_len);
1453 rv = soft_object_to_asn1(hkey_p, plain_data, &plain_len);
1454 if (rv != CKR_OK)
1455 goto cleanup_wrap;
1459 * For unpadded ECB and CBC mechanisms, the object needs to be
1460 * padded to the wrapping key's blocksize prior to the encryption.
1462 padded_len = plain_len;
1463 padded_data = plain_data;
1465 switch (pMechanism->mechanism) {
1466 case CKM_DES_ECB:
1467 case CKM_DES3_ECB:
1468 case CKM_AES_ECB:
1469 case CKM_DES_CBC:
1470 case CKM_DES3_CBC:
1471 case CKM_AES_CBC:
1472 case CKM_BLOWFISH_CBC:
1473 /* Find the block size of the wrapping key. */
1474 if (wrappingKey_p->class == CKO_SECRET_KEY) {
1475 switch (wrappingKey_p->key_type) {
1476 case CKK_DES:
1477 case CKK_DES2:
1478 case CKK_DES3:
1479 wkey_blksz = DES_BLOCK_LEN;
1480 break;
1481 case CKK_AES:
1482 wkey_blksz = AES_BLOCK_LEN;
1483 break;
1484 case CKK_BLOWFISH:
1485 wkey_blksz = BLOWFISH_BLOCK_LEN;
1486 break;
1487 default:
1488 break;
1490 } else {
1491 rv = CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
1492 goto cleanup_wrap;
1495 /* Extend the plain text data to block size boundary. */
1496 if ((padded_len % wkey_blksz) != 0) {
1497 padded_len += (wkey_blksz - (plain_len % wkey_blksz));
1498 if ((padded_data = malloc(padded_len)) == NULL) {
1499 rv = CKR_HOST_MEMORY;
1500 goto cleanup_wrap;
1502 (void) memset(padded_data, 0x0, padded_len);
1503 (void) memcpy(padded_data, plain_data, plain_len);
1505 break;
1506 default:
1507 break;
1510 rv = soft_encrypt_init(session_p, pMechanism, wrappingKey_p);
1511 if (rv != CKR_OK)
1512 goto cleanup_wrap;
1514 rv = soft_encrypt(session_p, padded_data, padded_len,
1515 pWrappedKey, pulWrappedKeyLen);
1517 cleanup_wrap:
1518 if (padded_data != NULL && padded_len != plain_len) {
1519 /* Clear buffer before returning to memory pool. */
1520 freezero(padded_data, padded_len);
1523 if ((hkey_p->class != CKO_SECRET_KEY) && (plain_data != NULL)) {
1524 /* Clear buffer before returning to memory pool. */
1525 freezero(plain_data, plain_len);
1528 return (rv);
1532 * Quick check for whether unwrapped key length is appropriate for key type
1533 * and whether it needs to be truncated (in case the wrapping function had
1534 * to pad the key prior to wrapping).
1536 static CK_RV
1537 soft_unwrap_secret_len_check(CK_KEY_TYPE keytype, CK_MECHANISM_TYPE mechtype,
1538 CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount)
1540 CK_ULONG i;
1541 boolean_t isValueLen = B_FALSE;
1544 * Based on the key type and the mech used to unwrap, need to
1545 * determine if CKA_VALUE_LEN should or should not be specified.
1546 * PKCS#11 v2.11 restricts CKA_VALUE_LEN from being specified
1547 * for C_UnwrapKey for all mechs and key types, but v2.20 loosens
1548 * that restriction, perhaps because it makes it impossible to
1549 * determine the original length of unwrapped variable-length secret
1550 * keys, such as RC4, AES, and GENERIC_SECRET. These variable-length
1551 * secret keys would have been padded with trailing null-bytes so
1552 * that they could be successfully wrapped with *_ECB and *_CBC
1553 * mechanisms. Hence for unwrapping with these mechs, CKA_VALUE_LEN
1554 * must be specified. For unwrapping with other mechs, such as
1555 * *_CBC_PAD, the CKA_VALUE_LEN is not needed.
1558 /* Find out if template has CKA_VALUE_LEN. */
1559 for (i = 0; i < ulAttributeCount; i++) {
1560 if (pTemplate[i].type == CKA_VALUE_LEN &&
1561 pTemplate[i].pValue != NULL) {
1562 isValueLen = B_TRUE;
1563 break;
1567 /* Does its presence conflict with the mech type and key type? */
1568 switch (mechtype) {
1569 case CKM_DES_ECB:
1570 case CKM_DES3_ECB:
1571 case CKM_AES_ECB:
1572 case CKM_DES_CBC:
1573 case CKM_DES3_CBC:
1574 case CKM_AES_CBC:
1575 case CKM_BLOWFISH_CBC:
1577 * CKA_VALUE_LEN must be specified
1578 * if keytype is CKK_RC4, CKK_AES and CKK_GENERIC_SECRET
1579 * and must not be specified otherwise
1581 switch (keytype) {
1582 case CKK_DES:
1583 case CKK_DES2:
1584 case CKK_DES3:
1585 if (isValueLen)
1586 return (CKR_TEMPLATE_INCONSISTENT);
1587 break;
1588 case CKK_GENERIC_SECRET:
1589 case CKK_RC4:
1590 case CKK_AES:
1591 case CKK_BLOWFISH:
1592 if (!isValueLen)
1593 return (CKR_TEMPLATE_INCOMPLETE);
1594 break;
1595 default:
1596 return (CKR_FUNCTION_NOT_SUPPORTED);
1598 break;
1599 default:
1600 /* CKA_VALUE_LEN must not be specified */
1601 if (isValueLen)
1602 return (CKR_TEMPLATE_INCONSISTENT);
1603 break;
1606 return (CKR_OK);
1609 CK_RV
1610 soft_unwrapkey(soft_session_t *session_p, CK_MECHANISM_PTR pMechanism,
1611 soft_object_t *unwrappingkey_p, CK_BYTE_PTR pWrappedKey,
1612 CK_ULONG ulWrappedKeyLen, CK_ATTRIBUTE_PTR pTemplate,
1613 CK_ULONG ulAttributeCount, CK_OBJECT_HANDLE_PTR phKey)
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;
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;
1633 if (new_obj_class == ~0UL)
1634 return (CKR_TEMPLATE_INCOMPLETE);
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.
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);
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);
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.
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.
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;
1690 rv = soft_decrypt_init(session_p, pMechanism, unwrappingkey_p);
1691 if (rv != CKR_OK)
1692 goto cleanup_unwrap;
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;
1700 /* Allocate space for the unwrapped data */
1701 if ((plain_data = malloc(plain_len)) == NULL) {
1702 rv = CKR_HOST_MEMORY;
1703 goto cleanup_unwrap;
1705 (void) memset(plain_data, 0x0, plain_len);
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;
1713 if (new_objp->class == CKO_SECRET_KEY) {
1715 * Since no ASN.1 encoding is done for secret keys, check for
1716 * appropriateness and copy decrypted buffer to the key object.
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;
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.
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;
1736 OBJ_SEC(new_objp) = sck;
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;
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.
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;
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;
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;
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;
1802 if (new_objp->class != CKO_SECRET_KEY) {
1803 /* Clear buffer before returning to memory pool. */
1804 freezero(plain_data, plain_len);
1807 *phKey = (CK_OBJECT_HANDLE)new_objp;
1809 return (CKR_OK);
1811 cleanup_unwrap:
1812 /* The decrypted private key buffer must be freed explicitly. */
1813 if ((new_objp->class != CKO_SECRET_KEY) && (plain_data != NULL)) {
1814 /* Clear buffer before returning to memory pool. */
1815 freezero(plain_data, plain_len);
1818 /* sck and new_objp are indirectly free()d inside these functions */
1819 if (IS_TOKEN_OBJECT(new_objp))
1820 soft_delete_token_object(new_objp, persistent, B_FALSE);
1821 else
1822 soft_delete_object(session_p, new_objp, B_FALSE, B_FALSE);
1824 return (rv);