/* This Source Code Form is subject to the terms of the Mozilla Public *License,v.2.0.IfacopyoftheMPLwasnotdistributedwiththis
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* *ThisfilePK11Contextswhichareusedinmultiparthashing, *encryption/decryption,andsigning/vericationoperations.
*/
/* *themonitors...
*/ void
PK11_EnterContextMonitor(PK11Context *cx)
{ /* if we own the session and our slot is ThreadSafe, only monitor
* the Context */ if ((cx->ownSession) && (cx->slot->isThreadSafe)) { /* Should this use monitors instead? */
PR_Lock(cx->sessionLock);
} else {
PK11_EnterSlotMonitor(cx->slot);
}
}
void
PK11_ExitContextMonitor(PK11Context *cx)
{ /* if we own the session and our slot is ThreadSafe, only monitor
* the Context */ if ((cx->ownSession) && (cx->slot->isThreadSafe)) { /* Should this use monitors instead? */
PR_Unlock(cx->sessionLock);
} else {
PK11_ExitSlotMonitor(cx->slot);
}
}
/* *FreeupaCipherContext
*/ void
PK11_DestroyContext(PK11Context *context, PRBool freeit)
{
pk11_CloseSession(context->slot, context->session, context->ownSession); /* initialize the critical fields of the context */ if (context->savedData != NULL)
PORT_Free(context->savedData); if (context->key)
PK11_FreeSymKey(context->key); if (context->param && context->param != &pk11_null_params)
SECITEM_FreeItem(context->param, PR_TRUE); if (context->sessionLock)
PR_DestroyLock(context->sessionLock);
PK11_FreeSlot(context->slot); if (freeit)
PORT_Free(context);
}
context->ivCounter = 0;
context->ivMaxCount = 0;
context->ivFixedBits = 0;
context->ivLen = 0;
context->ivGen = CKG_NO_GENERATE;
context->simulate_mechanism = (mech)->mechanism;
context->simulate_message = PR_FALSE; /* check that we can do the Message interface. We need to check *foreither1)areweusingaPKCS#11v3interfaceand2)isthe *Messageflagsetonthemechanism.Ifeitherisfalsewesimulate *themessageinterfacefortheEncryptandDecryptcasesusingthe *PKCS#11V2interface. *SignandverifydonothaveV2interfaces,sowegoaheadandfail
* if those cases */ if ((PK11_CheckPKCS11Version(slot, 3, 0, PR_TRUE) >= 0) &&
PK11_DoesMechanismFlag(slot, (mech)->mechanism, flags)) {
PK11_EnterContextMonitor(context);
crv = (*initFunc)((context)->session, (mech), (context)->objectID);
PK11_ExitContextMonitor(context); if ((crv == CKR_FUNCTION_NOT_SUPPORTED) ||
(crv == CKR_MECHANISM_INVALID)) { /* we have a 3.0 interface, and the flag was set (or ignored)
* but the implementation was not there, use the V2 interface */
crv = (scrv);
context->simulate_message = PR_TRUE;
}
} else {
crv = (scrv);
context->simulate_message = PR_TRUE;
} return crv;
}
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv)); return SECFailure;
}
/* handle the case where the token is using the old NSS mechanism */ if (context->simulate_message &&
!PK11_DoesMechanism(context->slot, context->simulate_mechanism)) { if ((context->simulate_mechanism == CKM_CHACHA20_POLY1305) &&
PK11_DoesMechanism(context->slot, CKM_NSS_CHACHA20_POLY1305)) {
context->simulate_mechanism = CKM_NSS_CHACHA20_POLY1305;
} else {
PORT_SetError(PK11_MapError(CKR_MECHANISM_INVALID)); return SECFailure;
}
}
/* *handlesessionstarvationcase..useourlastsessiontomultiplex
*/ if (!context->ownSession) {
PK11_EnterContextMonitor(context);
context->savedData = pk11_saveContext(context, context->savedData,
&context->savedLength); if (context->savedData == NULL)
rv = SECFailure; /* clear out out session for others to use */
pk11_Finalize(context);
PK11_ExitContextMonitor(context);
} return rv;
}
/* *Testinginterfaces,notforgeneraluse.Thisfunctionforces *anAEADcontextintosimulationmodeeventhoughthetargettoken *canalreadydoPKCS#11v3.0Message(i.e.softoken).
*/
SECStatus
_PK11_ContextSetAEADSimulation(PK11Context *context)
{
CK_RV crv; /* only message encrypt and message decrypt contexts can be simulated */ if ((context->operation != (CKA_NSS_MESSAGE | CKA_ENCRYPT)) &&
(context->operation != (CKA_NSS_MESSAGE | CKA_DECRYPT))) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
} /* if we are already simulating, return */ if (context->simulate_message) { return SECSuccess;
} /* we need to shutdown the existing AEAD operation */ switch (context->operation) { case CKA_NSS_MESSAGE | CKA_ENCRYPT:
crv = PK11_GETTAB(context->slot)->C_MessageEncryptFinal(context->session); break; case CKA_NSS_MESSAGE | CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_MessageDecryptFinal(context->session); break; default:
PORT_SetError(SEC_ERROR_NOT_INITIALIZED); return SECFailure;
} if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv)); return SECFailure;
}
context->simulate_message = PR_TRUE; return SECSuccess;
}
/* now deal with the fortezza hack... the fortezza hack is an attempt *togetaroundtheissueofthecardnotallowingyoutodoaFORTEZZA *LoadIV/Encrypt,whichwasaddedbecausesuchacombinationcouldbe *usetocircumventthekeyescrowsystem.UnfortunatelySSLneedsto *dothiskindofoperation,soinSSLwedoaloadIV(toverifyit), *ThenGenerateIV,andthroughawaythefirst8bytesoneitherside
* of the connection.*/
context->fortezzaHack = PR_FALSE; if (type == CKM_SKIPJACK_CBC64) { if (symKey && (symKey->origin == PK11_OriginFortezzaHack)) {
context->fortezzaHack = PR_TRUE;
}
}
/* initialize the critical fields of the context */
context->operation = operation; /* If we were given a symKey, keep our own reference to it so *thatthekeydoesn'tdisappearinthemiddleoftheoperation *ifthecallerfreesit.PublicandPrivatekeysarenotreference *counted,sothecallerjusthastokeephiscopiesarounduntil
* the operation completes */
context->key = symKey ? PK11_ReferenceSymKey(symKey) : NULL;
context->objectID = objectID;
context->slot = PK11_ReferenceSlot(slot);
context->session = pk11_GetNewSession(slot, &context->ownSession);
context->pwArg = pwArg; /* get our session */
context->savedData = NULL;
/* save the parameters so that some digesting stuff can do multiple
* begins on a single context */
context->type = type; if (param) { if (param->len > 0) {
context->param = SECITEM_DupItem(param);
} else {
context->param = (SECItem *)&pk11_null_params;
}
} else {
PORT_SetError(SEC_ERROR_INVALID_ARGS);
context->param = NULL;
}
context->init = PR_FALSE;
context->sessionLock = PR_NewLock(); if ((context->param == NULL) || (context->sessionLock == NULL)) {
PK11_DestroyContext(context, PR_TRUE); return NULL;
}
/* if this slot doesn't support the mechanism, go to a slot that does */
newKey = pk11_ForceSlot(symKey, type, operation); if (newKey == NULL) {
PK11_ReferenceSymKey(symKey);
} else {
symKey = newKey;
}
/* Context keeps its reference to the symKey, so it's safe to *freeourreferencewewearethrough,eventhoughwemayhave
* created the key using pk11_ForceSlot. */
context = pk11_CreateNewContextInSlot(type, symKey->slot, operation, symKey,
symKey->objectID, param, NULL,
symKey->cx);
PK11_FreeSymKey(symKey); return context;
}
/* To support multipart public key operations (like hash/verify operations),
* we need to create contexts with public keys. */
PK11Context *
PK11_CreateSignatureContextByPubKey(CK_MECHANISM_TYPE type,
CK_ATTRIBUTE_TYPE operation,
SECKEYPublicKey *pubKey, const SECItem *param, const SECItem *sig, void *pwArg)
{
PK11SlotInfo *slot = pubKey->pkcs11Slot;
SECItem nullparam = { 0, 0, 0 };
/* if this slot doesn't support the mechanism, go to a slot that does */ /* public keys have all their data in the public key data structure, *sothere'snoneedtoexporttheoldkey,justimportthisone.The
* import manages consistancy of the public key data structure */ if (slot == NULL || !PK11_DoesMechanism(slot, type)) {
CK_OBJECT_HANDLE objectID;
slot = PK11_GetBestSlot(type, NULL); if (slot == NULL) { return NULL;
}
objectID = PK11_ImportPublicKey(slot, pubKey, PR_FALSE);
PK11_FreeSlot(slot); if (objectID == CK_INVALID_HANDLE) { return NULL;
}
}
/* unlike symkeys, we accept a NULL parameter. map a null parameter *totheemptyparameter.Thismatchesthesemanticsof
* PK11_VerifyWithMechanism */ return pk11_CreateNewContextInSlot(type, pubKey->pkcs11Slot, operation,
NULL, pubKey->pkcs11ID,
param ? param : &nullparam, sig, pwArg);
}
/* traditional PK11_CreateContextByPubKey just doesn't have the signature.
* This will work unless operation is CKA_NSS_VERIFY_SIGNATURE */
PK11Context *
PK11_CreateContextByPubKey(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE operation,
SECKEYPublicKey *pubKey, const SECItem *param, void *pwArg)
{ return PK11_CreateSignatureContextByPubKey(type, operation, pubKey, param,
NULL, pwArg);
}
/* To support multipart private key operations (like hash/sign operations),
* we need to create contexts with private keys. */
PK11Context *
PK11_CreateContextByPrivKey(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE operation,
SECKEYPrivateKey *privKey, const SECItem *param)
{
SECItem nullparam = { 0, 0, 0 }; /* Private keys are generally not movable. If the token the *privatekeylivesoncan'tdotheoperation,generallyweare *stuckanyway.Sononeedtotrytomanipulatethekeyinto
* another token */
/* if this slot doesn't support the mechanism, go to a slot that does */ /* unlike symkeys, we accept a NULL parameter. map a null parameter *totheemptyparameter.Thismatchesthesemanticsof
* PK11_SignWithMechanism */ return pk11_CreateNewContextInSlot(type, privKey->pkcs11Slot, operation,
NULL, privKey->pkcs11ID,
param ? param : &nullparam, NULL,
privKey->wincx);
}
/* *Digestcontextsdon'tneedkeys,butthedoneedtofindaslot. *MacingshouldusePK11_CreateContextBySymKey.
*/
PK11Context *
PK11_CreateDigestContext(SECOidTag hashAlg)
{ /* digesting has to work without authentication to the slot */
CK_MECHANISM_TYPE type;
PK11SlotInfo *slot;
PK11Context *context;
SECItem param;
type = PK11_AlgtagToMechanism(hashAlg);
slot = PK11_GetBestSlot(type, NULL); if (slot == NULL) {
PORT_SetError(SEC_ERROR_NO_MODULE); return NULL;
}
/* maybe should really be PK11_GenerateNewParam?? */
param.data = NULL;
param.len = 0;
param.type = 0;
/* now clone the save state. First we need to find the save state *oftheoldsession.Iftheoldcontextownsit'ssession,
* the state needs to be saved, otherwise the state is in saveData. */ if (old->ownSession) {
PK11_EnterContextMonitor(old);
data = pk11_saveContext(old, NULL, &len);
PK11_ExitContextMonitor(old);
needFree = PR_TRUE;
} else {
data = old->savedData;
len = old->savedLength;
}
if (data == NULL) {
PK11_DestroyContext(newcx, PR_TRUE); return NULL;
}
/* now copy that state into our new context. Again we have different *workifthenewcontextownsit'sownsession.Ifitdoes,we *restorethestategatheredabove.Ifitdoesn't,wecopythe
* saveData pointer... */ if (newcx->ownSession) {
PK11_EnterContextMonitor(newcx);
rv = pk11_restoreContext(newcx, data, len);
PK11_ExitContextMonitor(newcx);
} else {
PORT_Assert(newcx->savedData != NULL); if ((newcx->savedData == NULL) || (newcx->savedLength < len)) {
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
rv = SECFailure;
} else {
PORT_Memcpy(newcx->savedData, data, len);
newcx->savedLength = len;
}
}
rv = PK11_DigestOp(context, in, len); if (rv != SECSuccess) {
PK11_DestroyContext(context, PR_TRUE); return rv;
}
/* XXX This really should have been an argument to this function! */
max_length = HASH_ResultLenByOidTag(hashAlg);
PORT_Assert(max_length); if (!max_length)
max_length = HASH_LENGTH_MAX;
/* if we ran out of session, we need to restore our previously stored *state.
*/
PK11_EnterContextMonitor(context); if (!context->ownSession) {
rv = pk11_restoreContext(context, context->savedData,
context->savedLength); if (rv != SECSuccess) {
PK11_ExitContextMonitor(context); return rv;
}
}
/* *Thefortezzahackistosend8extrabytesonthefirstencryptedand *losethemonthefirstdecrypt.
*/ if (context->fortezzaHack) { unsignedchar random[8]; if (context->operation == CKA_ENCRYPT) {
PK11_ExitContextMonitor(context);
rv = PK11_GenerateRandom(random, sizeof(random));
PK11_EnterContextMonitor(context);
/* since we are offseting the output, we can't encrypt back into *thesamebuffer...allocateatemporarybufferjustforthis
* call. */
allocOut = out = (unsignedchar *)PORT_Alloc(maxout); if (out == NULL) {
PK11_ExitContextMonitor(context); return SECFailure;
}
crv = PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session, random, sizeof(random), out, &length);
if (context->ivCounter != 0) { /* If we've already generated a message, make sure all subsequent
* messages are using the same generator */ if ((context->ivGen != ivgen) ||
(context->ivFixedBits != fixedBits) ||
(context->ivLen != ivLen)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
} else { /* remember these values */
context->ivGen = ivgen;
context->ivFixedBits = fixedBits;
context->ivLen = ivLen; /* now calculate how may bits of IV we have to supply */
flexBits = ivLen * PR_BITS_PER_BYTE; /* first make sure we aren't going to overflow */ if (flexBits < fixedBits) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
flexBits -= fixedBits; /* if we are generating a random number reduce the acceptable bits to
* avoid birthday attacks */ if (ivgen == CKG_GENERATE_RANDOM) { if (flexBits <= GCMIV_RANDOM_BIRTHDAY_BITS) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
} /* see freebl/blapit.h for how GCMIV_RANDOM_BIRTHDAY_BITS is
* calculated. */
flexBits -= GCMIV_RANDOM_BIRTHDAY_BITS;
flexBits = flexBits >> 1;
} if (flexBits == 0) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
} /* Turn those bits into the number of IV's we can safely return */ if (flexBits >= sizeof(context->ivMaxCount) * PR_BITS_PER_BYTE) {
context->ivMaxCount = PR_UINT64(0xffffffffffffffff);
} else {
context->ivMaxCount = (PR_UINT64(1) << flexBits);
}
}
/* no generate, accept the IV from the source */ if (ivgen == CKG_NO_GENERATE) {
context->ivCounter = 1; return SECSuccess;
}
/* make sure we haven't exceeded the number of IVs we can return
* for this key, generator, and IV size */ if (context->ivCounter >= context->ivMaxCount) { /* use a unique error from just bad user input */
PORT_SetError(SEC_ERROR_EXTRA_INPUT); return SECFailure;
}
/* build to mask to handle the first byte of the IV */
ivOffset = fixedBits / PR_BITS_PER_BYTE;
ivMask = 0xff >> ((PR_BITS_PER_BYTE - (fixedBits & 7)) & 7);
ivNewCount = ivLen - ivOffset;
/* finally generate the IV */ switch (ivgen) { case CKG_GENERATE: /* default to counter */ case CKG_GENERATE_COUNTER:
iv[ivOffset] = (iv[ivOffset] & ~ivMask) |
(PORT_GET_BYTE_BE(context->ivCounter, 0, ivNewCount) & ivMask); for (i = 1; i < ivNewCount; i++) {
iv[ivOffset + i] =
PORT_GET_BYTE_BE(context->ivCounter, i, ivNewCount);
} break; case CKG_GENERATE_COUNTER_XOR:
iv[ivOffset] ^=
(PORT_GET_BYTE_BE(context->ivCounter, 0, ivNewCount) & ivMask); for (i = 1; i < ivNewCount; i++) {
iv[ivOffset + i] ^=
PORT_GET_BYTE_BE(context->ivCounter, i, ivNewCount);
} break; case CKG_GENERATE_RANDOM:
ivSave = iv[ivOffset] & ~ivMask;
rv = PK11_GenerateRandom(iv + ivOffset, ivNewCount);
iv[ivOffset] = ivSave | (iv[ivOffset] & ivMask); if (rv != SECSuccess) { return rv;
} break;
}
context->ivCounter++; return SECSuccess;
}
/* *PKCS#11v2.40didnothaveamessageinterface.Ifourmodulecan't
* do the message interface use the old method of doing AEAD */ static SECStatus
pk11_AEADSimulateOp(PK11Context *context, void *params, int paramslen, constunsignedchar *aad, int aadlen, unsignedchar *out, int *outlen, int maxout, constunsignedchar *in, int inlen)
{ unsignedint length = maxout;
SECStatus rv = SECSuccess; unsignedchar *saveOut = out; unsignedchar *allocOut = NULL;
*outlen = 0; /* figure out if we are encrypting or decrypting, as tags are
* handled differently in both */ switch (context->operation) { case CKA_NSS_MESSAGE | CKA_ENCRYPT:
encrypt = PR_TRUE; break; case CKA_NSS_MESSAGE | CKA_DECRYPT:
encrypt = PR_FALSE; break; default:
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
switch (mechanism) { case CKM_CHACHA20_POLY1305: case CKM_SALSA20_POLY1305: if (paramslen != sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
chacha_poly_message =
(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS *)params;
chacha_poly.pNonce = chacha_poly_message->pNonce;
chacha_poly.ulNonceLen = chacha_poly_message->ulNonceLen;
chacha_poly.pAAD = (CK_BYTE_PTR)aad;
chacha_poly.ulAADLen = aadlen;
tag = chacha_poly_message->pTag;
taglen = 16;
sim_params.data = (unsignedchar *)&chacha_poly;
sim_params.len = sizeof(chacha_poly); /* SALSA20_POLY1305 and CHACHA20_POLY1305 do not generate the iv
* internally, don't simulate it either */ break; case CKM_NSS_CHACHA20_POLY1305: if (paramslen != sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
chacha_poly_message =
(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS *)params;
tag = chacha_poly_message->pTag;
taglen = 16;
nss_chacha_poly.pNonce = chacha_poly_message->pNonce;
nss_chacha_poly.ulNonceLen = chacha_poly_message->ulNonceLen;
nss_chacha_poly.pAAD = (CK_BYTE_PTR)aad;
nss_chacha_poly.ulAADLen = aadlen;
nss_chacha_poly.ulTagLen = taglen;
sim_params.data = (unsignedchar *)&nss_chacha_poly;
sim_params.len = sizeof(nss_chacha_poly); /* CKM_NSS_CHACHA20_POLY1305 does not generate the iv
* internally, don't simulate it either */ break; case CKM_AES_CCM: if (paramslen != sizeof(CK_CCM_MESSAGE_PARAMS)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
ccm_message = (CK_CCM_MESSAGE_PARAMS *)params;
ccm.ulDataLen = ccm_message->ulDataLen;
ccm.pNonce = ccm_message->pNonce;
ccm.ulNonceLen = ccm_message->ulNonceLen;
ccm.pAAD = (CK_BYTE_PTR)aad;
ccm.ulAADLen = aadlen;
ccm.ulMACLen = ccm_message->ulMACLen;
tag = ccm_message->pMAC;
taglen = ccm_message->ulMACLen;
sim_params.data = (unsignedchar *)&ccm;
sim_params.len = sizeof(ccm); if (encrypt) { /* simulate generating the IV */
rv = pk11_GenerateIV(context, ccm_message->nonceGenerator,
ccm_message->ulNonceFixedBits,
ccm_message->pNonce,
ccm_message->ulNonceLen); if (rv != SECSuccess) { return rv;
}
} break; case CKM_AES_GCM: if (paramslen != sizeof(CK_GCM_MESSAGE_PARAMS)) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
gcm_message = (CK_GCM_MESSAGE_PARAMS *)params;
gcm.pIv = gcm_message->pIv;
gcm.ulIvLen = gcm_message->ulIvLen;
gcm.ulIvBits = gcm.ulIvLen * PR_BITS_PER_BYTE;
gcm.pAAD = (CK_BYTE_PTR)aad;
gcm.ulAADLen = aadlen;
gcm.ulTagBits = gcm_message->ulTagBits;
tag = gcm_message->pTag;
taglen = (gcm_message->ulTagBits + (PR_BITS_PER_BYTE - 1)) / PR_BITS_PER_BYTE;
sim_params.data = (unsignedchar *)&gcm;
sim_params.len = sizeof(gcm); if (encrypt) { /* simulate generating the IV */
rv = pk11_GenerateIV(context, gcm_message->ivGenerator,
gcm_message->ulIvFixedBits,
gcm_message->pIv, gcm_message->ulIvLen); if (rv != SECSuccess) { return rv;
}
} break; default:
PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); return SECFailure;
} /* now handle the tag. The message interface separates the tag from *thedata,whilethesingleshotgetsandputsthetagattheendof
* the encrypted data. */ if (!encrypt) { /* In the decrypt case, if the tag is already at the end of the *inputbufferwearegolden,otherwisewe'llneedanewinput
* buffer and copy the tag at the end of it */ if (tag != in + inlen) {
allocOut = PORT_Alloc(inlen + taglen); if (allocOut == NULL) { return SECFailure;
}
PORT_Memcpy(allocOut, in, inlen);
PORT_Memcpy(allocOut + inlen, tag, taglen);
in = allocOut;
}
inlen = inlen + taglen;
} else { /* if we end up allocating, we don't want to overrun this buffer,
* so we fail early here */ if (maxout < inlen) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
} /* in the encrypt case, we are fine if maxout is big enough to hold
* the tag. We'll copy the tag after the operation */ if (maxout < inlen + taglen) {
allocOut = PORT_Alloc(inlen + taglen); if (allocOut == NULL) { return SECFailure;
}
out = allocOut;
length = maxout = inlen + taglen;
}
} /* now do the operation */ if (encrypt) {
rv = PK11_Encrypt(context->key, mechanism, &sim_params, out, &length,
maxout, in, inlen);
} else {
rv = PK11_Decrypt(context->key, mechanism, &sim_params, out, &length,
maxout, in, inlen);
} if (rv != SECSuccess) { /* If the mechanism was CKM_AES_GCM, the module may have been *followingthesameerrorasoldversionsofNSS.Retrywith
* the CK_NSS_GCM_PARAMS */ if ((mechanism == CKM_AES_GCM) &&
(PORT_GetError() == SEC_ERROR_BAD_DATA)) {
CK_NSS_GCM_PARAMS gcm_nss;
gcm_message = (CK_GCM_MESSAGE_PARAMS *)params;
gcm_nss.pIv = gcm_message->pIv;
gcm_nss.ulIvLen = gcm_message->ulIvLen;
gcm_nss.pAAD = (CK_BYTE_PTR)aad;
gcm_nss.ulAADLen = aadlen;
gcm_nss.ulTagBits = gcm_message->ulTagBits;
sim_params.data = (unsignedchar *)&gcm_nss;
sim_params.len = sizeof(gcm_nss); if (encrypt) {
rv = PK11_Encrypt(context->key, mechanism, &sim_params, out,
&length, maxout, in, inlen);
} else {
rv = PK11_Decrypt(context->key, mechanism, &sim_params, out,
&length, maxout, in, inlen);
} if (rv != SECSuccess) { goto fail;
}
} else { goto fail;
}
}
/* on encrypt, separate the output buffer from the tag */ if (encrypt) { if ((length < taglen) || (length > inlen + taglen)) { /* PKCS #11 module should not return a length smaller than
* taglen, or bigger than inlen+taglen */
PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
rv = SECFailure; goto fail;
}
length = length - taglen; if (allocOut) { /* *Ifweusedatemporarybuffer,copyitouttotheoriginal *buffer.
*/
PORT_Memcpy(saveOut, allocOut, length);
} /* if the tag isn't in the right place, copy it out */ if (tag != out + length) {
PORT_Memcpy(tag, out + length, taglen);
}
}
*outlen = length;
rv = SECSuccess;
fail: if (allocOut) {
PORT_Free(allocOut);
} return rv;
}
/* *DoanAEADoperation.Thisfunctionoptionallyreturns *andIVonEncryptforallmechanism.NSSknowswhichmechanisms *generateIV'sinthetokenandwhichdon't.Thisallowsthe *applicationstomakeasinglecallwithoutspecialhandlingfor *eachAEADmechanism(thespecialhandlingisallcontainedhere.
*/
SECStatus
PK11_AEADOp(PK11Context *context, CK_GENERATOR_FUNCTION ivgen, int fixedbits, unsignedchar *iv, int ivlen, constunsignedchar *aad, int aadlen, unsignedchar *out, int *outlen, int maxout, unsignedchar *tag, int taglen, constunsignedchar *in, int inlen)
{
CK_GCM_MESSAGE_PARAMS gcm_message;
CK_CCM_MESSAGE_PARAMS ccm_message;
CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS chacha_poly_message; void *params; int paramslen;
SECStatus rv;
switch (context->simulate_mechanism) { case CKM_CHACHA20_POLY1305: case CKM_SALSA20_POLY1305: case CKM_NSS_CHACHA20_POLY1305:
chacha_poly_message.pNonce = iv;
chacha_poly_message.ulNonceLen = ivlen;
chacha_poly_message.pTag = tag;
params = &chacha_poly_message;
paramslen = sizeof(CK_SALSA20_CHACHA20_POLY1305_MSG_PARAMS); /* SALSA20_POLY1305 and CHACHA20_POLY1305 do not generate the iv
* internally, Do it here. */ if (context->operation == (CKA_NSS_MESSAGE | CKA_ENCRYPT)) { /* simulate generating the IV */
rv = pk11_GenerateIV(context, ivgen, fixedbits, iv, ivlen); if (rv != SECSuccess) { return rv;
}
} break; case CKM_AES_GCM:
gcm_message.pIv = iv;
gcm_message.ulIvLen = ivlen;
gcm_message.ivGenerator = ivgen;
gcm_message.ulIvFixedBits = fixedbits;
gcm_message.pTag = tag;
gcm_message.ulTagBits = taglen * 8;
params = &gcm_message;
paramslen = sizeof(CK_GCM_MESSAGE_PARAMS); /* GCM generates IV internally */ break; case CKM_AES_CCM:
ccm_message.ulDataLen = inlen;
ccm_message.pNonce = iv;
ccm_message.ulNonceLen = ivlen;
ccm_message.nonceGenerator = ivgen;
ccm_message.ulNonceFixedBits = fixedbits;
ccm_message.pMAC = tag;
ccm_message.ulMACLen = taglen;
params = &ccm_message;
paramslen = sizeof(CK_GCM_MESSAGE_PARAMS); /* CCM generates IV internally */ break;
/* Do and AED operation. The application builds the params on it's own *andpassesthemin.Thisallowsapplicationsdirectaccesstotheparams *sotheycanusemechanismsnotyetunderstoodby,NSS,orgetsemantics
* not suppied by PK11_AEAD. */
SECStatus
PK11_AEADRawOp(PK11Context *context, void *params, int paramslen, constunsignedchar *aad, int aadlen, unsignedchar *out, int *outlen, int maxout, constunsignedchar *in, int inlen)
{
CK_RV crv = CKR_OK;
CK_ULONG length = maxout;
SECStatus rv = SECSuccess;
/* *ThePKCS11moduledoesnotsupportthemessageinterface,fall
* back to using single shot operation */ if (context->simulate_message) { return pk11_AEADSimulateOp(context, params, paramslen, aad, aadlen,
out, outlen, maxout, in, inlen);
}
/* if we ran out of session, we need to restore our previously stored *state.
*/
PK11_EnterContextMonitor(context); if (!context->ownSession) {
rv = pk11_restoreContext(context, context->savedData,
context->savedLength); if (rv != SECSuccess) {
PK11_ExitContextMonitor(context); return rv;
}
}
if (inLen == 0) { return SECSuccess;
} if (!in) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
/* if we ran out of session, we need to restore our previously stored *state.
*/
context->init = PR_FALSE;
PK11_EnterContextMonitor(context); if (!context->ownSession) {
rv = pk11_restoreContext(context, context->savedData,
context->savedLength); if (rv != SECSuccess) {
PK11_ExitContextMonitor(context); return rv;
}
}
switch (context->operation) { /* also for MAC'ing */ case CKA_SIGN:
crv = PK11_GETTAB(context->slot)->C_SignUpdate(context->session, (unsignedchar *)in, inLen); break; case CKA_VERIFY:
crv = PK11_GETTAB(context->slot)->C_VerifyUpdate(context->session, (unsignedchar *)in, inLen); break; case CKA_NSS_VERIFY_SIGNATURE:
crv = PK11_GETTAB(context->slot)->C_VerifySignatureUpdate(context->session, (unsignedchar *)in, inLen); break; case CKA_DIGEST:
crv = PK11_GETTAB(context->slot)->C_DigestUpdate(context->session, (unsignedchar *)in, inLen); break; default:
crv = CKR_OPERATION_NOT_INITIALIZED; break;
}
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv));
rv = SECFailure;
}
/* *handlesessionstarvationcase..useourlastsessiontomultiplex
*/ if (!context->ownSession) {
context->savedData = pk11_saveContext(context, context->savedData,
&context->savedLength); if (context->savedData == NULL)
rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
PK11_ExitContextMonitor(context); return rv;
}
if (!context || !key) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
/* if we ran out of session, we need to restore our previously stored *state.
*/ if (context->slot != key->slot) {
newKey = pk11_CopyToSlot(context->slot, CKM_SSL3_SHA1_MAC, CKA_SIGN, key);
} else {
newKey = PK11_ReferenceSymKey(key);
}
if (crv != CKR_OK) {
PORT_SetError(PK11_MapError(crv));
rv = SECFailure;
}
/* *handlesessionstarvationcase..useourlastsessiontomultiplex
*/ if (!context->ownSession) {
context->savedData = pk11_saveContext(context, context->savedData,
&context->savedLength); if (context->savedData == NULL)
rv = SECFailure;
/* clear out out session for others to use */
pk11_Finalize(context);
}
PK11_ExitContextMonitor(context); if (newKey)
PK11_FreeSymKey(newKey); return rv;
}
finalize: switch (context->operation) { case CKA_ENCRYPT:
crv = PK11_GETTAB(context->slot)->C_EncryptFinal(context->session, buffer, &count); break; case CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session, buffer, &count); break; case CKA_SIGN:
crv = PK11_GETTAB(context->slot)->C_SignFinal(context->session, buffer, &count); break; case CKA_VERIFY:
crv = PK11_GETTAB(context->slot)->C_VerifyFinal(context->session, buffer, count); break; case CKA_NSS_VERIFY_SIGNATURE:
crv = PK11_GETTAB(context->slot)->C_VerifySignatureFinal(context->session); break; case CKA_DIGEST:
crv = PK11_GETTAB(context->slot)->C_DigestFinal(context->session, buffer, &count); break; case CKA_NSS_MESSAGE | CKA_ENCRYPT:
crv = PK11_GETTAB(context->slot)->C_MessageEncryptFinal(context->session); break; case CKA_NSS_MESSAGE | CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_MessageDecryptFinal(context->session); break; case CKA_NSS_MESSAGE | CKA_SIGN:
crv = PK11_GETTAB(context->slot)->C_MessageSignFinal(context->session); break; case CKA_NSS_MESSAGE | CKA_VERIFY:
crv = PK11_GETTAB(context->slot)->C_MessageVerifyFinal(context->session); break; default:
crv = CKR_OPERATION_NOT_INITIALIZED; break;
}
if (crv != CKR_OK) { if (buffer != stackBuf) {
PORT_Free(buffer);
} if (crv == CKR_OPERATION_NOT_INITIALIZED) { /* if there's no operation, it is finalized */ return SECSuccess;
}
PORT_SetError(PK11_MapError(crv)); return SECFailure;
}
/* Message interface does not need to allocate a final buffer */ /* nor does CKA_NSS_VERIFY_SIGNATURE. We could use a clever trick *heretoincludetheCKA_NSS_SIGNATUREaddition,butthisformis
* more clear to the reader what is happenning */ if ((((context->operation) & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) ||
((context->operation) == CKA_NSS_VERIFY_SIGNATURE)) { return SECSuccess;
}
/* try to finalize the session with a buffer */ if (buffer == NULL) { if (count <= sizeof stackBuf) {
buffer = stackBuf;
} else {
buffer = PORT_Alloc(count); if (buffer == NULL) { return SECFailure;
}
} goto finalize;
} if (buffer != stackBuf) {
PORT_Free(buffer);
} return SECSuccess;
}
/* message interface returns no data on Final, Should not use DigestFinal
* in this case */ if (((context->operation) & CKA_NSS_MESSAGE_MASK) == CKA_NSS_MESSAGE) {
PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure;
}
/* if we ran out of session, we need to restore our previously stored *state.
*/
PK11_EnterContextMonitor(context); if (!context->ownSession) {
rv = pk11_restoreContext(context, context->savedData,
context->savedLength); if (rv != SECSuccess) {
PK11_ExitContextMonitor(context); return rv;
}
}
len = length; switch (context->operation) { case CKA_SIGN:
crv = PK11_GETTAB(context->slot)->C_SignFinal(context->session, data, &len); break; case CKA_VERIFY:
crv = PK11_GETTAB(context->slot)->C_VerifyFinal(context->session, data, len); break; case CKA_NSS_VERIFY_SIGNATURE:
crv = PK11_GETTAB(context->slot)->C_VerifySignatureFinal(context->session); break; case CKA_DIGEST:
crv = PK11_GETTAB(context->slot)->C_DigestFinal(context->session, data, &len); break; case CKA_ENCRYPT:
crv = PK11_GETTAB(context->slot)->C_EncryptFinal(context->session, data, &len); break; case CKA_DECRYPT:
crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session, data, &len); break; default:
crv = CKR_OPERATION_NOT_INITIALIZED; break;
}
PK11_ExitContextMonitor(context);
context->init = PR_FALSE; /* allow Begin to start up again */