michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: /* michael@0: * This file contains functions to manage asymetric keys, (public and michael@0: * private keys). michael@0: */ michael@0: #include "seccomon.h" michael@0: #include "secmod.h" michael@0: #include "secmodi.h" michael@0: #include "secmodti.h" michael@0: #include "pkcs11.h" michael@0: #include "pkcs11t.h" michael@0: #include "pk11func.h" michael@0: #include "cert.h" michael@0: #include "key.h" michael@0: #include "secitem.h" michael@0: #include "secasn1.h" michael@0: #include "secoid.h" michael@0: #include "secerr.h" michael@0: #include "sslerr.h" michael@0: #include "sechash.h" michael@0: michael@0: #include "secpkcs5.h" michael@0: #include "blapit.h" michael@0: michael@0: static SECItem * michael@0: pk11_MakeIDFromPublicKey(SECKEYPublicKey *pubKey) michael@0: { michael@0: /* set the ID to the public key so we can find it again */ michael@0: SECItem *pubKeyIndex = NULL; michael@0: switch (pubKey->keyType) { michael@0: case rsaKey: michael@0: pubKeyIndex = &pubKey->u.rsa.modulus; michael@0: break; michael@0: case dsaKey: michael@0: pubKeyIndex = &pubKey->u.dsa.publicValue; michael@0: break; michael@0: case dhKey: michael@0: pubKeyIndex = &pubKey->u.dh.publicValue; michael@0: break; michael@0: case ecKey: michael@0: pubKeyIndex = &pubKey->u.ec.publicValue; michael@0: break; michael@0: default: michael@0: return NULL; michael@0: } michael@0: PORT_Assert(pubKeyIndex != NULL); michael@0: michael@0: return PK11_MakeIDFromPubKey(pubKeyIndex); michael@0: } michael@0: michael@0: /* michael@0: * import a public key into the desired slot michael@0: * michael@0: * This function takes a public key structure and creates a public key in a michael@0: * given slot. If isToken is set, then a persistant public key is created. michael@0: * michael@0: * Note: it is possible for this function to return a handle for a key which michael@0: * is persistant, even if isToken is not set. michael@0: */ michael@0: CK_OBJECT_HANDLE michael@0: PK11_ImportPublicKey(PK11SlotInfo *slot, SECKEYPublicKey *pubKey, michael@0: PRBool isToken) michael@0: { michael@0: CK_BBOOL cktrue = CK_TRUE; michael@0: CK_BBOOL ckfalse = CK_FALSE; michael@0: CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY; michael@0: CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; michael@0: CK_OBJECT_HANDLE objectID; michael@0: CK_ATTRIBUTE theTemplate[11]; michael@0: CK_ATTRIBUTE *signedattr = NULL; michael@0: CK_ATTRIBUTE *attrs = theTemplate; michael@0: SECItem *ckaId = NULL; michael@0: SECItem *pubValue = NULL; michael@0: int signedcount = 0; michael@0: int templateCount = 0; michael@0: SECStatus rv; michael@0: michael@0: /* if we already have an object in the desired slot, use it */ michael@0: if (!isToken && pubKey->pkcs11Slot == slot) { michael@0: return pubKey->pkcs11ID; michael@0: } michael@0: michael@0: /* free the existing key */ michael@0: if (pubKey->pkcs11Slot != NULL) { michael@0: PK11SlotInfo *oSlot = pubKey->pkcs11Slot; michael@0: if (!PK11_IsPermObject(pubKey->pkcs11Slot,pubKey->pkcs11ID)) { michael@0: PK11_EnterSlotMonitor(oSlot); michael@0: (void) PK11_GETTAB(oSlot)->C_DestroyObject(oSlot->session, michael@0: pubKey->pkcs11ID); michael@0: PK11_ExitSlotMonitor(oSlot); michael@0: } michael@0: PK11_FreeSlot(oSlot); michael@0: pubKey->pkcs11Slot = NULL; michael@0: } michael@0: PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_TOKEN, isToken ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL) ); attrs++; michael@0: if (isToken) { michael@0: ckaId = pk11_MakeIDFromPublicKey(pubKey); michael@0: if (ckaId == NULL) { michael@0: PORT_SetError( SEC_ERROR_BAD_KEY ); michael@0: return CK_INVALID_HANDLE; michael@0: } michael@0: PK11_SETATTRS(attrs, CKA_ID, ckaId->data, ckaId->len); attrs++; michael@0: } michael@0: michael@0: /* now import the key */ michael@0: { michael@0: switch (pubKey->keyType) { michael@0: case rsaKey: michael@0: keyType = CKK_RSA; michael@0: PK11_SETATTRS(attrs, CKA_WRAP, &cktrue, sizeof(CK_BBOOL) ); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_ENCRYPT, &cktrue, michael@0: sizeof(CK_BBOOL) ); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL)); attrs++; michael@0: signedattr = attrs; michael@0: PK11_SETATTRS(attrs, CKA_MODULUS, pubKey->u.rsa.modulus.data, michael@0: pubKey->u.rsa.modulus.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, michael@0: pubKey->u.rsa.publicExponent.data, michael@0: pubKey->u.rsa.publicExponent.len); attrs++; michael@0: break; michael@0: case dsaKey: michael@0: keyType = CKK_DSA; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++; michael@0: signedattr = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dsa.params.prime.data, michael@0: pubKey->u.dsa.params.prime.len); attrs++; michael@0: PK11_SETATTRS(attrs,CKA_SUBPRIME,pubKey->u.dsa.params.subPrime.data, michael@0: pubKey->u.dsa.params.subPrime.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dsa.params.base.data, michael@0: pubKey->u.dsa.params.base.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dsa.publicValue.data, michael@0: pubKey->u.dsa.publicValue.len); attrs++; michael@0: break; michael@0: case fortezzaKey: michael@0: keyType = CKK_DSA; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++; michael@0: signedattr = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PRIME,pubKey->u.fortezza.params.prime.data, michael@0: pubKey->u.fortezza.params.prime.len); attrs++; michael@0: PK11_SETATTRS(attrs,CKA_SUBPRIME, michael@0: pubKey->u.fortezza.params.subPrime.data, michael@0: pubKey->u.fortezza.params.subPrime.len);attrs++; michael@0: PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.fortezza.params.base.data, michael@0: pubKey->u.fortezza.params.base.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.fortezza.DSSKey.data, michael@0: pubKey->u.fortezza.DSSKey.len); attrs++; michael@0: break; michael@0: case dhKey: michael@0: keyType = CKK_DH; michael@0: PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));attrs++; michael@0: signedattr = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dh.prime.data, michael@0: pubKey->u.dh.prime.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dh.base.data, michael@0: pubKey->u.dh.base.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dh.publicValue.data, michael@0: pubKey->u.dh.publicValue.len); attrs++; michael@0: break; michael@0: case ecKey: michael@0: keyType = CKK_EC; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++; michael@0: PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));attrs++; michael@0: signedattr = attrs; michael@0: PK11_SETATTRS(attrs, CKA_EC_PARAMS, michael@0: pubKey->u.ec.DEREncodedParams.data, michael@0: pubKey->u.ec.DEREncodedParams.len); attrs++; michael@0: if (PR_GetEnv("NSS_USE_DECODED_CKA_EC_POINT")) { michael@0: PK11_SETATTRS(attrs, CKA_EC_POINT, michael@0: pubKey->u.ec.publicValue.data, michael@0: pubKey->u.ec.publicValue.len); attrs++; michael@0: } else { michael@0: pubValue = SEC_ASN1EncodeItem(NULL, NULL, michael@0: &pubKey->u.ec.publicValue, michael@0: SEC_ASN1_GET(SEC_OctetStringTemplate)); michael@0: if (pubValue == NULL) { michael@0: if (ckaId) { michael@0: SECITEM_FreeItem(ckaId,PR_TRUE); michael@0: } michael@0: return CK_INVALID_HANDLE; michael@0: } michael@0: PK11_SETATTRS(attrs, CKA_EC_POINT, michael@0: pubValue->data, pubValue->len); attrs++; michael@0: } michael@0: break; michael@0: default: michael@0: if (ckaId) { michael@0: SECITEM_FreeItem(ckaId,PR_TRUE); michael@0: } michael@0: PORT_SetError( SEC_ERROR_BAD_KEY ); michael@0: return CK_INVALID_HANDLE; michael@0: } michael@0: michael@0: templateCount = attrs - theTemplate; michael@0: signedcount = attrs - signedattr; michael@0: PORT_Assert(templateCount <= (sizeof(theTemplate)/sizeof(CK_ATTRIBUTE))); michael@0: for (attrs=signedattr; signedcount; attrs++, signedcount--) { michael@0: pk11_SignedToUnsigned(attrs); michael@0: } michael@0: rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, theTemplate, michael@0: templateCount, isToken, &objectID); michael@0: if (ckaId) { michael@0: SECITEM_FreeItem(ckaId,PR_TRUE); michael@0: } michael@0: if (pubValue) { michael@0: SECITEM_FreeItem(pubValue,PR_TRUE); michael@0: } michael@0: if ( rv != SECSuccess) { michael@0: return CK_INVALID_HANDLE; michael@0: } michael@0: } michael@0: michael@0: pubKey->pkcs11ID = objectID; michael@0: pubKey->pkcs11Slot = PK11_ReferenceSlot(slot); michael@0: michael@0: return objectID; michael@0: } michael@0: michael@0: /* michael@0: * take an attribute and copy it into a secitem michael@0: */ michael@0: static CK_RV michael@0: pk11_Attr2SecItem(PLArenaPool *arena, const CK_ATTRIBUTE *attr, SECItem *item) michael@0: { michael@0: item->data = NULL; michael@0: michael@0: (void)SECITEM_AllocItem(arena, item, attr->ulValueLen); michael@0: if (item->data == NULL) { michael@0: return CKR_HOST_MEMORY; michael@0: } michael@0: PORT_Memcpy(item->data, attr->pValue, item->len); michael@0: return CKR_OK; michael@0: } michael@0: michael@0: michael@0: /* michael@0: * get a curve length from a set of ecParams. michael@0: * michael@0: * We need this so we can reliably determine if the ecPoint passed to us michael@0: * was encoded or not. With out this, for many curves, we would incorrectly michael@0: * identify an unencoded curve as an encoded curve 1 in 65536 times, and for michael@0: * a few we would make that same mistake 1 in 32768 times. These are bad michael@0: * numbers since they are rare enough to pass tests, but common enough to michael@0: * be tripped over in the field. michael@0: * michael@0: * This function will only work for curves we recognized as of March 2009. michael@0: * The assumption is curves in use after March of 2009 would be supplied by michael@0: * PKCS #11 modules that already pass the correct encoding to us. michael@0: * michael@0: * Point length = (Roundup(curveLenInBits/8)*2+1) michael@0: */ michael@0: static int michael@0: pk11_get_EC_PointLenInBytes(PLArenaPool *arena, const SECItem *ecParams) michael@0: { michael@0: SECItem oid; michael@0: SECOidTag tag; michael@0: SECStatus rv; michael@0: michael@0: /* decode the OID tag */ michael@0: rv = SEC_QuickDERDecodeItem(arena, &oid, michael@0: SEC_ASN1_GET(SEC_ObjectIDTemplate), ecParams); michael@0: if (rv != SECSuccess) { michael@0: /* could be explict curves, allow them to work if the michael@0: * PKCS #11 module support them. If we try to parse the michael@0: * explicit curve value in the future, we may return -1 here michael@0: * to indicate an invalid parameter if the explicit curve michael@0: * decode fails. */ michael@0: return 0; michael@0: } michael@0: michael@0: tag = SECOID_FindOIDTag(&oid); michael@0: switch (tag) { michael@0: case SEC_OID_SECG_EC_SECP112R1: michael@0: case SEC_OID_SECG_EC_SECP112R2: michael@0: return 29; /* curve len in bytes = 14 bytes */ michael@0: case SEC_OID_SECG_EC_SECT113R1: michael@0: case SEC_OID_SECG_EC_SECT113R2: michael@0: return 31; /* curve len in bytes = 15 bytes */ michael@0: case SEC_OID_SECG_EC_SECP128R1: michael@0: case SEC_OID_SECG_EC_SECP128R2: michael@0: return 33; /* curve len in bytes = 16 bytes */ michael@0: case SEC_OID_SECG_EC_SECT131R1: michael@0: case SEC_OID_SECG_EC_SECT131R2: michael@0: return 35; /* curve len in bytes = 17 bytes */ michael@0: case SEC_OID_SECG_EC_SECP160K1: michael@0: case SEC_OID_SECG_EC_SECP160R1: michael@0: case SEC_OID_SECG_EC_SECP160R2: michael@0: return 41; /* curve len in bytes = 20 bytes */ michael@0: case SEC_OID_SECG_EC_SECT163K1: michael@0: case SEC_OID_SECG_EC_SECT163R1: michael@0: case SEC_OID_SECG_EC_SECT163R2: michael@0: case SEC_OID_ANSIX962_EC_C2PNB163V1: michael@0: case SEC_OID_ANSIX962_EC_C2PNB163V2: michael@0: case SEC_OID_ANSIX962_EC_C2PNB163V3: michael@0: return 43; /* curve len in bytes = 21 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2PNB176V1: michael@0: return 45; /* curve len in bytes = 22 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2TNB191V1: michael@0: case SEC_OID_ANSIX962_EC_C2TNB191V2: michael@0: case SEC_OID_ANSIX962_EC_C2TNB191V3: michael@0: case SEC_OID_SECG_EC_SECP192K1: michael@0: case SEC_OID_ANSIX962_EC_PRIME192V1: michael@0: case SEC_OID_ANSIX962_EC_PRIME192V2: michael@0: case SEC_OID_ANSIX962_EC_PRIME192V3: michael@0: return 49; /*curve len in bytes = 24 bytes */ michael@0: case SEC_OID_SECG_EC_SECT193R1: michael@0: case SEC_OID_SECG_EC_SECT193R2: michael@0: return 51; /*curve len in bytes = 25 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2PNB208W1: michael@0: return 53; /*curve len in bytes = 26 bytes */ michael@0: case SEC_OID_SECG_EC_SECP224K1: michael@0: case SEC_OID_SECG_EC_SECP224R1: michael@0: return 57; /*curve len in bytes = 28 bytes */ michael@0: case SEC_OID_SECG_EC_SECT233K1: michael@0: case SEC_OID_SECG_EC_SECT233R1: michael@0: case SEC_OID_SECG_EC_SECT239K1: michael@0: case SEC_OID_ANSIX962_EC_PRIME239V1: michael@0: case SEC_OID_ANSIX962_EC_PRIME239V2: michael@0: case SEC_OID_ANSIX962_EC_PRIME239V3: michael@0: case SEC_OID_ANSIX962_EC_C2TNB239V1: michael@0: case SEC_OID_ANSIX962_EC_C2TNB239V2: michael@0: case SEC_OID_ANSIX962_EC_C2TNB239V3: michael@0: return 61; /*curve len in bytes = 30 bytes */ michael@0: case SEC_OID_ANSIX962_EC_PRIME256V1: michael@0: case SEC_OID_SECG_EC_SECP256K1: michael@0: return 65; /*curve len in bytes = 32 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2PNB272W1: michael@0: return 69; /*curve len in bytes = 34 bytes */ michael@0: case SEC_OID_SECG_EC_SECT283K1: michael@0: case SEC_OID_SECG_EC_SECT283R1: michael@0: return 73; /*curve len in bytes = 36 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2PNB304W1: michael@0: return 77; /*curve len in bytes = 38 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2TNB359V1: michael@0: return 91; /*curve len in bytes = 45 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2PNB368W1: michael@0: return 93; /*curve len in bytes = 46 bytes */ michael@0: case SEC_OID_SECG_EC_SECP384R1: michael@0: return 97; /*curve len in bytes = 48 bytes */ michael@0: case SEC_OID_SECG_EC_SECT409K1: michael@0: case SEC_OID_SECG_EC_SECT409R1: michael@0: return 105; /*curve len in bytes = 52 bytes */ michael@0: case SEC_OID_ANSIX962_EC_C2TNB431R1: michael@0: return 109; /*curve len in bytes = 54 bytes */ michael@0: case SEC_OID_SECG_EC_SECP521R1: michael@0: return 133; /*curve len in bytes = 66 bytes */ michael@0: case SEC_OID_SECG_EC_SECT571K1: michael@0: case SEC_OID_SECG_EC_SECT571R1: michael@0: return 145; /*curve len in bytes = 72 bytes */ michael@0: /* unknown or unrecognized OIDs. return unknown length */ michael@0: default: michael@0: break; michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: /* michael@0: * returns the decoded point. In some cases the point may already be decoded. michael@0: * this function tries to detect those cases and return the point in michael@0: * publicKeyValue. In other cases it's DER encoded. In those cases the point michael@0: * is first decoded and returned. Space for the point is allocated out of michael@0: * the passed in arena. michael@0: */ michael@0: static CK_RV michael@0: pk11_get_Decoded_ECPoint(PLArenaPool *arena, const SECItem *ecParams, michael@0: const CK_ATTRIBUTE *ecPoint, SECItem *publicKeyValue) michael@0: { michael@0: SECItem encodedPublicValue; michael@0: SECStatus rv; michael@0: int keyLen; michael@0: michael@0: if (ecPoint->ulValueLen == 0) { michael@0: return CKR_ATTRIBUTE_VALUE_INVALID; michael@0: } michael@0: michael@0: /* michael@0: * The PKCS #11 spec requires ecPoints to be encoded as a DER OCTET String. michael@0: * NSS has mistakenly passed unencoded values, and some PKCS #11 vendors michael@0: * followed that mistake. Now we need to detect which encoding we were michael@0: * passed in. The task is made more complicated by the fact the the michael@0: * DER encoding byte (SEC_ASN_OCTET_STRING) is the same as the michael@0: * EC_POINT_FORM_UNCOMPRESSED byte (0x04), so we can't use that to michael@0: * determine which curve we are using. michael@0: */ michael@0: michael@0: /* get the expected key length for the passed in curve. michael@0: * pk11_get_EC_PointLenInBytes only returns valid values for curves michael@0: * NSS has traditionally recognized. If the curve is not recognized, michael@0: * it will return '0', and we have to figure out if the key was michael@0: * encoded or not heuristically. If the ecParams are invalid, it michael@0: * will return -1 for the keyLen. michael@0: */ michael@0: keyLen = pk11_get_EC_PointLenInBytes(arena, ecParams); michael@0: if (keyLen < 0) { michael@0: return CKR_ATTRIBUTE_VALUE_INVALID; michael@0: } michael@0: michael@0: michael@0: /* If the point is uncompressed and the lengths match, it michael@0: * must be an unencoded point */ michael@0: if ((*((char *)ecPoint->pValue) == EC_POINT_FORM_UNCOMPRESSED) michael@0: && (ecPoint->ulValueLen == keyLen)) { michael@0: return pk11_Attr2SecItem(arena, ecPoint, publicKeyValue); michael@0: } michael@0: michael@0: /* now assume the key passed to us was encoded and decode it */ michael@0: if (*((char *)ecPoint->pValue) == SEC_ASN1_OCTET_STRING) { michael@0: /* OK, now let's try to decode it and see if it's valid */ michael@0: encodedPublicValue.data = ecPoint->pValue; michael@0: encodedPublicValue.len = ecPoint->ulValueLen; michael@0: rv = SEC_QuickDERDecodeItem(arena, publicKeyValue, michael@0: SEC_ASN1_GET(SEC_OctetStringTemplate), &encodedPublicValue); michael@0: michael@0: /* it coded correctly & we know the key length (and they match) michael@0: * then we are done, return the results. */ michael@0: if (keyLen && rv == SECSuccess && publicKeyValue->len == keyLen) { michael@0: return CKR_OK; michael@0: } michael@0: michael@0: /* if we know the key length, one of the above tests should have michael@0: * succeded. If it doesn't the module gave us bad data */ michael@0: if (keyLen) { michael@0: return CKR_ATTRIBUTE_VALUE_INVALID; michael@0: } michael@0: michael@0: michael@0: /* We don't know the key length, so we don't know deterministically michael@0: * which encoding was used. We now will try to pick the most likely michael@0: * form that's correct, with a preference for the encoded form if we michael@0: * can't determine for sure. We do this by checking the key we got michael@0: * back from SEC_QuickDERDecodeItem for defects. If no defects are michael@0: * found, we assume the encoded parameter was was passed to us. michael@0: * our defect tests include: michael@0: * 1) it didn't decode. michael@0: * 2) The decode key had an invalid length (must be odd). michael@0: * 3) The decoded key wasn't an UNCOMPRESSED key. michael@0: * 4) The decoded key didn't include the entire encoded block michael@0: * except the DER encoding values. (fixing DER length to one michael@0: * particular value). michael@0: */ michael@0: if ((rv != SECSuccess) michael@0: || ((publicKeyValue->len & 1) != 1) michael@0: || (publicKeyValue->data[0] != EC_POINT_FORM_UNCOMPRESSED) michael@0: || (PORT_Memcmp(&encodedPublicValue.data[encodedPublicValue.len - michael@0: publicKeyValue->len], publicKeyValue->data, michael@0: publicKeyValue->len) != 0)) { michael@0: /* The decoded public key was flawed, the original key must have michael@0: * already been in decoded form. Do a quick sanity check then michael@0: * return the original key value. michael@0: */ michael@0: if ((encodedPublicValue.len & 1) == 0) { michael@0: return CKR_ATTRIBUTE_VALUE_INVALID; michael@0: } michael@0: return pk11_Attr2SecItem(arena, ecPoint, publicKeyValue); michael@0: } michael@0: michael@0: /* as best we can figure, the passed in key was encoded, and we've michael@0: * now decoded it. Note: there is a chance this could be wrong if the michael@0: * following conditions hold: michael@0: * 1) The first byte or bytes of the X point looks like a valid length michael@0: * of precisely the right size (2*curveSize -1). this means for curves michael@0: * less than 512 bits (64 bytes), this will happen 1 in 256 times*. michael@0: * for curves between 512 and 1024, this will happen 1 in 65,536 times* michael@0: * for curves between 1024 and 256K this will happen 1 in 16 million* michael@0: * 2) The length of the 'DER length field' is odd michael@0: * (making both the encoded and decode michael@0: * values an odd length. this is true of all curves less than 512, michael@0: * as well as curves between 1024 and 256K). michael@0: * 3) The X[length of the 'DER length field'] == 0x04, 1 in 256. michael@0: * michael@0: * (* assuming all values are equally likely in the first byte, michael@0: * This isn't true if the curve length is not a multiple of 8. In these michael@0: * cases, if the DER length is possible, it's more likely, michael@0: * if it's not possible, then we have no false decodes). michael@0: * michael@0: * For reference here are the odds for the various curves we currently michael@0: * have support for (and the only curves SSL will negotiate at this michael@0: * time). NOTE: None of the supported curves will show up here michael@0: * because we return a valid length for all of these curves. michael@0: * The only way to get here is to have some application (not SSL) michael@0: * which supports some unknown curve and have some vendor supplied michael@0: * PKCS #11 module support that curve. NOTE: in this case, one michael@0: * presumes that that pkcs #11 module is likely to be using the michael@0: * correct encodings. michael@0: * michael@0: * Prime Curves (GFp): michael@0: * Bit False Odds of michael@0: * Size DER Len False Decode Positive michael@0: * 112 27 1 in 65536 michael@0: * 128 31 1 in 65536 michael@0: * 160 39 1 in 65536 michael@0: * 192 47 1 in 65536 michael@0: * 224 55 1 in 65536 michael@0: * 239 59 1 in 32768 (top byte can only be 0-127) michael@0: * 256 63 1 in 65536 michael@0: * 521 129,131 0 (decoded value would be even) michael@0: * michael@0: * Binary curves (GF2m). michael@0: * Bit False Odds of michael@0: * Size DER Len False Decode Positive michael@0: * 131 33 0 (top byte can only be 0-7) michael@0: * 163 41 0 (top byte can only be 0-7) michael@0: * 176 43 1 in 65536 michael@0: * 191 47 1 in 32768 (top byte can only be 0-127) michael@0: * 193 49 0 (top byte can only be 0-1) michael@0: * 208 51 1 in 65536 michael@0: * 233 59 0 (top byte can only be 0-1) michael@0: * 239 59 1 in 32768 (top byte can only be 0-127) michael@0: * 272 67 1 in 65536 michael@0: * 283 71 0 (top byte can only be 0-7) michael@0: * 304 75 1 in 65536 michael@0: * 359 89 1 in 32768 (top byte can only be 0-127) michael@0: * 368 91 1 in 65536 michael@0: * 409 103 0 (top byte can only be 0-1) michael@0: * 431 107 1 in 32768 (top byte can only be 0-127) michael@0: * 571 129,143 0 (decoded value would be even) michael@0: * michael@0: */ michael@0: michael@0: return CKR_OK; michael@0: } michael@0: michael@0: /* In theory, we should handle the case where the curve == 0 and michael@0: * the first byte is EC_POINT_FORM_UNCOMPRESSED, (which would be michael@0: * handled by doing a santity check on the key length and returning michael@0: * pk11_Attr2SecItem() to copy the ecPoint to the publicKeyValue). michael@0: * michael@0: * This test is unnecessary, however, due to the fact that michael@0: * EC_POINT_FORM_UNCOMPRESSED == SEC_ASIN1_OCTET_STRING, that case is michael@0: * handled in the above if. That means if we get here, the initial michael@0: * byte of our ecPoint value was invalid, so we can safely return. michael@0: * invalid attribute. michael@0: */ michael@0: michael@0: return CKR_ATTRIBUTE_VALUE_INVALID; michael@0: } michael@0: michael@0: /* michael@0: * extract a public key from a slot and id michael@0: */ michael@0: SECKEYPublicKey * michael@0: PK11_ExtractPublicKey(PK11SlotInfo *slot,KeyType keyType,CK_OBJECT_HANDLE id) michael@0: { michael@0: CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY; michael@0: PLArenaPool *arena; michael@0: PLArenaPool *tmp_arena; michael@0: SECKEYPublicKey *pubKey; michael@0: int templateCount = 0; michael@0: CK_KEY_TYPE pk11KeyType; michael@0: CK_RV crv; michael@0: CK_ATTRIBUTE template[8]; michael@0: CK_ATTRIBUTE *attrs= template; michael@0: CK_ATTRIBUTE *modulus,*exponent,*base,*prime,*subprime,*value; michael@0: CK_ATTRIBUTE *ecparams; michael@0: michael@0: /* if we didn't know the key type, get it */ michael@0: if (keyType== nullKey) { michael@0: michael@0: pk11KeyType = PK11_ReadULongAttribute(slot,id,CKA_KEY_TYPE); michael@0: if (pk11KeyType == CK_UNAVAILABLE_INFORMATION) { michael@0: return NULL; michael@0: } michael@0: switch (pk11KeyType) { michael@0: case CKK_RSA: michael@0: keyType = rsaKey; michael@0: break; michael@0: case CKK_DSA: michael@0: keyType = dsaKey; michael@0: break; michael@0: case CKK_DH: michael@0: keyType = dhKey; michael@0: break; michael@0: case CKK_EC: michael@0: keyType = ecKey; michael@0: break; michael@0: default: michael@0: PORT_SetError( SEC_ERROR_BAD_KEY ); michael@0: return NULL; michael@0: } michael@0: } michael@0: michael@0: michael@0: /* now we need to create space for the public key */ michael@0: arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) return NULL; michael@0: tmp_arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE); michael@0: if (tmp_arena == NULL) { michael@0: PORT_FreeArena (arena, PR_FALSE); michael@0: return NULL; michael@0: } michael@0: michael@0: michael@0: pubKey = (SECKEYPublicKey *) michael@0: PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey)); michael@0: if (pubKey == NULL) { michael@0: PORT_FreeArena (arena, PR_FALSE); michael@0: PORT_FreeArena (tmp_arena, PR_FALSE); michael@0: return NULL; michael@0: } michael@0: michael@0: pubKey->arena = arena; michael@0: pubKey->keyType = keyType; michael@0: pubKey->pkcs11Slot = PK11_ReferenceSlot(slot); michael@0: pubKey->pkcs11ID = id; michael@0: PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, michael@0: sizeof(keyClass)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_KEY_TYPE, &pk11KeyType, michael@0: sizeof(pk11KeyType) ); attrs++; michael@0: switch (pubKey->keyType) { michael@0: case rsaKey: michael@0: modulus = attrs; michael@0: PK11_SETATTRS(attrs, CKA_MODULUS, NULL, 0); attrs++; michael@0: exponent = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, NULL, 0); attrs++; michael@0: michael@0: templateCount = attrs - template; michael@0: PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE)); michael@0: crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount); michael@0: if (crv != CKR_OK) break; michael@0: michael@0: if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_RSA)) { michael@0: crv = CKR_OBJECT_HANDLE_INVALID; michael@0: break; michael@0: } michael@0: crv = pk11_Attr2SecItem(arena,modulus,&pubKey->u.rsa.modulus); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,exponent,&pubKey->u.rsa.publicExponent); michael@0: if (crv != CKR_OK) break; michael@0: break; michael@0: case dsaKey: michael@0: prime = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++; michael@0: subprime = attrs; michael@0: PK11_SETATTRS(attrs, CKA_SUBPRIME, NULL, 0); attrs++; michael@0: base = attrs; michael@0: PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++; michael@0: value = attrs; michael@0: PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++; michael@0: templateCount = attrs - template; michael@0: PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE)); michael@0: crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount); michael@0: if (crv != CKR_OK) break; michael@0: michael@0: if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DSA)) { michael@0: crv = CKR_OBJECT_HANDLE_INVALID; michael@0: break; michael@0: } michael@0: crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dsa.params.prime); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,subprime,&pubKey->u.dsa.params.subPrime); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dsa.params.base); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dsa.publicValue); michael@0: if (crv != CKR_OK) break; michael@0: break; michael@0: case dhKey: michael@0: prime = attrs; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++; michael@0: base = attrs; michael@0: PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++; michael@0: value =attrs; michael@0: PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++; michael@0: templateCount = attrs - template; michael@0: PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE)); michael@0: crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount); michael@0: if (crv != CKR_OK) break; michael@0: michael@0: if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DH)) { michael@0: crv = CKR_OBJECT_HANDLE_INVALID; michael@0: break; michael@0: } michael@0: crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dh.prime); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dh.base); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dh.publicValue); michael@0: if (crv != CKR_OK) break; michael@0: break; michael@0: case ecKey: michael@0: pubKey->u.ec.size = 0; michael@0: ecparams = attrs; michael@0: PK11_SETATTRS(attrs, CKA_EC_PARAMS, NULL, 0); attrs++; michael@0: value =attrs; michael@0: PK11_SETATTRS(attrs, CKA_EC_POINT, NULL, 0); attrs++; michael@0: templateCount = attrs - template; michael@0: PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE)); michael@0: crv = PK11_GetAttributes(arena,slot,id,template,templateCount); michael@0: if (crv != CKR_OK) break; michael@0: michael@0: if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_EC)) { michael@0: crv = CKR_OBJECT_HANDLE_INVALID; michael@0: break; michael@0: } michael@0: michael@0: crv = pk11_Attr2SecItem(arena,ecparams, michael@0: &pubKey->u.ec.DEREncodedParams); michael@0: if (crv != CKR_OK) break; michael@0: crv = pk11_get_Decoded_ECPoint(arena, michael@0: &pubKey->u.ec.DEREncodedParams, value, michael@0: &pubKey->u.ec.publicValue); michael@0: break; michael@0: case fortezzaKey: michael@0: case nullKey: michael@0: default: michael@0: crv = CKR_OBJECT_HANDLE_INVALID; michael@0: break; michael@0: } michael@0: michael@0: PORT_FreeArena(tmp_arena,PR_FALSE); michael@0: michael@0: if (crv != CKR_OK) { michael@0: PORT_FreeArena(arena,PR_FALSE); michael@0: PK11_FreeSlot(slot); michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: return NULL; michael@0: } michael@0: michael@0: return pubKey; michael@0: } michael@0: michael@0: /* michael@0: * Build a Private Key structure from raw PKCS #11 information. michael@0: */ michael@0: SECKEYPrivateKey * michael@0: PK11_MakePrivKey(PK11SlotInfo *slot, KeyType keyType, michael@0: PRBool isTemp, CK_OBJECT_HANDLE privID, void *wincx) michael@0: { michael@0: PLArenaPool *arena; michael@0: SECKEYPrivateKey *privKey; michael@0: PRBool isPrivate; michael@0: SECStatus rv; michael@0: michael@0: /* don't know? look it up */ michael@0: if (keyType == nullKey) { michael@0: CK_KEY_TYPE pk11Type = CKK_RSA; michael@0: michael@0: pk11Type = PK11_ReadULongAttribute(slot,privID,CKA_KEY_TYPE); michael@0: isTemp = (PRBool)!PK11_HasAttributeSet(slot,privID,CKA_TOKEN,PR_FALSE); michael@0: switch (pk11Type) { michael@0: case CKK_RSA: keyType = rsaKey; break; michael@0: case CKK_DSA: keyType = dsaKey; break; michael@0: case CKK_DH: keyType = dhKey; break; michael@0: case CKK_KEA: keyType = fortezzaKey; break; michael@0: case CKK_EC: keyType = ecKey; break; michael@0: default: michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /* if the key is private, make sure we are authenticated to the michael@0: * token before we try to use it */ michael@0: isPrivate = (PRBool)PK11_HasAttributeSet(slot,privID,CKA_PRIVATE,PR_FALSE); michael@0: if (isPrivate) { michael@0: rv = PK11_Authenticate(slot, PR_TRUE, wincx); michael@0: if (rv != SECSuccess) { michael@0: return NULL; michael@0: } michael@0: } michael@0: michael@0: /* now we need to create space for the private key */ michael@0: arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) return NULL; michael@0: michael@0: privKey = (SECKEYPrivateKey *) michael@0: PORT_ArenaZAlloc(arena, sizeof(SECKEYPrivateKey)); michael@0: if (privKey == NULL) { michael@0: PORT_FreeArena(arena, PR_FALSE); michael@0: return NULL; michael@0: } michael@0: michael@0: privKey->arena = arena; michael@0: privKey->keyType = keyType; michael@0: privKey->pkcs11Slot = PK11_ReferenceSlot(slot); michael@0: privKey->pkcs11ID = privID; michael@0: privKey->pkcs11IsTemp = isTemp; michael@0: privKey->wincx = wincx; michael@0: michael@0: return privKey; michael@0: } michael@0: michael@0: michael@0: PK11SlotInfo * michael@0: PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key) michael@0: { michael@0: PK11SlotInfo *slot = key->pkcs11Slot; michael@0: slot = PK11_ReferenceSlot(slot); michael@0: return slot; michael@0: } michael@0: michael@0: /* michael@0: * Get the modulus length for raw parsing michael@0: */ michael@0: int michael@0: PK11_GetPrivateModulusLen(SECKEYPrivateKey *key) michael@0: { michael@0: CK_ATTRIBUTE theTemplate = { CKA_MODULUS, NULL, 0 }; michael@0: PK11SlotInfo *slot = key->pkcs11Slot; michael@0: CK_RV crv; michael@0: int length; michael@0: michael@0: switch (key->keyType) { michael@0: case rsaKey: michael@0: crv = PK11_GetAttributes(NULL, slot, key->pkcs11ID, &theTemplate, 1); michael@0: if (crv != CKR_OK) { michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: return -1; michael@0: } michael@0: length = theTemplate.ulValueLen; michael@0: if ( *(unsigned char *)theTemplate.pValue == 0) { michael@0: length--; michael@0: } michael@0: if (theTemplate.pValue != NULL) michael@0: PORT_Free(theTemplate.pValue); michael@0: return (int) length; michael@0: michael@0: case fortezzaKey: michael@0: case dsaKey: michael@0: case dhKey: michael@0: default: michael@0: break; michael@0: } michael@0: if (theTemplate.pValue != NULL) michael@0: PORT_Free(theTemplate.pValue); michael@0: PORT_SetError( SEC_ERROR_INVALID_KEY ); michael@0: return -1; michael@0: } michael@0: michael@0: michael@0: michael@0: /* michael@0: * take a private key in one pkcs11 module and load it into another: michael@0: * NOTE: the source private key is a rare animal... it can't be sensitive. michael@0: * This is used to do a key gen using one pkcs11 module and storing the michael@0: * result into another. michael@0: */ michael@0: static SECKEYPrivateKey * michael@0: pk11_loadPrivKeyWithFlags(PK11SlotInfo *slot,SECKEYPrivateKey *privKey, michael@0: SECKEYPublicKey *pubKey, PK11AttrFlags attrFlags) michael@0: { michael@0: CK_ATTRIBUTE privTemplate[] = { michael@0: /* class must be first */ michael@0: { CKA_CLASS, NULL, 0 }, michael@0: { CKA_KEY_TYPE, NULL, 0 }, michael@0: { CKA_ID, NULL, 0 }, michael@0: /* RSA - the attributes below will be replaced for other michael@0: * key types. michael@0: */ michael@0: { CKA_MODULUS, NULL, 0 }, michael@0: { CKA_PRIVATE_EXPONENT, NULL, 0 }, michael@0: { CKA_PUBLIC_EXPONENT, NULL, 0 }, michael@0: { CKA_PRIME_1, NULL, 0 }, michael@0: { CKA_PRIME_2, NULL, 0 }, michael@0: { CKA_EXPONENT_1, NULL, 0 }, michael@0: { CKA_EXPONENT_2, NULL, 0 }, michael@0: { CKA_COEFFICIENT, NULL, 0 }, michael@0: { CKA_DECRYPT, NULL, 0 }, michael@0: { CKA_DERIVE, NULL, 0 }, michael@0: { CKA_SIGN, NULL, 0 }, michael@0: { CKA_SIGN_RECOVER, NULL, 0 }, michael@0: { CKA_UNWRAP, NULL, 0 }, michael@0: /* reserve space for the attributes that may be michael@0: * specified in attrFlags */ michael@0: { CKA_TOKEN, NULL, 0 }, michael@0: { CKA_PRIVATE, NULL, 0 }, michael@0: { CKA_MODIFIABLE, NULL, 0 }, michael@0: { CKA_SENSITIVE, NULL, 0 }, michael@0: { CKA_EXTRACTABLE, NULL, 0 }, michael@0: #define NUM_RESERVED_ATTRS 5 /* number of reserved attributes above */ michael@0: }; michael@0: CK_BBOOL cktrue = CK_TRUE; michael@0: CK_BBOOL ckfalse = CK_FALSE; michael@0: CK_ATTRIBUTE *attrs = NULL, *ap; michael@0: const int templateSize = sizeof(privTemplate)/sizeof(privTemplate[0]); michael@0: PLArenaPool *arena; michael@0: CK_OBJECT_HANDLE objectID; michael@0: int i, count = 0; michael@0: int extra_count = 0; michael@0: CK_RV crv; michael@0: SECStatus rv; michael@0: PRBool token = ((attrFlags & PK11_ATTR_TOKEN) != 0); michael@0: michael@0: if (pk11_BadAttrFlags(attrFlags)) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return NULL; michael@0: } michael@0: michael@0: for (i=0; i < templateSize; i++) { michael@0: if (privTemplate[i].type == CKA_MODULUS) { michael@0: attrs= &privTemplate[i]; michael@0: count = i; michael@0: break; michael@0: } michael@0: } michael@0: PORT_Assert(attrs != NULL); michael@0: if (attrs == NULL) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return NULL; michael@0: } michael@0: michael@0: ap = attrs; michael@0: michael@0: switch (privKey->keyType) { michael@0: case rsaKey: michael@0: count = templateSize - NUM_RESERVED_ATTRS; michael@0: extra_count = count - (attrs - privTemplate); michael@0: break; michael@0: case dsaKey: michael@0: ap->type = CKA_PRIME; ap++; count++; extra_count++; michael@0: ap->type = CKA_SUBPRIME; ap++; count++; extra_count++; michael@0: ap->type = CKA_BASE; ap++; count++; extra_count++; michael@0: ap->type = CKA_VALUE; ap++; count++; extra_count++; michael@0: ap->type = CKA_SIGN; ap++; count++; extra_count++; michael@0: break; michael@0: case dhKey: michael@0: ap->type = CKA_PRIME; ap++; count++; extra_count++; michael@0: ap->type = CKA_BASE; ap++; count++; extra_count++; michael@0: ap->type = CKA_VALUE; ap++; count++; extra_count++; michael@0: ap->type = CKA_DERIVE; ap++; count++; extra_count++; michael@0: break; michael@0: case ecKey: michael@0: ap->type = CKA_EC_PARAMS; ap++; count++; extra_count++; michael@0: ap->type = CKA_VALUE; ap++; count++; extra_count++; michael@0: ap->type = CKA_DERIVE; ap++; count++; extra_count++; michael@0: ap->type = CKA_SIGN; ap++; count++; extra_count++; michael@0: break; michael@0: default: michael@0: count = 0; michael@0: extra_count = 0; michael@0: break; michael@0: } michael@0: michael@0: if (count == 0) { michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return NULL; michael@0: } michael@0: michael@0: arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) return NULL; michael@0: /* michael@0: * read out the old attributes. michael@0: */ michael@0: crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID, michael@0: privTemplate,count); michael@0: if (crv != CKR_OK) { michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: return NULL; michael@0: } michael@0: michael@0: /* Set token, private, modifiable, sensitive, and extractable */ michael@0: count += pk11_AttrFlagsToAttributes(attrFlags, &privTemplate[count], michael@0: &cktrue, &ckfalse); michael@0: michael@0: /* Not everyone can handle zero padded key values, give michael@0: * them the raw data as unsigned */ michael@0: for (ap=attrs; extra_count; ap++, extra_count--) { michael@0: pk11_SignedToUnsigned(ap); michael@0: } michael@0: michael@0: /* now Store the puppies */ michael@0: rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, privTemplate, michael@0: count, token, &objectID); michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: if (rv != SECSuccess) { michael@0: return NULL; michael@0: } michael@0: michael@0: /* try loading the public key */ michael@0: if (pubKey) { michael@0: PK11_ImportPublicKey(slot, pubKey, token); michael@0: if (pubKey->pkcs11Slot) { michael@0: PK11_FreeSlot(pubKey->pkcs11Slot); michael@0: pubKey->pkcs11Slot = NULL; michael@0: pubKey->pkcs11ID = CK_INVALID_HANDLE; michael@0: } michael@0: } michael@0: michael@0: /* build new key structure */ michael@0: return PK11_MakePrivKey(slot, privKey->keyType, !token, michael@0: objectID, privKey->wincx); michael@0: } michael@0: michael@0: static SECKEYPrivateKey * michael@0: pk11_loadPrivKey(PK11SlotInfo *slot,SECKEYPrivateKey *privKey, michael@0: SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive) michael@0: { michael@0: PK11AttrFlags attrFlags = 0; michael@0: if (token) { michael@0: attrFlags |= (PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE); michael@0: } else { michael@0: attrFlags |= (PK11_ATTR_SESSION | PK11_ATTR_PUBLIC); michael@0: } michael@0: if (sensitive) { michael@0: attrFlags |= PK11_ATTR_SENSITIVE; michael@0: } else { michael@0: attrFlags |= PK11_ATTR_INSENSITIVE; michael@0: } michael@0: return pk11_loadPrivKeyWithFlags(slot, privKey, pubKey, attrFlags); michael@0: } michael@0: michael@0: /* michael@0: * export this for PSM michael@0: */ michael@0: SECKEYPrivateKey * michael@0: PK11_LoadPrivKey(PK11SlotInfo *slot,SECKEYPrivateKey *privKey, michael@0: SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive) michael@0: { michael@0: return pk11_loadPrivKey(slot,privKey,pubKey,token,sensitive); michael@0: } michael@0: michael@0: michael@0: /* michael@0: * Use the token to generate a key pair. michael@0: */ michael@0: SECKEYPrivateKey * michael@0: PK11_GenerateKeyPairWithOpFlags(PK11SlotInfo *slot,CK_MECHANISM_TYPE type, michael@0: void *param, SECKEYPublicKey **pubKey, PK11AttrFlags attrFlags, michael@0: CK_FLAGS opFlags, CK_FLAGS opFlagsMask, void *wincx) michael@0: { michael@0: /* we have to use these native types because when we call PKCS 11 modules michael@0: * we have to make sure that we are using the correct sizes for all the michael@0: * parameters. */ michael@0: CK_BBOOL ckfalse = CK_FALSE; michael@0: CK_BBOOL cktrue = CK_TRUE; michael@0: CK_ULONG modulusBits; michael@0: CK_BYTE publicExponent[4]; michael@0: CK_ATTRIBUTE privTemplate[] = { michael@0: { CKA_SENSITIVE, NULL, 0}, michael@0: { CKA_TOKEN, NULL, 0}, michael@0: { CKA_PRIVATE, NULL, 0}, michael@0: { CKA_DERIVE, NULL, 0}, michael@0: { CKA_UNWRAP, NULL, 0}, michael@0: { CKA_SIGN, NULL, 0}, michael@0: { CKA_DECRYPT, NULL, 0}, michael@0: { CKA_EXTRACTABLE, NULL, 0}, michael@0: { CKA_MODIFIABLE, NULL, 0}, michael@0: }; michael@0: CK_ATTRIBUTE rsaPubTemplate[] = { michael@0: { CKA_MODULUS_BITS, NULL, 0}, michael@0: { CKA_PUBLIC_EXPONENT, NULL, 0}, michael@0: { CKA_TOKEN, NULL, 0}, michael@0: { CKA_DERIVE, NULL, 0}, michael@0: { CKA_WRAP, NULL, 0}, michael@0: { CKA_VERIFY, NULL, 0}, michael@0: { CKA_VERIFY_RECOVER, NULL, 0}, michael@0: { CKA_ENCRYPT, NULL, 0}, michael@0: { CKA_MODIFIABLE, NULL, 0}, michael@0: }; michael@0: CK_ATTRIBUTE dsaPubTemplate[] = { michael@0: { CKA_PRIME, NULL, 0 }, michael@0: { CKA_SUBPRIME, NULL, 0 }, michael@0: { CKA_BASE, NULL, 0 }, michael@0: { CKA_TOKEN, NULL, 0}, michael@0: { CKA_DERIVE, NULL, 0}, michael@0: { CKA_WRAP, NULL, 0}, michael@0: { CKA_VERIFY, NULL, 0}, michael@0: { CKA_VERIFY_RECOVER, NULL, 0}, michael@0: { CKA_ENCRYPT, NULL, 0}, michael@0: { CKA_MODIFIABLE, NULL, 0}, michael@0: }; michael@0: CK_ATTRIBUTE dhPubTemplate[] = { michael@0: { CKA_PRIME, NULL, 0 }, michael@0: { CKA_BASE, NULL, 0 }, michael@0: { CKA_TOKEN, NULL, 0}, michael@0: { CKA_DERIVE, NULL, 0}, michael@0: { CKA_WRAP, NULL, 0}, michael@0: { CKA_VERIFY, NULL, 0}, michael@0: { CKA_VERIFY_RECOVER, NULL, 0}, michael@0: { CKA_ENCRYPT, NULL, 0}, michael@0: { CKA_MODIFIABLE, NULL, 0}, michael@0: }; michael@0: CK_ATTRIBUTE ecPubTemplate[] = { michael@0: { CKA_EC_PARAMS, NULL, 0 }, michael@0: { CKA_TOKEN, NULL, 0}, michael@0: { CKA_DERIVE, NULL, 0}, michael@0: { CKA_WRAP, NULL, 0}, michael@0: { CKA_VERIFY, NULL, 0}, michael@0: { CKA_VERIFY_RECOVER, NULL, 0}, michael@0: { CKA_ENCRYPT, NULL, 0}, michael@0: { CKA_MODIFIABLE, NULL, 0}, michael@0: }; michael@0: SECKEYECParams * ecParams; michael@0: michael@0: /*CK_ULONG key_size = 0;*/ michael@0: CK_ATTRIBUTE *pubTemplate; michael@0: int privCount = 0; michael@0: int pubCount = 0; michael@0: PK11RSAGenParams *rsaParams; michael@0: SECKEYPQGParams *dsaParams; michael@0: SECKEYDHParams * dhParams; michael@0: CK_MECHANISM mechanism; michael@0: CK_MECHANISM test_mech; michael@0: CK_MECHANISM test_mech2; michael@0: CK_SESSION_HANDLE session_handle; michael@0: CK_RV crv; michael@0: CK_OBJECT_HANDLE privID,pubID; michael@0: SECKEYPrivateKey *privKey; michael@0: KeyType keyType; michael@0: PRBool restore; michael@0: int peCount,i; michael@0: CK_ATTRIBUTE *attrs; michael@0: CK_ATTRIBUTE *privattrs; michael@0: CK_ATTRIBUTE setTemplate; michael@0: CK_MECHANISM_INFO mechanism_info; michael@0: CK_OBJECT_CLASS keyClass; michael@0: SECItem *cka_id; michael@0: PRBool haslock = PR_FALSE; michael@0: PRBool pubIsToken = PR_FALSE; michael@0: PRBool token = ((attrFlags & PK11_ATTR_TOKEN) != 0); michael@0: /* subset of attrFlags applicable to the public key */ michael@0: PK11AttrFlags pubKeyAttrFlags = attrFlags & michael@0: (PK11_ATTR_TOKEN | PK11_ATTR_SESSION michael@0: | PK11_ATTR_MODIFIABLE | PK11_ATTR_UNMODIFIABLE); michael@0: michael@0: if (pk11_BadAttrFlags(attrFlags)) { michael@0: PORT_SetError( SEC_ERROR_INVALID_ARGS ); michael@0: return NULL; michael@0: } michael@0: michael@0: if (!param) { michael@0: PORT_SetError( SEC_ERROR_INVALID_ARGS ); michael@0: return NULL; michael@0: } michael@0: michael@0: /* michael@0: * The opFlags and opFlagMask parameters allow us to control the michael@0: * settings of the key usage attributes (CKA_ENCRYPT and friends). michael@0: * opFlagMask is set to one if the flag is specified in opFlags and michael@0: * zero if it is to take on a default value calculated by michael@0: * PK11_GenerateKeyPairWithOpFlags. michael@0: * opFlags specifies the actual value of the flag 1 or 0. michael@0: * Bits not corresponding to one bits in opFlagMask should be zero. michael@0: */ michael@0: michael@0: /* if we are trying to turn on a flag, it better be in the mask */ michael@0: PORT_Assert ((opFlags & ~opFlagsMask) == 0); michael@0: opFlags &= opFlagsMask; michael@0: michael@0: PORT_Assert(slot != NULL); michael@0: if (slot == NULL) { michael@0: PORT_SetError( SEC_ERROR_NO_MODULE); michael@0: return NULL; michael@0: } michael@0: michael@0: /* if our slot really doesn't do this mechanism, Generate the key michael@0: * in our internal token and write it out */ michael@0: if (!PK11_DoesMechanism(slot,type)) { michael@0: PK11SlotInfo *int_slot = PK11_GetInternalSlot(); michael@0: michael@0: /* don't loop forever looking for a slot */ michael@0: if (slot == int_slot) { michael@0: PK11_FreeSlot(int_slot); michael@0: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); michael@0: return NULL; michael@0: } michael@0: michael@0: /* if there isn't a suitable slot, then we can't do the keygen */ michael@0: if (int_slot == NULL) { michael@0: PORT_SetError( SEC_ERROR_NO_MODULE ); michael@0: return NULL; michael@0: } michael@0: michael@0: /* generate the temporary key to load */ michael@0: privKey = PK11_GenerateKeyPair(int_slot,type, param, pubKey, PR_FALSE, michael@0: PR_FALSE, wincx); michael@0: PK11_FreeSlot(int_slot); michael@0: michael@0: /* if successful, load the temp key into the new token */ michael@0: if (privKey != NULL) { michael@0: SECKEYPrivateKey *newPrivKey = pk11_loadPrivKeyWithFlags(slot, michael@0: privKey,*pubKey,attrFlags); michael@0: SECKEY_DestroyPrivateKey(privKey); michael@0: if (newPrivKey == NULL) { michael@0: SECKEY_DestroyPublicKey(*pubKey); michael@0: *pubKey = NULL; michael@0: } michael@0: return newPrivKey; michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: michael@0: mechanism.mechanism = type; michael@0: mechanism.pParameter = NULL; michael@0: mechanism.ulParameterLen = 0; michael@0: test_mech.pParameter = NULL; michael@0: test_mech.ulParameterLen = 0; michael@0: test_mech2.mechanism = CKM_INVALID_MECHANISM; michael@0: test_mech2.pParameter = NULL; michael@0: test_mech2.ulParameterLen = 0; michael@0: michael@0: /* set up the private key template */ michael@0: privattrs = privTemplate; michael@0: privattrs += pk11_AttrFlagsToAttributes(attrFlags, privattrs, michael@0: &cktrue, &ckfalse); michael@0: michael@0: /* set up the mechanism specific info */ michael@0: switch (type) { michael@0: case CKM_RSA_PKCS_KEY_PAIR_GEN: michael@0: case CKM_RSA_X9_31_KEY_PAIR_GEN: michael@0: rsaParams = (PK11RSAGenParams *)param; michael@0: if (rsaParams->pe == 0) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return NULL; michael@0: } michael@0: modulusBits = rsaParams->keySizeInBits; michael@0: peCount = 0; michael@0: michael@0: /* convert pe to a PKCS #11 string */ michael@0: for (i=0; i < 4; i++) { michael@0: if (peCount || (rsaParams->pe & michael@0: ((unsigned long)0xff000000L >> (i*8)))) { michael@0: publicExponent[peCount] = michael@0: (CK_BYTE)((rsaParams->pe >> (3-i)*8) & 0xff); michael@0: peCount++; michael@0: } michael@0: } michael@0: PORT_Assert(peCount != 0); michael@0: attrs = rsaPubTemplate; michael@0: PK11_SETATTRS(attrs, CKA_MODULUS_BITS, michael@0: &modulusBits, sizeof(modulusBits)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, michael@0: publicExponent, peCount);attrs++; michael@0: pubTemplate = rsaPubTemplate; michael@0: keyType = rsaKey; michael@0: test_mech.mechanism = CKM_RSA_PKCS; michael@0: break; michael@0: case CKM_DSA_KEY_PAIR_GEN: michael@0: dsaParams = (SECKEYPQGParams *)param; michael@0: attrs = dsaPubTemplate; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, dsaParams->prime.data, michael@0: dsaParams->prime.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_SUBPRIME, dsaParams->subPrime.data, michael@0: dsaParams->subPrime.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_BASE, dsaParams->base.data, michael@0: dsaParams->base.len); attrs++; michael@0: pubTemplate = dsaPubTemplate; michael@0: keyType = dsaKey; michael@0: test_mech.mechanism = CKM_DSA; michael@0: break; michael@0: case CKM_DH_PKCS_KEY_PAIR_GEN: michael@0: dhParams = (SECKEYDHParams *)param; michael@0: attrs = dhPubTemplate; michael@0: PK11_SETATTRS(attrs, CKA_PRIME, dhParams->prime.data, michael@0: dhParams->prime.len); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_BASE, dhParams->base.data, michael@0: dhParams->base.len); attrs++; michael@0: pubTemplate = dhPubTemplate; michael@0: keyType = dhKey; michael@0: test_mech.mechanism = CKM_DH_PKCS_DERIVE; michael@0: break; michael@0: case CKM_EC_KEY_PAIR_GEN: michael@0: ecParams = (SECKEYECParams *)param; michael@0: attrs = ecPubTemplate; michael@0: PK11_SETATTRS(attrs, CKA_EC_PARAMS, ecParams->data, michael@0: ecParams->len); attrs++; michael@0: pubTemplate = ecPubTemplate; michael@0: keyType = ecKey; michael@0: /* michael@0: * ECC supports 2 different mechanism types (unlike RSA, which michael@0: * supports different usages with the same mechanism). michael@0: * We may need to query both mechanism types and or the results michael@0: * together -- but we only do that if either the user has michael@0: * requested both usages, or not specified any usages. michael@0: */ michael@0: if ((opFlags & (CKF_SIGN|CKF_DERIVE)) == (CKF_SIGN|CKF_DERIVE)) { michael@0: /* We've explicitly turned on both flags, use both mechanism */ michael@0: test_mech.mechanism = CKM_ECDH1_DERIVE; michael@0: test_mech2.mechanism = CKM_ECDSA; michael@0: } else if (opFlags & CKF_SIGN) { michael@0: /* just do signing */ michael@0: test_mech.mechanism = CKM_ECDSA; michael@0: } else if (opFlags & CKF_DERIVE) { michael@0: /* just do ECDH */ michael@0: test_mech.mechanism = CKM_ECDH1_DERIVE; michael@0: } else { michael@0: /* neither was specified default to both */ michael@0: test_mech.mechanism = CKM_ECDH1_DERIVE; michael@0: test_mech2.mechanism = CKM_ECDSA; michael@0: } michael@0: break; michael@0: default: michael@0: PORT_SetError( SEC_ERROR_BAD_KEY ); michael@0: return NULL; michael@0: } michael@0: michael@0: /* now query the slot to find out how "good" a key we can generate */ michael@0: if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot); michael@0: crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID, michael@0: test_mech.mechanism,&mechanism_info); michael@0: /* michael@0: * EC keys are used in multiple different types of mechanism, if we michael@0: * are using dual use keys, we need to query the second mechanism michael@0: * as well. michael@0: */ michael@0: if (test_mech2.mechanism != CKM_INVALID_MECHANISM) { michael@0: CK_MECHANISM_INFO mechanism_info2; michael@0: CK_RV crv2; michael@0: michael@0: if (crv != CKR_OK) { michael@0: /* the first failed, make sure there is no trash in the michael@0: * mechanism flags when we or it below */ michael@0: mechanism_info.flags = 0; michael@0: } michael@0: crv2 = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID, michael@0: test_mech2.mechanism, &mechanism_info2); michael@0: if (crv2 == CKR_OK) { michael@0: crv = CKR_OK; /* succeed if either mechnaism info succeeds */ michael@0: /* combine the 2 sets of mechnanism flags */ michael@0: mechanism_info.flags |= mechanism_info2.flags; michael@0: } michael@0: } michael@0: if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot); michael@0: if ((crv != CKR_OK) || (mechanism_info.flags == 0)) { michael@0: /* must be old module... guess what it should be... */ michael@0: switch (test_mech.mechanism) { michael@0: case CKM_RSA_PKCS: michael@0: mechanism_info.flags = (CKF_SIGN | CKF_DECRYPT | michael@0: CKF_WRAP | CKF_VERIFY_RECOVER | CKF_ENCRYPT | CKF_WRAP); michael@0: break; michael@0: case CKM_DSA: michael@0: mechanism_info.flags = CKF_SIGN | CKF_VERIFY; michael@0: break; michael@0: case CKM_DH_PKCS_DERIVE: michael@0: mechanism_info.flags = CKF_DERIVE; michael@0: break; michael@0: case CKM_ECDH1_DERIVE: michael@0: mechanism_info.flags = CKF_DERIVE; michael@0: if (test_mech2.mechanism == CKM_ECDSA) { michael@0: mechanism_info.flags |= CKF_SIGN | CKF_VERIFY; michael@0: } michael@0: break; michael@0: case CKM_ECDSA: michael@0: mechanism_info.flags = CKF_SIGN | CKF_VERIFY; michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: } michael@0: /* now adjust our flags according to the user's key usage passed to us */ michael@0: mechanism_info.flags = (mechanism_info.flags & (~opFlagsMask)) | opFlags; michael@0: /* set the public key attributes */ michael@0: attrs += pk11_AttrFlagsToAttributes(pubKeyAttrFlags, attrs, michael@0: &cktrue, &ckfalse); michael@0: PK11_SETATTRS(attrs, CKA_DERIVE, michael@0: mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_WRAP, michael@0: mechanism_info.flags & CKF_WRAP ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY, michael@0: mechanism_info.flags & CKF_VERIFY ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_VERIFY_RECOVER, michael@0: mechanism_info.flags & CKF_VERIFY_RECOVER ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_ENCRYPT, michael@0: mechanism_info.flags & CKF_ENCRYPT? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); attrs++; michael@0: /* set the private key attributes */ michael@0: PK11_SETATTRS(privattrs, CKA_DERIVE, michael@0: mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); privattrs++; michael@0: PK11_SETATTRS(privattrs, CKA_UNWRAP, michael@0: mechanism_info.flags & CKF_UNWRAP ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); privattrs++; michael@0: PK11_SETATTRS(privattrs, CKA_SIGN, michael@0: mechanism_info.flags & CKF_SIGN ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); privattrs++; michael@0: PK11_SETATTRS(privattrs, CKA_DECRYPT, michael@0: mechanism_info.flags & CKF_DECRYPT ? &cktrue : &ckfalse, michael@0: sizeof(CK_BBOOL)); privattrs++; michael@0: michael@0: if (token) { michael@0: session_handle = PK11_GetRWSession(slot); michael@0: haslock = PK11_RWSessionHasLock(slot,session_handle); michael@0: restore = PR_TRUE; michael@0: } else { michael@0: session_handle = slot->session; michael@0: if (session_handle != CK_INVALID_SESSION) michael@0: PK11_EnterSlotMonitor(slot); michael@0: restore = PR_FALSE; michael@0: haslock = PR_TRUE; michael@0: } michael@0: michael@0: if (session_handle == CK_INVALID_SESSION) { michael@0: PORT_SetError(SEC_ERROR_BAD_DATA); michael@0: return NULL; michael@0: } michael@0: privCount = privattrs - privTemplate; michael@0: pubCount = attrs - pubTemplate; michael@0: crv = PK11_GETTAB(slot)->C_GenerateKeyPair(session_handle, &mechanism, michael@0: pubTemplate,pubCount,privTemplate,privCount,&pubID,&privID); michael@0: michael@0: if (crv != CKR_OK) { michael@0: if (restore) { michael@0: PK11_RestoreROSession(slot,session_handle); michael@0: } else PK11_ExitSlotMonitor(slot); michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: return NULL; michael@0: } michael@0: /* This locking code is dangerous and needs to be more thought michael@0: * out... the real problem is that we're holding the mutex open this long michael@0: */ michael@0: if (haslock) { PK11_ExitSlotMonitor(slot); } michael@0: michael@0: /* swap around the ID's for older PKCS #11 modules */ michael@0: keyClass = PK11_ReadULongAttribute(slot,pubID,CKA_CLASS); michael@0: if (keyClass != CKO_PUBLIC_KEY) { michael@0: CK_OBJECT_HANDLE tmp = pubID; michael@0: pubID = privID; michael@0: privID = tmp; michael@0: } michael@0: michael@0: *pubKey = PK11_ExtractPublicKey(slot, keyType, pubID); michael@0: if (*pubKey == NULL) { michael@0: if (restore) { michael@0: /* we may have to restore the mutex so it get's exited properly michael@0: * in RestoreROSession */ michael@0: if (haslock) PK11_EnterSlotMonitor(slot); michael@0: PK11_RestoreROSession(slot,session_handle); michael@0: } michael@0: PK11_DestroyObject(slot,pubID); michael@0: PK11_DestroyObject(slot,privID); michael@0: return NULL; michael@0: } michael@0: michael@0: /* set the ID to the public key so we can find it again */ michael@0: cka_id = pk11_MakeIDFromPublicKey(*pubKey); michael@0: pubIsToken = (PRBool)PK11_HasAttributeSet(slot,pubID, CKA_TOKEN,PR_FALSE); michael@0: michael@0: PK11_SETATTRS(&setTemplate, CKA_ID, cka_id->data, cka_id->len); michael@0: michael@0: if (haslock) { PK11_EnterSlotMonitor(slot); } michael@0: crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, privID, michael@0: &setTemplate, 1); michael@0: michael@0: if (crv == CKR_OK && pubIsToken) { michael@0: crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, pubID, michael@0: &setTemplate, 1); michael@0: } michael@0: michael@0: michael@0: if (restore) { michael@0: PK11_RestoreROSession(slot,session_handle); michael@0: } else { michael@0: PK11_ExitSlotMonitor(slot); michael@0: } michael@0: SECITEM_FreeItem(cka_id,PR_TRUE); michael@0: michael@0: michael@0: if (crv != CKR_OK) { michael@0: PK11_DestroyObject(slot,pubID); michael@0: PK11_DestroyObject(slot,privID); michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: *pubKey = NULL; michael@0: return NULL; michael@0: } michael@0: michael@0: privKey = PK11_MakePrivKey(slot,keyType,!token,privID,wincx); michael@0: if (privKey == NULL) { michael@0: SECKEY_DestroyPublicKey(*pubKey); michael@0: PK11_DestroyObject(slot,privID); michael@0: *pubKey = NULL; michael@0: return NULL; michael@0: } michael@0: michael@0: return privKey; michael@0: } michael@0: michael@0: SECKEYPrivateKey * michael@0: PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot,CK_MECHANISM_TYPE type, michael@0: void *param, SECKEYPublicKey **pubKey, PK11AttrFlags attrFlags, void *wincx) michael@0: { michael@0: return PK11_GenerateKeyPairWithOpFlags(slot,type,param,pubKey,attrFlags, michael@0: 0, 0, wincx); michael@0: } michael@0: michael@0: /* michael@0: * Use the token to generate a key pair. michael@0: */ michael@0: SECKEYPrivateKey * michael@0: PK11_GenerateKeyPair(PK11SlotInfo *slot,CK_MECHANISM_TYPE type, michael@0: void *param, SECKEYPublicKey **pubKey, PRBool token, michael@0: PRBool sensitive, void *wincx) michael@0: { michael@0: PK11AttrFlags attrFlags = 0; michael@0: michael@0: if (token) { michael@0: attrFlags |= PK11_ATTR_TOKEN; michael@0: } else { michael@0: attrFlags |= PK11_ATTR_SESSION; michael@0: } michael@0: if (sensitive) { michael@0: attrFlags |= (PK11_ATTR_SENSITIVE | PK11_ATTR_PRIVATE); michael@0: } else { michael@0: attrFlags |= (PK11_ATTR_INSENSITIVE | PK11_ATTR_PUBLIC); michael@0: } michael@0: return PK11_GenerateKeyPairWithFlags(slot, type, param, pubKey, michael@0: attrFlags, wincx); michael@0: } michael@0: michael@0: /* build a public KEA key from the public value */ michael@0: SECKEYPublicKey * michael@0: PK11_MakeKEAPubKey(unsigned char *keyData,int length) michael@0: { michael@0: SECKEYPublicKey *pubk; michael@0: SECItem pkData; michael@0: SECStatus rv; michael@0: PLArenaPool *arena; michael@0: michael@0: pkData.data = keyData; michael@0: pkData.len = length; michael@0: michael@0: arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); michael@0: if (arena == NULL) michael@0: return NULL; michael@0: michael@0: pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey)); michael@0: if (pubk == NULL) { michael@0: PORT_FreeArena (arena, PR_FALSE); michael@0: return NULL; michael@0: } michael@0: michael@0: pubk->arena = arena; michael@0: pubk->pkcs11Slot = 0; michael@0: pubk->pkcs11ID = CK_INVALID_HANDLE; michael@0: pubk->keyType = fortezzaKey; michael@0: rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.KEAKey, &pkData); michael@0: if (rv != SECSuccess) { michael@0: PORT_FreeArena (arena, PR_FALSE); michael@0: return NULL; michael@0: } michael@0: return pubk; michael@0: } michael@0: michael@0: /* michael@0: * NOTE: This function doesn't return a SECKEYPrivateKey struct to represent michael@0: * the new private key object. If it were to create a session object that michael@0: * could later be looked up by its nickname, it would leak a SECKEYPrivateKey. michael@0: * So isPerm must be true. michael@0: */ michael@0: SECStatus michael@0: PK11_ImportEncryptedPrivateKeyInfo(PK11SlotInfo *slot, michael@0: SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem, michael@0: SECItem *nickname, SECItem *publicValue, PRBool isPerm, michael@0: PRBool isPrivate, KeyType keyType, michael@0: unsigned int keyUsage, void *wincx) michael@0: { michael@0: if (!isPerm) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return SECFailure; michael@0: } michael@0: return PK11_ImportEncryptedPrivateKeyInfoAndReturnKey(slot, epki, michael@0: pwitem, nickname, publicValue, isPerm, isPrivate, keyType, michael@0: keyUsage, NULL, wincx); michael@0: } michael@0: michael@0: SECStatus michael@0: PK11_ImportEncryptedPrivateKeyInfoAndReturnKey(PK11SlotInfo *slot, michael@0: SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem, michael@0: SECItem *nickname, SECItem *publicValue, PRBool isPerm, michael@0: PRBool isPrivate, KeyType keyType, michael@0: unsigned int keyUsage, SECKEYPrivateKey **privk, michael@0: void *wincx) michael@0: { michael@0: CK_MECHANISM_TYPE pbeMechType; michael@0: SECItem *crypto_param = NULL; michael@0: PK11SymKey *key = NULL; michael@0: SECStatus rv = SECSuccess; michael@0: CK_MECHANISM_TYPE cryptoMechType; michael@0: SECKEYPrivateKey *privKey = NULL; michael@0: PRBool faulty3DES = PR_FALSE; michael@0: int usageCount = 0; michael@0: CK_KEY_TYPE key_type; michael@0: CK_ATTRIBUTE_TYPE *usage = NULL; michael@0: CK_ATTRIBUTE_TYPE rsaUsage[] = { michael@0: CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER }; michael@0: CK_ATTRIBUTE_TYPE dsaUsage[] = { CKA_SIGN }; michael@0: CK_ATTRIBUTE_TYPE dhUsage[] = { CKA_DERIVE }; michael@0: CK_ATTRIBUTE_TYPE ecUsage[] = { CKA_SIGN, CKA_DERIVE }; michael@0: if((epki == NULL) || (pwitem == NULL)) michael@0: return SECFailure; michael@0: michael@0: pbeMechType = PK11_AlgtagToMechanism(SECOID_FindOIDTag( michael@0: &epki->algorithm.algorithm)); michael@0: michael@0: switch (keyType) { michael@0: default: michael@0: case rsaKey: michael@0: key_type = CKK_RSA; michael@0: switch (keyUsage & (KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE)) { michael@0: case KU_KEY_ENCIPHERMENT: michael@0: usage = rsaUsage; michael@0: usageCount = 2; michael@0: break; michael@0: case KU_DIGITAL_SIGNATURE: michael@0: usage = &rsaUsage[2]; michael@0: usageCount = 2; michael@0: break; michael@0: case KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE: michael@0: case 0: /* default to everything */ michael@0: usage = rsaUsage; michael@0: usageCount = 4; michael@0: break; michael@0: } michael@0: break; michael@0: case dhKey: michael@0: key_type = CKK_DH; michael@0: usage = dhUsage; michael@0: usageCount = sizeof(dhUsage)/sizeof(dhUsage[0]); michael@0: break; michael@0: case dsaKey: michael@0: key_type = CKK_DSA; michael@0: usage = dsaUsage; michael@0: usageCount = sizeof(dsaUsage)/sizeof(dsaUsage[0]); michael@0: break; michael@0: case ecKey: michael@0: key_type = CKK_EC; michael@0: switch (keyUsage & (KU_DIGITAL_SIGNATURE|KU_KEY_AGREEMENT)) { michael@0: case KU_DIGITAL_SIGNATURE: michael@0: usage = ecUsage; michael@0: usageCount = 1; michael@0: break; michael@0: case KU_KEY_AGREEMENT: michael@0: usage = &ecUsage[1]; michael@0: usageCount = 1; michael@0: break; michael@0: case KU_DIGITAL_SIGNATURE|KU_KEY_AGREEMENT: michael@0: default: /* default to everything */ michael@0: usage = ecUsage; michael@0: usageCount = 2; michael@0: break; michael@0: } michael@0: break; michael@0: } michael@0: michael@0: try_faulty_3des: michael@0: michael@0: key = PK11_PBEKeyGen(slot, &epki->algorithm, pwitem, faulty3DES, wincx); michael@0: if (key == NULL) { michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: cryptoMechType = pk11_GetPBECryptoMechanism(&epki->algorithm, michael@0: &crypto_param, pwitem, faulty3DES); michael@0: if (cryptoMechType == CKM_INVALID_MECHANISM) { michael@0: rv = SECFailure; michael@0: goto done; michael@0: } michael@0: michael@0: michael@0: cryptoMechType = PK11_GetPadMechanism(cryptoMechType); michael@0: michael@0: PORT_Assert(usage != NULL); michael@0: PORT_Assert(usageCount != 0); michael@0: privKey = PK11_UnwrapPrivKey(slot, key, cryptoMechType, michael@0: crypto_param, &epki->encryptedData, michael@0: nickname, publicValue, isPerm, isPrivate, michael@0: key_type, usage, usageCount, wincx); michael@0: if(privKey) { michael@0: if (privk) { michael@0: *privk = privKey; michael@0: } else { michael@0: SECKEY_DestroyPrivateKey(privKey); michael@0: } michael@0: privKey = NULL; michael@0: rv = SECSuccess; michael@0: goto done; michael@0: } michael@0: michael@0: /* if we are unable to import the key and the pbeMechType is michael@0: * CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC, then it is possible that michael@0: * the encrypted blob was created with a buggy key generation method michael@0: * which is described in the PKCS 12 implementation notes. So we michael@0: * need to try importing via that method. michael@0: */ michael@0: if((pbeMechType == CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC) && (!faulty3DES)) { michael@0: /* clean up after ourselves before redoing the key generation. */ michael@0: michael@0: PK11_FreeSymKey(key); michael@0: key = NULL; michael@0: michael@0: if(crypto_param) { michael@0: SECITEM_ZfreeItem(crypto_param, PR_TRUE); michael@0: crypto_param = NULL; michael@0: } michael@0: michael@0: faulty3DES = PR_TRUE; michael@0: goto try_faulty_3des; michael@0: } michael@0: michael@0: /* key import really did fail */ michael@0: rv = SECFailure; michael@0: michael@0: done: michael@0: if(crypto_param != NULL) { michael@0: SECITEM_ZfreeItem(crypto_param, PR_TRUE); michael@0: } michael@0: michael@0: if(key != NULL) { michael@0: PK11_FreeSymKey(key); michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: SECKEYPrivateKeyInfo * michael@0: PK11_ExportPrivateKeyInfo(CERTCertificate *cert, void *wincx) michael@0: { michael@0: SECKEYPrivateKeyInfo *pki = NULL; michael@0: SECKEYPrivateKey *pk = PK11_FindKeyByAnyCert(cert, wincx); michael@0: if (pk != NULL) { michael@0: pki = PK11_ExportPrivKeyInfo(pk, wincx); michael@0: SECKEY_DestroyPrivateKey(pk); michael@0: } michael@0: return pki; michael@0: } michael@0: michael@0: SECKEYEncryptedPrivateKeyInfo * michael@0: PK11_ExportEncryptedPrivKeyInfo( michael@0: PK11SlotInfo *slot, /* optional, encrypt key in this slot */ michael@0: SECOidTag algTag, /* encrypt key with this algorithm */ michael@0: SECItem *pwitem, /* password for PBE encryption */ michael@0: SECKEYPrivateKey *pk, /* encrypt this private key */ michael@0: int iteration, /* interations for PBE alg */ michael@0: void *wincx) /* context for password callback ? */ michael@0: { michael@0: SECKEYEncryptedPrivateKeyInfo *epki = NULL; michael@0: PLArenaPool *arena = NULL; michael@0: SECAlgorithmID *algid; michael@0: SECOidTag pbeAlgTag = SEC_OID_UNKNOWN; michael@0: SECItem *crypto_param = NULL; michael@0: PK11SymKey *key = NULL; michael@0: SECKEYPrivateKey *tmpPK = NULL; michael@0: SECStatus rv = SECSuccess; michael@0: CK_RV crv; michael@0: CK_ULONG encBufLen; michael@0: CK_MECHANISM_TYPE pbeMechType; michael@0: CK_MECHANISM_TYPE cryptoMechType; michael@0: CK_MECHANISM cryptoMech; michael@0: michael@0: if (!pwitem || !pk) { michael@0: PORT_SetError(SEC_ERROR_INVALID_ARGS); michael@0: return NULL; michael@0: } michael@0: michael@0: algid = sec_pkcs5CreateAlgorithmID(algTag, SEC_OID_UNKNOWN, SEC_OID_UNKNOWN, michael@0: &pbeAlgTag, 0, NULL, iteration); michael@0: if (algid == NULL) { michael@0: return NULL; michael@0: } michael@0: michael@0: arena = PORT_NewArena(2048); michael@0: if (arena) michael@0: epki = PORT_ArenaZNew(arena, SECKEYEncryptedPrivateKeyInfo); michael@0: if(epki == NULL) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: epki->arena = arena; michael@0: michael@0: michael@0: /* if we didn't specify a slot, use the slot the private key was in */ michael@0: if (!slot) { michael@0: slot = pk->pkcs11Slot; michael@0: } michael@0: michael@0: /* if we specified a different slot, and the private key slot can do the michael@0: * pbe key gen, generate the key in the private key slot so we don't have michael@0: * to move it later */ michael@0: pbeMechType = PK11_AlgtagToMechanism(pbeAlgTag); michael@0: if (slot != pk->pkcs11Slot) { michael@0: if (PK11_DoesMechanism(pk->pkcs11Slot,pbeMechType)) { michael@0: slot = pk->pkcs11Slot; michael@0: } michael@0: } michael@0: key = PK11_PBEKeyGen(slot, algid, pwitem, PR_FALSE, wincx); michael@0: if (key == NULL) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: cryptoMechType = PK11_GetPBECryptoMechanism(algid, &crypto_param, pwitem); michael@0: if (cryptoMechType == CKM_INVALID_MECHANISM) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMechType); michael@0: cryptoMech.pParameter = crypto_param ? crypto_param->data : NULL; michael@0: cryptoMech.ulParameterLen = crypto_param ? crypto_param->len : 0; michael@0: michael@0: /* If the key isn't in the private key slot, move it */ michael@0: if (key->slot != pk->pkcs11Slot) { michael@0: PK11SymKey *newkey = pk11_CopyToSlot(pk->pkcs11Slot, michael@0: key->type, CKA_WRAP, key); michael@0: if (newkey == NULL) { michael@0: /* couldn't import the wrapping key, try exporting the michael@0: * private key */ michael@0: tmpPK = pk11_loadPrivKey(key->slot, pk, NULL, PR_FALSE, PR_TRUE); michael@0: if (tmpPK == NULL) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: pk = tmpPK; michael@0: } else { michael@0: /* free the old key and use the new key */ michael@0: PK11_FreeSymKey(key); michael@0: key = newkey; michael@0: } michael@0: } michael@0: michael@0: /* we are extracting an encrypted privateKey structure. michael@0: * which needs to be freed along with the buffer into which it is michael@0: * returned. eventually, we should retrieve an encrypted key using michael@0: * pkcs8/pkcs5. michael@0: */ michael@0: encBufLen = 0; michael@0: PK11_EnterSlotMonitor(pk->pkcs11Slot); michael@0: crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session, michael@0: &cryptoMech, key->objectID, pk->pkcs11ID, NULL, michael@0: &encBufLen); michael@0: PK11_ExitSlotMonitor(pk->pkcs11Slot); michael@0: if (crv != CKR_OK) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: epki->encryptedData.data = PORT_ArenaAlloc(arena, encBufLen); michael@0: if (!epki->encryptedData.data) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: PK11_EnterSlotMonitor(pk->pkcs11Slot); michael@0: crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session, michael@0: &cryptoMech, key->objectID, pk->pkcs11ID, michael@0: epki->encryptedData.data, &encBufLen); michael@0: PK11_ExitSlotMonitor(pk->pkcs11Slot); michael@0: epki->encryptedData.len = (unsigned int) encBufLen; michael@0: if(crv != CKR_OK) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: if(!epki->encryptedData.len) { michael@0: rv = SECFailure; michael@0: goto loser; michael@0: } michael@0: michael@0: rv = SECOID_CopyAlgorithmID(arena, &epki->algorithm, algid); michael@0: michael@0: loser: michael@0: if(crypto_param != NULL) { michael@0: SECITEM_ZfreeItem(crypto_param, PR_TRUE); michael@0: crypto_param = NULL; michael@0: } michael@0: michael@0: if(key != NULL) { michael@0: PK11_FreeSymKey(key); michael@0: } michael@0: if (tmpPK != NULL) { michael@0: SECKEY_DestroyPrivateKey(tmpPK); michael@0: } michael@0: SECOID_DestroyAlgorithmID(algid, PR_TRUE); michael@0: michael@0: if(rv == SECFailure) { michael@0: if(arena != NULL) { michael@0: PORT_FreeArena(arena, PR_TRUE); michael@0: } michael@0: epki = NULL; michael@0: } michael@0: michael@0: return epki; michael@0: } michael@0: michael@0: SECKEYEncryptedPrivateKeyInfo * michael@0: PK11_ExportEncryptedPrivateKeyInfo( michael@0: PK11SlotInfo *slot, /* optional, encrypt key in this slot */ michael@0: SECOidTag algTag, /* encrypt key with this algorithm */ michael@0: SECItem *pwitem, /* password for PBE encryption */ michael@0: CERTCertificate *cert, /* wrap priv key for this user cert */ michael@0: int iteration, /* interations for PBE alg */ michael@0: void *wincx) /* context for password callback ? */ michael@0: { michael@0: SECKEYEncryptedPrivateKeyInfo *epki = NULL; michael@0: SECKEYPrivateKey *pk = PK11_FindKeyByAnyCert(cert, wincx); michael@0: if (pk != NULL) { michael@0: epki = PK11_ExportEncryptedPrivKeyInfo(slot, algTag, pwitem, pk, michael@0: iteration, wincx); michael@0: SECKEY_DestroyPrivateKey(pk); michael@0: } michael@0: return epki; michael@0: } michael@0: michael@0: SECItem* michael@0: PK11_DEREncodePublicKey(const SECKEYPublicKey *pubk) michael@0: { michael@0: return SECKEY_EncodeDERSubjectPublicKeyInfo(pubk); michael@0: } michael@0: michael@0: char * michael@0: PK11_GetPrivateKeyNickname(SECKEYPrivateKey *privKey) michael@0: { michael@0: return PK11_GetObjectNickname(privKey->pkcs11Slot,privKey->pkcs11ID); michael@0: } michael@0: michael@0: char * michael@0: PK11_GetPublicKeyNickname(SECKEYPublicKey *pubKey) michael@0: { michael@0: return PK11_GetObjectNickname(pubKey->pkcs11Slot,pubKey->pkcs11ID); michael@0: } michael@0: michael@0: SECStatus michael@0: PK11_SetPrivateKeyNickname(SECKEYPrivateKey *privKey, const char *nickname) michael@0: { michael@0: return PK11_SetObjectNickname(privKey->pkcs11Slot, michael@0: privKey->pkcs11ID,nickname); michael@0: } michael@0: michael@0: SECStatus michael@0: PK11_SetPublicKeyNickname(SECKEYPublicKey *pubKey, const char *nickname) michael@0: { michael@0: return PK11_SetObjectNickname(pubKey->pkcs11Slot, michael@0: pubKey->pkcs11ID,nickname); michael@0: } michael@0: michael@0: SECKEYPQGParams * michael@0: PK11_GetPQGParamsFromPrivateKey(SECKEYPrivateKey *privKey) michael@0: { michael@0: CK_ATTRIBUTE pTemplate[] = { michael@0: { CKA_PRIME, NULL, 0 }, michael@0: { CKA_SUBPRIME, NULL, 0 }, michael@0: { CKA_BASE, NULL, 0 }, michael@0: }; michael@0: int pTemplateLen = sizeof(pTemplate)/sizeof(pTemplate[0]); michael@0: PLArenaPool *arena = NULL; michael@0: SECKEYPQGParams *params; michael@0: CK_RV crv; michael@0: michael@0: michael@0: arena = PORT_NewArena(2048); michael@0: if (arena == NULL) { michael@0: goto loser; michael@0: } michael@0: params=(SECKEYPQGParams *)PORT_ArenaZAlloc(arena,sizeof(SECKEYPQGParams)); michael@0: if (params == NULL) { michael@0: goto loser; michael@0: } michael@0: michael@0: crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID, michael@0: pTemplate, pTemplateLen); michael@0: if (crv != CKR_OK) { michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: goto loser; michael@0: } michael@0: michael@0: params->arena = arena; michael@0: params->prime.data = pTemplate[0].pValue; michael@0: params->prime.len = pTemplate[0].ulValueLen; michael@0: params->subPrime.data = pTemplate[1].pValue; michael@0: params->subPrime.len = pTemplate[1].ulValueLen; michael@0: params->base.data = pTemplate[2].pValue; michael@0: params->base.len = pTemplate[2].ulValueLen; michael@0: michael@0: return params; michael@0: michael@0: loser: michael@0: if (arena != NULL) { michael@0: PORT_FreeArena(arena,PR_FALSE); michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: SECKEYPrivateKey* michael@0: PK11_CopyTokenPrivKeyToSessionPrivKey(PK11SlotInfo *destSlot, michael@0: SECKEYPrivateKey *privKey) michael@0: { michael@0: CK_RV crv; michael@0: CK_OBJECT_HANDLE newKeyID; michael@0: michael@0: static const CK_BBOOL ckfalse = CK_FALSE; michael@0: static const CK_ATTRIBUTE template[1] = { michael@0: { CKA_TOKEN, (CK_BBOOL *)&ckfalse, sizeof ckfalse } michael@0: }; michael@0: michael@0: if (destSlot && destSlot != privKey->pkcs11Slot) { michael@0: SECKEYPrivateKey *newKey = michael@0: pk11_loadPrivKey(destSlot, michael@0: privKey, michael@0: NULL, /* pubKey */ michael@0: PR_FALSE, /* token */ michael@0: PR_FALSE);/* sensitive */ michael@0: if (newKey) michael@0: return newKey; michael@0: } michael@0: destSlot = privKey->pkcs11Slot; michael@0: PK11_Authenticate(destSlot, PR_TRUE, privKey->wincx); michael@0: PK11_EnterSlotMonitor(destSlot); michael@0: crv = PK11_GETTAB(destSlot)->C_CopyObject( destSlot->session, michael@0: privKey->pkcs11ID, michael@0: (CK_ATTRIBUTE *)template, michael@0: 1, &newKeyID); michael@0: PK11_ExitSlotMonitor(destSlot); michael@0: michael@0: if (crv != CKR_OK) { michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: return NULL; michael@0: } michael@0: michael@0: return PK11_MakePrivKey(destSlot, privKey->keyType, PR_TRUE /*isTemp*/, michael@0: newKeyID, privKey->wincx); michael@0: } michael@0: michael@0: SECKEYPrivateKey* michael@0: PK11_ConvertSessionPrivKeyToTokenPrivKey(SECKEYPrivateKey *privk, void* wincx) michael@0: { michael@0: PK11SlotInfo* slot = privk->pkcs11Slot; michael@0: CK_ATTRIBUTE template[1]; michael@0: CK_ATTRIBUTE *attrs = template; michael@0: CK_BBOOL cktrue = CK_TRUE; michael@0: CK_RV crv; michael@0: CK_OBJECT_HANDLE newKeyID; michael@0: CK_SESSION_HANDLE rwsession; michael@0: michael@0: PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue)); attrs++; michael@0: michael@0: PK11_Authenticate(slot, PR_TRUE, wincx); michael@0: rwsession = PK11_GetRWSession(slot); michael@0: if (rwsession == CK_INVALID_SESSION) { michael@0: PORT_SetError(SEC_ERROR_BAD_DATA); michael@0: return NULL; michael@0: } michael@0: crv = PK11_GETTAB(slot)->C_CopyObject(rwsession, privk->pkcs11ID, michael@0: template, 1, &newKeyID); michael@0: PK11_RestoreROSession(slot, rwsession); michael@0: michael@0: if (crv != CKR_OK) { michael@0: PORT_SetError( PK11_MapError(crv) ); michael@0: return NULL; michael@0: } michael@0: michael@0: return PK11_MakePrivKey(slot, nullKey /*KeyType*/, PR_FALSE /*isTemp*/, michael@0: newKeyID, NULL /*wincx*/); michael@0: } michael@0: michael@0: /* michael@0: * destroy a private key if there are no matching certs. michael@0: * this function also frees the privKey structure. michael@0: */ michael@0: SECStatus michael@0: PK11_DeleteTokenPrivateKey(SECKEYPrivateKey *privKey, PRBool force) michael@0: { michael@0: CERTCertificate *cert=PK11_GetCertFromPrivateKey(privKey); michael@0: SECStatus rv = SECWouldBlock; michael@0: michael@0: if (!cert || force) { michael@0: /* now, then it's safe for the key to go away */ michael@0: rv = PK11_DestroyTokenObject(privKey->pkcs11Slot,privKey->pkcs11ID); michael@0: } michael@0: if (cert) { michael@0: CERT_DestroyCertificate(cert); michael@0: } michael@0: SECKEY_DestroyPrivateKey(privKey); michael@0: return rv; michael@0: } michael@0: michael@0: /* michael@0: * destroy a private key if there are no matching certs. michael@0: * this function also frees the privKey structure. michael@0: */ michael@0: SECStatus michael@0: PK11_DeleteTokenPublicKey(SECKEYPublicKey *pubKey) michael@0: { michael@0: /* now, then it's safe for the key to go away */ michael@0: if (pubKey->pkcs11Slot == NULL) { michael@0: return SECFailure; michael@0: } michael@0: PK11_DestroyTokenObject(pubKey->pkcs11Slot,pubKey->pkcs11ID); michael@0: SECKEY_DestroyPublicKey(pubKey); michael@0: return SECSuccess; michael@0: } michael@0: michael@0: /* michael@0: * key call back structure. michael@0: */ michael@0: typedef struct pk11KeyCallbackStr { michael@0: SECStatus (* callback)(SECKEYPrivateKey *,void *); michael@0: void *callbackArg; michael@0: void *wincx; michael@0: } pk11KeyCallback; michael@0: michael@0: /* michael@0: * callback to map Object Handles to Private Keys; michael@0: */ michael@0: SECStatus michael@0: pk11_DoKeys(PK11SlotInfo *slot, CK_OBJECT_HANDLE keyHandle, void *arg) michael@0: { michael@0: SECStatus rv = SECSuccess; michael@0: SECKEYPrivateKey *privKey; michael@0: pk11KeyCallback *keycb = (pk11KeyCallback *) arg; michael@0: if (!arg) { michael@0: return SECFailure; michael@0: } michael@0: michael@0: privKey = PK11_MakePrivKey(slot,nullKey,PR_TRUE,keyHandle,keycb->wincx); michael@0: michael@0: if (privKey == NULL) { michael@0: return SECFailure; michael@0: } michael@0: michael@0: if (keycb->callback) { michael@0: rv = (*keycb->callback)(privKey,keycb->callbackArg); michael@0: } michael@0: michael@0: SECKEY_DestroyPrivateKey(privKey); michael@0: return rv; michael@0: } michael@0: michael@0: /*********************************************************************** michael@0: * PK11_TraversePrivateKeysInSlot michael@0: * michael@0: * Traverses all the private keys on a slot. michael@0: * michael@0: * INPUTS michael@0: * slot michael@0: * The PKCS #11 slot whose private keys you want to traverse. michael@0: * callback michael@0: * A callback function that will be called for each key. michael@0: * arg michael@0: * An argument that will be passed to the callback function. michael@0: */ michael@0: SECStatus michael@0: PK11_TraversePrivateKeysInSlot( PK11SlotInfo *slot, michael@0: SECStatus(* callback)(SECKEYPrivateKey*, void*), void *arg) michael@0: { michael@0: pk11KeyCallback perKeyCB; michael@0: pk11TraverseSlot perObjectCB; michael@0: CK_OBJECT_CLASS privkClass = CKO_PRIVATE_KEY; michael@0: CK_BBOOL ckTrue = CK_TRUE; michael@0: CK_ATTRIBUTE theTemplate[2]; michael@0: int templateSize = 2; michael@0: michael@0: theTemplate[0].type = CKA_CLASS; michael@0: theTemplate[0].pValue = &privkClass; michael@0: theTemplate[0].ulValueLen = sizeof(privkClass); michael@0: theTemplate[1].type = CKA_TOKEN; michael@0: theTemplate[1].pValue = &ckTrue; michael@0: theTemplate[1].ulValueLen = sizeof(ckTrue); michael@0: michael@0: if(slot==NULL) { michael@0: return SECSuccess; michael@0: } michael@0: michael@0: perObjectCB.callback = pk11_DoKeys; michael@0: perObjectCB.callbackArg = &perKeyCB; michael@0: perObjectCB.findTemplate = theTemplate; michael@0: perObjectCB.templateCount = templateSize; michael@0: perKeyCB.callback = callback; michael@0: perKeyCB.callbackArg = arg; michael@0: perKeyCB.wincx = NULL; michael@0: michael@0: return PK11_TraverseSlot(slot, &perObjectCB); michael@0: } michael@0: michael@0: /* michael@0: * return the private key with the given ID michael@0: */ michael@0: CK_OBJECT_HANDLE michael@0: pk11_FindPrivateKeyFromCertID(PK11SlotInfo *slot, SECItem *keyID) michael@0: { michael@0: CK_OBJECT_CLASS privKey = CKO_PRIVATE_KEY; michael@0: CK_ATTRIBUTE theTemplate[] = { michael@0: { CKA_ID, NULL, 0 }, michael@0: { CKA_CLASS, NULL, 0 }, michael@0: }; michael@0: /* if you change the array, change the variable below as well */ michael@0: int tsize = sizeof(theTemplate)/sizeof(theTemplate[0]); michael@0: CK_ATTRIBUTE *attrs = theTemplate; michael@0: michael@0: PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len ); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_CLASS, &privKey, sizeof(privKey)); michael@0: michael@0: return pk11_FindObjectByTemplate(slot,theTemplate,tsize); michael@0: } michael@0: michael@0: michael@0: SECKEYPrivateKey * michael@0: PK11_FindKeyByKeyID(PK11SlotInfo *slot, SECItem *keyID, void *wincx) michael@0: { michael@0: CK_OBJECT_HANDLE keyHandle; michael@0: SECKEYPrivateKey *privKey; michael@0: michael@0: keyHandle = pk11_FindPrivateKeyFromCertID(slot, keyID); michael@0: if (keyHandle == CK_INVALID_HANDLE) { michael@0: return NULL; michael@0: } michael@0: privKey = PK11_MakePrivKey(slot, nullKey, PR_TRUE, keyHandle, wincx); michael@0: return privKey; michael@0: } michael@0: michael@0: /* michael@0: * Generate a CKA_ID from the relevant public key data. The CKA_ID is generated michael@0: * from the pubKeyData by SHA1_Hashing it to produce a smaller CKA_ID (to make michael@0: * smart cards happy. michael@0: */ michael@0: SECItem * michael@0: PK11_MakeIDFromPubKey(SECItem *pubKeyData) michael@0: { michael@0: PK11Context *context; michael@0: SECItem *certCKA_ID; michael@0: SECStatus rv; michael@0: michael@0: if (pubKeyData->len <= SHA1_LENGTH) { michael@0: /* probably an already hashed value. The strongest known public michael@0: * key values <= 160 bits would be less than 40 bit symetric in michael@0: * strength. Don't hash them, just return the value. There are michael@0: * none at the time of this writing supported by previous versions michael@0: * of NSS, so change is binary compatible safe */ michael@0: return SECITEM_DupItem(pubKeyData); michael@0: } michael@0: michael@0: context = PK11_CreateDigestContext(SEC_OID_SHA1); michael@0: if (context == NULL) { michael@0: return NULL; michael@0: } michael@0: michael@0: rv = PK11_DigestBegin(context); michael@0: if (rv == SECSuccess) { michael@0: rv = PK11_DigestOp(context,pubKeyData->data,pubKeyData->len); michael@0: } michael@0: if (rv != SECSuccess) { michael@0: PK11_DestroyContext(context,PR_TRUE); michael@0: return NULL; michael@0: } michael@0: michael@0: certCKA_ID = (SECItem *)PORT_Alloc(sizeof(SECItem)); michael@0: if (certCKA_ID == NULL) { michael@0: PK11_DestroyContext(context,PR_TRUE); michael@0: return NULL; michael@0: } michael@0: michael@0: certCKA_ID->len = SHA1_LENGTH; michael@0: certCKA_ID->data = (unsigned char*)PORT_Alloc(certCKA_ID->len); michael@0: if (certCKA_ID->data == NULL) { michael@0: PORT_Free(certCKA_ID); michael@0: PK11_DestroyContext(context,PR_TRUE); michael@0: return NULL; michael@0: } michael@0: michael@0: rv = PK11_DigestFinal(context,certCKA_ID->data,&certCKA_ID->len, michael@0: SHA1_LENGTH); michael@0: PK11_DestroyContext(context,PR_TRUE); michael@0: if (rv != SECSuccess) { michael@0: SECITEM_FreeItem(certCKA_ID,PR_TRUE); michael@0: return NULL; michael@0: } michael@0: michael@0: return certCKA_ID; michael@0: } michael@0: michael@0: /* Looking for PK11_GetKeyIDFromPrivateKey? michael@0: * Call PK11_GetLowLevelKeyIDForPrivateKey instead. michael@0: */ michael@0: michael@0: michael@0: SECItem * michael@0: PK11_GetLowLevelKeyIDForPrivateKey(SECKEYPrivateKey *privKey) michael@0: { michael@0: return pk11_GetLowLevelKeyFromHandle(privKey->pkcs11Slot,privKey->pkcs11ID); michael@0: } michael@0: michael@0: static SECStatus michael@0: privateKeyListCallback(SECKEYPrivateKey *key, void *arg) michael@0: { michael@0: SECKEYPrivateKeyList *list = (SECKEYPrivateKeyList*)arg; michael@0: return SECKEY_AddPrivateKeyToListTail(list, SECKEY_CopyPrivateKey(key)); michael@0: } michael@0: michael@0: SECKEYPrivateKeyList* michael@0: PK11_ListPrivateKeysInSlot(PK11SlotInfo *slot) michael@0: { michael@0: SECStatus status; michael@0: SECKEYPrivateKeyList *keys; michael@0: michael@0: keys = SECKEY_NewPrivateKeyList(); michael@0: if(keys == NULL) return NULL; michael@0: michael@0: status = PK11_TraversePrivateKeysInSlot(slot, privateKeyListCallback, michael@0: (void*)keys); michael@0: michael@0: if( status != SECSuccess ) { michael@0: SECKEY_DestroyPrivateKeyList(keys); michael@0: keys = NULL; michael@0: } michael@0: michael@0: return keys; michael@0: } michael@0: michael@0: SECKEYPublicKeyList* michael@0: PK11_ListPublicKeysInSlot(PK11SlotInfo *slot, char *nickname) michael@0: { michael@0: CK_ATTRIBUTE findTemp[4]; michael@0: CK_ATTRIBUTE *attrs; michael@0: CK_BBOOL ckTrue = CK_TRUE; michael@0: CK_OBJECT_CLASS keyclass = CKO_PUBLIC_KEY; michael@0: int tsize = 0; michael@0: int objCount = 0; michael@0: CK_OBJECT_HANDLE *key_ids; michael@0: SECKEYPublicKeyList *keys; michael@0: int i,len; michael@0: michael@0: michael@0: attrs = findTemp; michael@0: PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++; michael@0: if (nickname) { michael@0: len = PORT_Strlen(nickname); michael@0: PK11_SETATTRS(attrs, CKA_LABEL, nickname, len); attrs++; michael@0: } michael@0: tsize = attrs - findTemp; michael@0: PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE)); michael@0: michael@0: key_ids = pk11_FindObjectsByTemplate(slot,findTemp,tsize,&objCount); michael@0: if (key_ids == NULL) { michael@0: return NULL; michael@0: } michael@0: keys = SECKEY_NewPublicKeyList(); michael@0: if (keys == NULL) { michael@0: PORT_Free(key_ids); michael@0: return NULL; michael@0: } michael@0: michael@0: for (i=0; i < objCount ; i++) { michael@0: SECKEYPublicKey *pubKey = michael@0: PK11_ExtractPublicKey(slot,nullKey,key_ids[i]); michael@0: if (pubKey) { michael@0: SECKEY_AddPublicKeyToListTail(keys, pubKey); michael@0: } michael@0: } michael@0: michael@0: PORT_Free(key_ids); michael@0: return keys; michael@0: } michael@0: michael@0: SECKEYPrivateKeyList* michael@0: PK11_ListPrivKeysInSlot(PK11SlotInfo *slot, char *nickname, void *wincx) michael@0: { michael@0: CK_ATTRIBUTE findTemp[4]; michael@0: CK_ATTRIBUTE *attrs; michael@0: CK_BBOOL ckTrue = CK_TRUE; michael@0: CK_OBJECT_CLASS keyclass = CKO_PRIVATE_KEY; michael@0: int tsize = 0; michael@0: int objCount = 0; michael@0: CK_OBJECT_HANDLE *key_ids; michael@0: SECKEYPrivateKeyList *keys; michael@0: int i,len; michael@0: michael@0: michael@0: attrs = findTemp; michael@0: PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++; michael@0: PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++; michael@0: if (nickname) { michael@0: len = PORT_Strlen(nickname); michael@0: PK11_SETATTRS(attrs, CKA_LABEL, nickname, len); attrs++; michael@0: } michael@0: tsize = attrs - findTemp; michael@0: PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE)); michael@0: michael@0: key_ids = pk11_FindObjectsByTemplate(slot,findTemp,tsize,&objCount); michael@0: if (key_ids == NULL) { michael@0: return NULL; michael@0: } michael@0: keys = SECKEY_NewPrivateKeyList(); michael@0: if (keys == NULL) { michael@0: PORT_Free(key_ids); michael@0: return NULL; michael@0: } michael@0: michael@0: for (i=0; i < objCount ; i++) { michael@0: SECKEYPrivateKey *privKey = michael@0: PK11_MakePrivKey(slot,nullKey,PR_TRUE,key_ids[i],wincx); michael@0: SECKEY_AddPrivateKeyToListTail(keys, privKey); michael@0: } michael@0: michael@0: PORT_Free(key_ids); michael@0: return keys; michael@0: } michael@0: