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