diff options
Diffstat (limited to 'nss/lib/softoken')
59 files changed, 21794 insertions, 22336 deletions
diff --git a/nss/lib/softoken/Makefile b/nss/lib/softoken/Makefile index b2f33e2..90a9da2 100644 --- a/nss/lib/softoken/Makefile +++ b/nss/lib/softoken/Makefile @@ -20,6 +20,16 @@ include $(CORE_DEPTH)/coreconf/config.mk # (3) Include "component" configuration information. (OPTIONAL) # ####################################################################### +ifdef NSS_NO_INIT_SUPPORT + DEFINES += -DNSS_NO_INIT_SUPPORT +endif +ifeq ($(OS_TARGET),Linux) +ifeq ($(CPU_ARCH),ppc) +ifdef USE_64 + DEFINES += -DNSS_NO_INIT_SUPPORT +endif # USE_64 +endif # ppc +endif # Linux ####################################################################### diff --git a/nss/lib/softoken/exports.gyp b/nss/lib/softoken/exports.gyp new file mode 100644 index 0000000..d11d8e4 --- /dev/null +++ b/nss/lib/softoken/exports.gyp @@ -0,0 +1,38 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +{ + 'includes': [ + '../../coreconf/config.gypi' + ], + 'targets': [ + { + 'target_name': 'lib_softoken_exports', + 'type': 'none', + 'copies': [ + { + 'files': [ + 'lowkeyi.h', + 'lowkeyti.h' + ], + 'destination': '<(nss_public_dist_dir)/<(module)' + }, + { + 'files': [ + 'lgglue.h', + 'pkcs11ni.h', + 'sdb.h', + 'sftkdbt.h', + 'softkver.h', + 'softoken.h', + 'softoknt.h' + ], + 'destination': '<(nss_private_dist_dir)/<(module)' + } + ] + } + ], + 'variables': { + 'module': 'nss' + } +} diff --git a/nss/lib/softoken/fipsaudt.c b/nss/lib/softoken/fipsaudt.c index b026374..e0fd641 100644 --- a/nss/lib/softoken/fipsaudt.c +++ b/nss/lib/softoken/fipsaudt.c @@ -23,15 +23,16 @@ * phObject: the pointer to object handle * rv: the return value of the PKCS #11 function */ -static void sftk_PrintReturnedObjectHandle(char *out, PRUint32 outlen, - const char *argName, CK_OBJECT_HANDLE_PTR phObject, CK_RV rv) +static void +sftk_PrintReturnedObjectHandle(char *out, PRUint32 outlen, + const char *argName, CK_OBJECT_HANDLE_PTR phObject, CK_RV rv) { if ((rv == CKR_OK) && phObject) { - PR_snprintf(out, outlen, - " *%s=0x%08lX", argName, (PRUint32)*phObject); + PR_snprintf(out, outlen, + " *%s=0x%08lX", argName, (PRUint32)*phObject); } else { - PORT_Assert(outlen != 0); - out[0] = '\0'; + PORT_Assert(outlen != 0); + out[0] = '\0'; } } @@ -41,279 +42,280 @@ static void sftk_PrintReturnedObjectHandle(char *out, PRUint32 outlen, */ #define MECHANISM_BUFSIZE 64 -static void sftk_PrintMechanism(char *out, PRUint32 outlen, - CK_MECHANISM_PTR pMechanism) +static void +sftk_PrintMechanism(char *out, PRUint32 outlen, + CK_MECHANISM_PTR pMechanism) { if (pMechanism) { - /* - * If we change the format string, we need to make sure - * MECHANISM_BUFSIZE is still large enough. We allow - * 20 bytes for %p on a 64-bit platform. - */ - PR_snprintf(out, outlen, "%p {mechanism=0x%08lX, ...}", - pMechanism, (PRUint32)pMechanism->mechanism); + /* + * If we change the format string, we need to make sure + * MECHANISM_BUFSIZE is still large enough. We allow + * 20 bytes for %p on a 64-bit platform. + */ + PR_snprintf(out, outlen, "%p {mechanism=0x%08lX, ...}", + pMechanism, (PRUint32)pMechanism->mechanism); } else { - PR_snprintf(out, outlen, "%p", pMechanism); + PR_snprintf(out, outlen, "%p", pMechanism); } } -void sftk_AuditCreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject, CK_RV rv) +void +sftk_AuditCreateObject(CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject, CK_RV rv) { char msg[256]; char shObject[32]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintReturnedObjectHandle(shObject, sizeof shObject, - "phObject", phObject, rv); + "phObject", phObject, rv); PR_snprintf(msg, sizeof msg, - "C_CreateObject(hSession=0x%08lX, pTemplate=%p, ulCount=%lu, " - "phObject=%p)=0x%08lX%s", - (PRUint32)hSession, pTemplate, (PRUint32)ulCount, - phObject, (PRUint32)rv, shObject); + "C_CreateObject(hSession=0x%08lX, pTemplate=%p, ulCount=%lu, " + "phObject=%p)=0x%08lX%s", + (PRUint32)hSession, pTemplate, (PRUint32)ulCount, + phObject, (PRUint32)rv, shObject); sftk_LogAuditMessage(severity, NSS_AUDIT_LOAD_KEY, msg); } -void sftk_AuditCopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject, CK_RV rv) +void +sftk_AuditCopyObject(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject, CK_RV rv) { char msg[256]; char shNewObject[32]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintReturnedObjectHandle(shNewObject, sizeof shNewObject, - "phNewObject", phNewObject, rv); + "phNewObject", phNewObject, rv); PR_snprintf(msg, sizeof msg, - "C_CopyObject(hSession=0x%08lX, hObject=0x%08lX, " - "pTemplate=%p, ulCount=%lu, phNewObject=%p)=0x%08lX%s", - (PRUint32)hSession, (PRUint32)hObject, - pTemplate, (PRUint32)ulCount, phNewObject, (PRUint32)rv, shNewObject); + "C_CopyObject(hSession=0x%08lX, hObject=0x%08lX, " + "pTemplate=%p, ulCount=%lu, phNewObject=%p)=0x%08lX%s", + (PRUint32)hSession, (PRUint32)hObject, + pTemplate, (PRUint32)ulCount, phNewObject, (PRUint32)rv, shNewObject); sftk_LogAuditMessage(severity, NSS_AUDIT_COPY_KEY, msg); } /* WARNING: hObject has been destroyed and can only be printed. */ -void sftk_AuditDestroyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_RV rv) +void +sftk_AuditDestroyObject(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_RV rv) { char msg[256]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; PR_snprintf(msg, sizeof msg, - "C_DestroyObject(hSession=0x%08lX, hObject=0x%08lX)=0x%08lX", - (PRUint32)hSession, (PRUint32)hObject, (PRUint32)rv); + "C_DestroyObject(hSession=0x%08lX, hObject=0x%08lX)=0x%08lX", + (PRUint32)hSession, (PRUint32)hObject, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_DESTROY_KEY, msg); } -void sftk_AuditGetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize, CK_RV rv) +void +sftk_AuditGetObjectSize(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize, CK_RV rv) { char msg[256]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; PR_snprintf(msg, sizeof msg, - "C_GetObjectSize(hSession=0x%08lX, hObject=0x%08lX, " - "pulSize=%p)=0x%08lX", - (PRUint32)hSession, (PRUint32)hObject, - pulSize, (PRUint32)rv); + "C_GetObjectSize(hSession=0x%08lX, hObject=0x%08lX, " + "pulSize=%p)=0x%08lX", + (PRUint32)hSession, (PRUint32)hObject, + pulSize, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_ACCESS_KEY, msg); } -void sftk_AuditGetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_RV rv) +void +sftk_AuditGetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_RV rv) { char msg[256]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; PR_snprintf(msg, sizeof msg, - "C_GetAttributeValue(hSession=0x%08lX, hObject=0x%08lX, " - "pTemplate=%p, ulCount=%lu)=0x%08lX", - (PRUint32)hSession, (PRUint32)hObject, - pTemplate, (PRUint32)ulCount, (PRUint32)rv); + "C_GetAttributeValue(hSession=0x%08lX, hObject=0x%08lX, " + "pTemplate=%p, ulCount=%lu)=0x%08lX", + (PRUint32)hSession, (PRUint32)hObject, + pTemplate, (PRUint32)ulCount, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_ACCESS_KEY, msg); } -void sftk_AuditSetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_RV rv) +void +sftk_AuditSetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_RV rv) { char msg[256]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; PR_snprintf(msg, sizeof msg, - "C_SetAttributeValue(hSession=0x%08lX, hObject=0x%08lX, " - "pTemplate=%p, ulCount=%lu)=0x%08lX", - (PRUint32)hSession, (PRUint32)hObject, - pTemplate, (PRUint32)ulCount, (PRUint32)rv); + "C_SetAttributeValue(hSession=0x%08lX, hObject=0x%08lX, " + "pTemplate=%p, ulCount=%lu)=0x%08lX", + (PRUint32)hSession, (PRUint32)hObject, + pTemplate, (PRUint32)ulCount, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_CHANGE_KEY, msg); } -void sftk_AuditCryptInit(const char *opName, CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey, CK_RV rv) +void +sftk_AuditCryptInit(const char *opName, CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey, CK_RV rv) { char msg[256]; char mech[MECHANISM_BUFSIZE]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); PR_snprintf(msg, sizeof msg, - "C_%sInit(hSession=0x%08lX, pMechanism=%s, " - "hKey=0x%08lX)=0x%08lX", - opName, (PRUint32)hSession, mech, - (PRUint32)hKey, (PRUint32)rv); + "C_%sInit(hSession=0x%08lX, pMechanism=%s, " + "hKey=0x%08lX)=0x%08lX", + opName, (PRUint32)hSession, mech, + (PRUint32)hKey, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_CRYPT, msg); } -void sftk_AuditGenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) +void +sftk_AuditGenerateKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) { char msg[256]; char mech[MECHANISM_BUFSIZE]; char shKey[32]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); sftk_PrintReturnedObjectHandle(shKey, sizeof shKey, "phKey", phKey, rv); PR_snprintf(msg, sizeof msg, - "C_GenerateKey(hSession=0x%08lX, pMechanism=%s, " - "pTemplate=%p, ulCount=%lu, phKey=%p)=0x%08lX%s", - (PRUint32)hSession, mech, - pTemplate, (PRUint32)ulCount, phKey, (PRUint32)rv, shKey); + "C_GenerateKey(hSession=0x%08lX, pMechanism=%s, " + "pTemplate=%p, ulCount=%lu, phKey=%p)=0x%08lX%s", + (PRUint32)hSession, mech, + pTemplate, (PRUint32)ulCount, phKey, (PRUint32)rv, shKey); sftk_LogAuditMessage(severity, NSS_AUDIT_GENERATE_KEY, msg); } -void sftk_AuditGenerateKeyPair(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey, CK_RV rv) +void +sftk_AuditGenerateKeyPair(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, + CK_OBJECT_HANDLE_PTR phPrivateKey, CK_RV rv) { char msg[512]; char mech[MECHANISM_BUFSIZE]; char shPublicKey[32]; char shPrivateKey[32]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); sftk_PrintReturnedObjectHandle(shPublicKey, sizeof shPublicKey, - "phPublicKey", phPublicKey, rv); + "phPublicKey", phPublicKey, rv); sftk_PrintReturnedObjectHandle(shPrivateKey, sizeof shPrivateKey, - "phPrivateKey", phPrivateKey, rv); + "phPrivateKey", phPrivateKey, rv); PR_snprintf(msg, sizeof msg, - "C_GenerateKeyPair(hSession=0x%08lX, pMechanism=%s, " - "pPublicKeyTemplate=%p, ulPublicKeyAttributeCount=%lu, " - "pPrivateKeyTemplate=%p, ulPrivateKeyAttributeCount=%lu, " - "phPublicKey=%p, phPrivateKey=%p)=0x%08lX%s%s", - (PRUint32)hSession, mech, - pPublicKeyTemplate, (PRUint32)ulPublicKeyAttributeCount, - pPrivateKeyTemplate, (PRUint32)ulPrivateKeyAttributeCount, - phPublicKey, phPrivateKey, (PRUint32)rv, shPublicKey, shPrivateKey); + "C_GenerateKeyPair(hSession=0x%08lX, pMechanism=%s, " + "pPublicKeyTemplate=%p, ulPublicKeyAttributeCount=%lu, " + "pPrivateKeyTemplate=%p, ulPrivateKeyAttributeCount=%lu, " + "phPublicKey=%p, phPrivateKey=%p)=0x%08lX%s%s", + (PRUint32)hSession, mech, + pPublicKeyTemplate, (PRUint32)ulPublicKeyAttributeCount, + pPrivateKeyTemplate, (PRUint32)ulPrivateKeyAttributeCount, + phPublicKey, phPrivateKey, (PRUint32)rv, shPublicKey, shPrivateKey); sftk_LogAuditMessage(severity, NSS_AUDIT_GENERATE_KEY, msg); } -void sftk_AuditWrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen, CK_RV rv) +void +sftk_AuditWrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, + CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen, CK_RV rv) { char msg[256]; char mech[MECHANISM_BUFSIZE]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); PR_snprintf(msg, sizeof msg, - "C_WrapKey(hSession=0x%08lX, pMechanism=%s, hWrappingKey=0x%08lX, " - "hKey=0x%08lX, pWrappedKey=%p, pulWrappedKeyLen=%p)=0x%08lX", - (PRUint32)hSession, mech, (PRUint32)hWrappingKey, - (PRUint32)hKey, pWrappedKey, pulWrappedKeyLen, (PRUint32)rv); + "C_WrapKey(hSession=0x%08lX, pMechanism=%s, hWrappingKey=0x%08lX, " + "hKey=0x%08lX, pWrappedKey=%p, pulWrappedKeyLen=%p)=0x%08lX", + (PRUint32)hSession, mech, (PRUint32)hWrappingKey, + (PRUint32)hKey, pWrappedKey, pulWrappedKeyLen, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_WRAP_KEY, msg); } -void sftk_AuditUnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) +void +sftk_AuditUnwrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, + CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) { char msg[256]; char mech[MECHANISM_BUFSIZE]; char shKey[32]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); sftk_PrintReturnedObjectHandle(shKey, sizeof shKey, "phKey", phKey, rv); PR_snprintf(msg, sizeof msg, - "C_UnwrapKey(hSession=0x%08lX, pMechanism=%s, " - "hUnwrappingKey=0x%08lX, pWrappedKey=%p, ulWrappedKeyLen=%lu, " - "pTemplate=%p, ulAttributeCount=%lu, phKey=%p)=0x%08lX%s", - (PRUint32)hSession, mech, - (PRUint32)hUnwrappingKey, pWrappedKey, (PRUint32)ulWrappedKeyLen, - pTemplate, (PRUint32)ulAttributeCount, phKey, (PRUint32)rv, shKey); + "C_UnwrapKey(hSession=0x%08lX, pMechanism=%s, " + "hUnwrappingKey=0x%08lX, pWrappedKey=%p, ulWrappedKeyLen=%lu, " + "pTemplate=%p, ulAttributeCount=%lu, phKey=%p)=0x%08lX%s", + (PRUint32)hSession, mech, + (PRUint32)hUnwrappingKey, pWrappedKey, (PRUint32)ulWrappedKeyLen, + pTemplate, (PRUint32)ulAttributeCount, phKey, (PRUint32)rv, shKey); sftk_LogAuditMessage(severity, NSS_AUDIT_UNWRAP_KEY, msg); } -void sftk_AuditDeriveKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) +void +sftk_AuditDeriveKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey, CK_RV rv) { char msg[512]; char mech[MECHANISM_BUFSIZE]; char shKey[32]; char sTlsKeys[128]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; sftk_PrintMechanism(mech, sizeof mech, pMechanism); sftk_PrintReturnedObjectHandle(shKey, sizeof shKey, "phKey", phKey, rv); if ((rv == CKR_OK) && - (pMechanism->mechanism == CKM_TLS_KEY_AND_MAC_DERIVE)) { - CK_SSL3_KEY_MAT_PARAMS *param = - (CK_SSL3_KEY_MAT_PARAMS *)pMechanism->pParameter; - CK_SSL3_KEY_MAT_OUT *keymat = param->pReturnedKeyMaterial; - PR_snprintf(sTlsKeys, sizeof sTlsKeys, - " hClientMacSecret=0x%08lX hServerMacSecret=0x%08lX" - " hClientKey=0x%08lX hServerKey=0x%08lX", - (PRUint32)keymat->hClientMacSecret, - (PRUint32)keymat->hServerMacSecret, - (PRUint32)keymat->hClientKey, - (PRUint32)keymat->hServerKey); + (pMechanism->mechanism == CKM_TLS_KEY_AND_MAC_DERIVE)) { + CK_SSL3_KEY_MAT_PARAMS *param = + (CK_SSL3_KEY_MAT_PARAMS *)pMechanism->pParameter; + CK_SSL3_KEY_MAT_OUT *keymat = param->pReturnedKeyMaterial; + PR_snprintf(sTlsKeys, sizeof sTlsKeys, + " hClientMacSecret=0x%08lX hServerMacSecret=0x%08lX" + " hClientKey=0x%08lX hServerKey=0x%08lX", + (PRUint32)keymat->hClientMacSecret, + (PRUint32)keymat->hServerMacSecret, + (PRUint32)keymat->hClientKey, + (PRUint32)keymat->hServerKey); } else { - sTlsKeys[0] = '\0'; + sTlsKeys[0] = '\0'; } PR_snprintf(msg, sizeof msg, - "C_DeriveKey(hSession=0x%08lX, pMechanism=%s, " - "hBaseKey=0x%08lX, pTemplate=%p, ulAttributeCount=%lu, " - "phKey=%p)=0x%08lX%s%s", - (PRUint32)hSession, mech, - (PRUint32)hBaseKey, pTemplate,(PRUint32)ulAttributeCount, - phKey, (PRUint32)rv, shKey, sTlsKeys); + "C_DeriveKey(hSession=0x%08lX, pMechanism=%s, " + "hBaseKey=0x%08lX, pTemplate=%p, ulAttributeCount=%lu, " + "phKey=%p)=0x%08lX%s%s", + (PRUint32)hSession, mech, + (PRUint32)hBaseKey, pTemplate, (PRUint32)ulAttributeCount, + phKey, (PRUint32)rv, shKey, sTlsKeys); sftk_LogAuditMessage(severity, NSS_AUDIT_DERIVE_KEY, msg); } -void sftk_AuditDigestKey(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hKey, CK_RV rv) +void +sftk_AuditDigestKey(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hKey, CK_RV rv) { char msg[256]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; PR_snprintf(msg, sizeof msg, - "C_DigestKey(hSession=0x%08lX, hKey=0x%08lX)=0x%08lX", - (PRUint32)hSession, (PRUint32)hKey, (PRUint32)rv); + "C_DigestKey(hSession=0x%08lX, hKey=0x%08lX)=0x%08lX", + (PRUint32)hSession, (PRUint32)hKey, (PRUint32)rv); sftk_LogAuditMessage(severity, NSS_AUDIT_DIGEST_KEY, msg); } diff --git a/nss/lib/softoken/fipstest.c b/nss/lib/softoken/fipstest.c index aed33bb..3563bd2 100644 --- a/nss/lib/softoken/fipstest.c +++ b/nss/lib/softoken/fipstest.c @@ -5,1106 +5,122 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "softoken.h" /* Required for RC2-ECB, RC2-CBC, RC4, DES-ECB, */ - /* DES-CBC, DES3-ECB, DES3-CBC, RSA */ - /* and DSA. */ -#include "seccomon.h" /* Required for RSA and DSA. */ -#include "lowkeyi.h" /* Required for RSA and DSA. */ -#include "pkcs11.h" /* Required for PKCS #11. */ +#include "seccomon.h" +#include "blapi.h" +#include "softoken.h" +#include "lowkeyi.h" +#include "secoid.h" #include "secerr.h" -#ifndef NSS_DISABLE_ECC -#include "ec.h" /* Required for ECDSA */ +/* + * different platforms have different ways of calling and initial entry point + * when the dll/.so is loaded. Most platforms support either a posix pragma + * or the GCC attribute. Some platforms suppor a pre-defined name, and some + * platforms have a link line way of invoking this function. + */ + +/* The pragma */ +#if defined(USE_INIT_PRAGMA) +#pragma init(sftk_startup_tests) #endif +/* GCC Attribute */ +#if defined(__GNUC__) && !defined(NSS_NO_INIT_SUPPORT) +#define INIT_FUNCTION __attribute__((constructor)) +#else +#define INIT_FUNCTION +#endif -/* FIPS preprocessor directives for RC2-ECB and RC2-CBC. */ -#define FIPS_RC2_KEY_LENGTH 5 /* 40-bits */ -#define FIPS_RC2_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_RC2_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for RC4. */ -#define FIPS_RC4_KEY_LENGTH 5 /* 40-bits */ -#define FIPS_RC4_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_RC4_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for DES-ECB and DES-CBC. */ -#define FIPS_DES_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_DES_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for DES3-CBC and DES3-ECB. */ -#define FIPS_DES3_ENCRYPT_LENGTH 8 /* 64-bits */ -#define FIPS_DES3_DECRYPT_LENGTH 8 /* 64-bits */ - - -/* FIPS preprocessor directives for AES-ECB and AES-CBC. */ -#define FIPS_AES_BLOCK_SIZE 16 /* 128-bits */ -#define FIPS_AES_ENCRYPT_LENGTH 16 /* 128-bits */ -#define FIPS_AES_DECRYPT_LENGTH 16 /* 128-bits */ -#define FIPS_AES_128_KEY_SIZE 16 /* 128-bits */ -#define FIPS_AES_192_KEY_SIZE 24 /* 192-bits */ -#define FIPS_AES_256_KEY_SIZE 32 /* 256-bits */ - - -/* FIPS preprocessor directives for message digests */ -#define FIPS_KNOWN_HASH_MESSAGE_LENGTH 64 /* 512-bits */ - - -/* FIPS preprocessor directives for RSA. */ -#define FIPS_RSA_TYPE siBuffer -#define FIPS_RSA_PUBLIC_EXPONENT_LENGTH 3 /* 24-bits */ -#define FIPS_RSA_PRIVATE_VERSION_LENGTH 1 /* 8-bits */ -#define FIPS_RSA_MESSAGE_LENGTH 256 /* 2048-bits */ -#define FIPS_RSA_COEFFICIENT_LENGTH 128 /* 1024-bits */ -#define FIPS_RSA_PRIME0_LENGTH 128 /* 1024-bits */ -#define FIPS_RSA_PRIME1_LENGTH 128 /* 1024-bits */ -#define FIPS_RSA_EXPONENT0_LENGTH 128 /* 1024-bits */ -#define FIPS_RSA_EXPONENT1_LENGTH 128 /* 1024-bits */ -#define FIPS_RSA_PRIVATE_EXPONENT_LENGTH 256 /* 2048-bits */ -#define FIPS_RSA_ENCRYPT_LENGTH 256 /* 2048-bits */ -#define FIPS_RSA_DECRYPT_LENGTH 256 /* 2048-bits */ -#define FIPS_RSA_SIGNATURE_LENGTH 256 /* 2048-bits */ -#define FIPS_RSA_MODULUS_LENGTH 256 /* 2048-bits */ - - -/* FIPS preprocessor directives for DSA. */ -#define FIPS_DSA_TYPE siBuffer -#define FIPS_DSA_DIGEST_LENGTH 20 /* 160-bits */ -#define FIPS_DSA_SUBPRIME_LENGTH 20 /* 160-bits */ -#define FIPS_DSA_SIGNATURE_LENGTH 40 /* 320-bits */ -#define FIPS_DSA_PRIME_LENGTH 128 /* 1024-bits */ -#define FIPS_DSA_BASE_LENGTH 128 /* 1024-bits */ - -/* FIPS preprocessor directives for RNG. */ -#define FIPS_RNG_XKEY_LENGTH 32 /* 256-bits */ - -static CK_RV -sftk_fips_RC2_PowerUpSelfTest( void ) -{ - /* RC2 Known Key (40-bits). */ - static const PRUint8 rc2_known_key[] = { "RSARC" }; - - /* RC2-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 rc2_cbc_known_initialization_vector[] = {"Security"}; - - /* RC2 Known Plaintext (64-bits). */ - static const PRUint8 rc2_ecb_known_plaintext[] = {"Netscape"}; - static const PRUint8 rc2_cbc_known_plaintext[] = {"Netscape"}; - - /* RC2 Known Ciphertext (64-bits). */ - static const PRUint8 rc2_ecb_known_ciphertext[] = { - 0x1a,0x71,0x33,0x54,0x8d,0x5c,0xd2,0x30}; - static const PRUint8 rc2_cbc_known_ciphertext[] = { - 0xff,0x41,0xdb,0x94,0x8a,0x4c,0x33,0xb3}; - - /* RC2 variables. */ - PRUint8 rc2_computed_ciphertext[FIPS_RC2_ENCRYPT_LENGTH]; - PRUint8 rc2_computed_plaintext[FIPS_RC2_DECRYPT_LENGTH]; - RC2Context * rc2_context; - unsigned int rc2_bytes_encrypted; - unsigned int rc2_bytes_decrypted; - SECStatus rc2_status; - - - /******************************************************/ - /* RC2-ECB Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - NULL, NSS_RC2, - FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext, - &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH, - rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_ciphertext, rc2_ecb_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-ECB Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - NULL, NSS_RC2, - FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext, - &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH, - rc2_ecb_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-CBC Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - rc2_cbc_known_initialization_vector, - NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext, - &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH, - rc2_cbc_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_ciphertext, rc2_cbc_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* RC2-CBC Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH, - rc2_cbc_known_initialization_vector, - NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH ); - - if( rc2_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext, - &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH, - rc2_cbc_known_ciphertext, - FIPS_RC2_ENCRYPT_LENGTH ); - - RC2_DestroyContext( rc2_context, PR_TRUE ); - - if( ( rc2_status != SECSuccess ) || - ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext, - FIPS_RC2_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -sftk_fips_RC4_PowerUpSelfTest( void ) -{ - /* RC4 Known Key (40-bits). */ - static const PRUint8 rc4_known_key[] = { "RSARC" }; - - /* RC4 Known Plaintext (64-bits). */ - static const PRUint8 rc4_known_plaintext[] = { "Netscape" }; - - /* RC4 Known Ciphertext (64-bits). */ - static const PRUint8 rc4_known_ciphertext[] = { - 0x29,0x33,0xc7,0x9a,0x9d,0x6c,0x09,0xdd}; - - /* RC4 variables. */ - PRUint8 rc4_computed_ciphertext[FIPS_RC4_ENCRYPT_LENGTH]; - PRUint8 rc4_computed_plaintext[FIPS_RC4_DECRYPT_LENGTH]; - RC4Context * rc4_context; - unsigned int rc4_bytes_encrypted; - unsigned int rc4_bytes_decrypted; - SECStatus rc4_status; - - - /**************************************************/ - /* RC4 Single-Round Known Answer Encryption Test: */ - /**************************************************/ - - rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH ); - - if( rc4_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc4_status = RC4_Encrypt( rc4_context, rc4_computed_ciphertext, - &rc4_bytes_encrypted, FIPS_RC4_ENCRYPT_LENGTH, - rc4_known_plaintext, FIPS_RC4_DECRYPT_LENGTH ); - - RC4_DestroyContext( rc4_context, PR_TRUE ); - - if( ( rc4_status != SECSuccess ) || - ( rc4_bytes_encrypted != FIPS_RC4_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( rc4_computed_ciphertext, rc4_known_ciphertext, - FIPS_RC4_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /**************************************************/ - /* RC4 Single-Round Known Answer Decryption Test: */ - /**************************************************/ - - rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH ); - - if( rc4_context == NULL ) - return( CKR_HOST_MEMORY ); - - rc4_status = RC4_Decrypt( rc4_context, rc4_computed_plaintext, - &rc4_bytes_decrypted, FIPS_RC4_DECRYPT_LENGTH, - rc4_known_ciphertext, FIPS_RC4_ENCRYPT_LENGTH ); - - RC4_DestroyContext( rc4_context, PR_TRUE ); - - if( ( rc4_status != SECSuccess ) || - ( rc4_bytes_decrypted != FIPS_RC4_DECRYPT_LENGTH ) || - ( PORT_Memcmp( rc4_computed_plaintext, rc4_known_plaintext, - FIPS_RC4_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -sftk_fips_DES_PowerUpSelfTest( void ) -{ - /* DES Known Key (56-bits). */ - static const PRUint8 des_known_key[] = { "ANSI DES" }; - - /* DES-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 des_cbc_known_initialization_vector[] = { "Security" }; - - /* DES Known Plaintext (64-bits). */ - static const PRUint8 des_ecb_known_plaintext[] = { "Netscape" }; - static const PRUint8 des_cbc_known_plaintext[] = { "Netscape" }; - - /* DES Known Ciphertext (64-bits). */ - static const PRUint8 des_ecb_known_ciphertext[] = { - 0x26,0x14,0xe9,0xc3,0x28,0x80,0x50,0xb0}; - static const PRUint8 des_cbc_known_ciphertext[] = { - 0x5e,0x95,0x94,0x5d,0x76,0xa2,0xd3,0x7d}; - - /* DES variables. */ - PRUint8 des_computed_ciphertext[FIPS_DES_ENCRYPT_LENGTH]; - PRUint8 des_computed_plaintext[FIPS_DES_DECRYPT_LENGTH]; - DESContext * des_context; - unsigned int des_bytes_encrypted; - unsigned int des_bytes_decrypted; - SECStatus des_status; - - - /******************************************************/ - /* DES-ECB Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_TRUE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Encrypt( des_context, des_computed_ciphertext, - &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH, - des_ecb_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_ciphertext, des_ecb_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-ECB Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_FALSE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Decrypt( des_context, des_computed_plaintext, - &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH, - des_ecb_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_plaintext, des_ecb_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-CBC Single-Round Known Answer Encryption Test. */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, - des_cbc_known_initialization_vector, - NSS_DES_CBC, PR_TRUE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Encrypt( des_context, des_computed_ciphertext, - &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH, - des_cbc_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_ciphertext, des_cbc_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* DES-CBC Single-Round Known Answer Decryption Test. */ - /******************************************************/ - - des_context = DES_CreateContext( des_known_key, - des_cbc_known_initialization_vector, - NSS_DES_CBC, PR_FALSE ); - - if( des_context == NULL ) - return( CKR_HOST_MEMORY ); - - des_status = DES_Decrypt( des_context, des_computed_plaintext, - &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH, - des_cbc_known_ciphertext, - FIPS_DES_ENCRYPT_LENGTH ); - - DES_DestroyContext( des_context, PR_TRUE ); - - if( ( des_status != SECSuccess ) || - ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des_computed_plaintext, des_cbc_known_plaintext, - FIPS_DES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -sftk_fips_DES3_PowerUpSelfTest( void ) -{ - /* DES3 Known Key (56-bits). */ - static const PRUint8 des3_known_key[] = { "ANSI Triple-DES Key Data" }; - - /* DES3-CBC Known Initialization Vector (64-bits). */ - static const PRUint8 des3_cbc_known_initialization_vector[] = { "Security" }; - - /* DES3 Known Plaintext (64-bits). */ - static const PRUint8 des3_ecb_known_plaintext[] = { "Netscape" }; - static const PRUint8 des3_cbc_known_plaintext[] = { "Netscape" }; - - /* DES3 Known Ciphertext (64-bits). */ - static const PRUint8 des3_ecb_known_ciphertext[] = { - 0x55,0x8e,0xad,0x3c,0xee,0x49,0x69,0xbe}; - static const PRUint8 des3_cbc_known_ciphertext[] = { - 0x43,0xdc,0x6a,0xc1,0xaf,0xa6,0x32,0xf5}; - - /* DES3 variables. */ - PRUint8 des3_computed_ciphertext[FIPS_DES3_ENCRYPT_LENGTH]; - PRUint8 des3_computed_plaintext[FIPS_DES3_DECRYPT_LENGTH]; - DESContext * des3_context; - unsigned int des3_bytes_encrypted; - unsigned int des3_bytes_decrypted; - SECStatus des3_status; - - - /*******************************************************/ - /* DES3-ECB Single-Round Known Answer Encryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, NULL, - NSS_DES_EDE3, PR_TRUE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext, - &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH, - des3_ecb_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_ciphertext, des3_ecb_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-ECB Single-Round Known Answer Decryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, NULL, - NSS_DES_EDE3, PR_FALSE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Decrypt( des3_context, des3_computed_plaintext, - &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH, - des3_ecb_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_plaintext, des3_ecb_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-CBC Single-Round Known Answer Encryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, - des3_cbc_known_initialization_vector, - NSS_DES_EDE3_CBC, PR_TRUE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext, - &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH, - des3_cbc_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_ciphertext, des3_cbc_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /*******************************************************/ - /* DES3-CBC Single-Round Known Answer Decryption Test. */ - /*******************************************************/ - - des3_context = DES_CreateContext( des3_known_key, - des3_cbc_known_initialization_vector, - NSS_DES_EDE3_CBC, PR_FALSE ); - - if( des3_context == NULL ) - return( CKR_HOST_MEMORY ); - - des3_status = DES_Decrypt( des3_context, des3_computed_plaintext, - &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH, - des3_cbc_known_ciphertext, - FIPS_DES3_ENCRYPT_LENGTH ); - - DES_DestroyContext( des3_context, PR_TRUE ); - - if( ( des3_status != SECSuccess ) || - ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) || - ( PORT_Memcmp( des3_computed_plaintext, des3_cbc_known_plaintext, - FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -/* AES self-test for 128-bit, 192-bit, or 256-bit key sizes*/ -static CK_RV -sftk_fips_AES_PowerUpSelfTest( int aes_key_size ) -{ - /* AES Known Key (up to 256-bits). */ - static const PRUint8 aes_known_key[] = - { "AES-128 RIJNDAELLEADNJIR 821-SEA" }; - - /* AES-CBC Known Initialization Vector (128-bits). */ - static const PRUint8 aes_cbc_known_initialization_vector[] = - { "SecurityytiruceS" }; - - /* AES Known Plaintext (128-bits). (blocksize is 128-bits) */ - static const PRUint8 aes_known_plaintext[] = { "NetscapeepacsteN" }; - - /* AES Known Ciphertext (128-bit key). */ - static const PRUint8 aes_ecb128_known_ciphertext[] = { - 0x3c,0xa5,0x96,0xf3,0x34,0x6a,0x96,0xc1, - 0x03,0x88,0x16,0x7b,0x20,0xbf,0x35,0x47 }; - - static const PRUint8 aes_cbc128_known_ciphertext[] = { - 0xcf,0x15,0x1d,0x4f,0x96,0xe4,0x4f,0x63, - 0x15,0x54,0x14,0x1d,0x4e,0xd8,0xd5,0xea }; - - /* AES Known Ciphertext (192-bit key). */ - static const PRUint8 aes_ecb192_known_ciphertext[] = { - 0xa0,0x18,0x62,0xed,0x88,0x19,0xcb,0x62, - 0x88,0x1d,0x4d,0xfe,0x84,0x02,0x89,0x0e }; - - static const PRUint8 aes_cbc192_known_ciphertext[] = { - 0x83,0xf7,0xa4,0x76,0xd1,0x6f,0x07,0xbe, - 0x07,0xbc,0x43,0x2f,0x6d,0xad,0x29,0xe1 }; - - /* AES Known Ciphertext (256-bit key). */ - static const PRUint8 aes_ecb256_known_ciphertext[] = { - 0xdb,0xa6,0x52,0x01,0x8a,0x70,0xae,0x66, - 0x3a,0x99,0xd8,0x95,0x7f,0xfb,0x01,0x67 }; - - static const PRUint8 aes_cbc256_known_ciphertext[] = { - 0x37,0xea,0x07,0x06,0x31,0x1c,0x59,0x27, - 0xc5,0xc5,0x68,0x71,0x6e,0x34,0x40,0x16 }; - - const PRUint8 *aes_ecb_known_ciphertext = - ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_ecb128_known_ciphertext : - ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_ecb192_known_ciphertext : - aes_ecb256_known_ciphertext; - - const PRUint8 *aes_cbc_known_ciphertext = - ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_cbc128_known_ciphertext : - ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_cbc192_known_ciphertext : - aes_cbc256_known_ciphertext; - - /* AES variables. */ - PRUint8 aes_computed_ciphertext[FIPS_AES_ENCRYPT_LENGTH]; - PRUint8 aes_computed_plaintext[FIPS_AES_DECRYPT_LENGTH]; - AESContext * aes_context; - unsigned int aes_bytes_encrypted; - unsigned int aes_bytes_decrypted; - SECStatus aes_status; - - /*check if aes_key_size is 128, 192, or 256 bits */ - if ((aes_key_size != FIPS_AES_128_KEY_SIZE) && - (aes_key_size != FIPS_AES_192_KEY_SIZE) && - (aes_key_size != FIPS_AES_256_KEY_SIZE)) - return( CKR_DEVICE_ERROR ); - - /******************************************************/ - /* AES-ECB Single-Round Known Answer Encryption Test: */ - /******************************************************/ - - aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_TRUE, - aes_key_size, FIPS_AES_BLOCK_SIZE ); - - if( aes_context == NULL ) - return( CKR_HOST_MEMORY ); - - aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext, - &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH, - aes_known_plaintext, - FIPS_AES_DECRYPT_LENGTH ); - - AES_DestroyContext( aes_context, PR_TRUE ); - - if( ( aes_status != SECSuccess ) || - ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( aes_computed_ciphertext, aes_ecb_known_ciphertext, - FIPS_AES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* AES-ECB Single-Round Known Answer Decryption Test: */ - /******************************************************/ - - aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_FALSE, - aes_key_size, FIPS_AES_BLOCK_SIZE ); - - if( aes_context == NULL ) - return( CKR_HOST_MEMORY ); - - aes_status = AES_Decrypt( aes_context, aes_computed_plaintext, - &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH, - aes_ecb_known_ciphertext, - FIPS_AES_ENCRYPT_LENGTH ); - - AES_DestroyContext( aes_context, PR_TRUE ); - - if( ( aes_status != SECSuccess ) || - ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext, - FIPS_AES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* AES-CBC Single-Round Known Answer Encryption Test. */ - /******************************************************/ - - aes_context = AES_CreateContext( aes_known_key, - aes_cbc_known_initialization_vector, - NSS_AES_CBC, PR_TRUE, aes_key_size, - FIPS_AES_BLOCK_SIZE ); - - if( aes_context == NULL ) - return( CKR_HOST_MEMORY ); - - aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext, - &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH, - aes_known_plaintext, - FIPS_AES_DECRYPT_LENGTH ); - - AES_DestroyContext( aes_context, PR_TRUE ); - - if( ( aes_status != SECSuccess ) || - ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) || - ( PORT_Memcmp( aes_computed_ciphertext, aes_cbc_known_ciphertext, - FIPS_AES_ENCRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - - /******************************************************/ - /* AES-CBC Single-Round Known Answer Decryption Test. */ - /******************************************************/ - - aes_context = AES_CreateContext( aes_known_key, - aes_cbc_known_initialization_vector, - NSS_AES_CBC, PR_FALSE, aes_key_size, - FIPS_AES_BLOCK_SIZE ); - - if( aes_context == NULL ) - return( CKR_HOST_MEMORY ); - - aes_status = AES_Decrypt( aes_context, aes_computed_plaintext, - &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH, - aes_cbc_known_ciphertext, - FIPS_AES_ENCRYPT_LENGTH ); - - AES_DestroyContext( aes_context, PR_TRUE ); - - if( ( aes_status != SECSuccess ) || - ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) || - ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext, - FIPS_AES_DECRYPT_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - -/* Known Hash Message (512-bits). Used for all hashes (incl. SHA-N [N>1]). */ -static const PRUint8 known_hash_message[] = { - "The test message for the MD2, MD5, and SHA-1 hashing algorithms." }; - - -static CK_RV -sftk_fips_MD2_PowerUpSelfTest( void ) -{ - /* MD2 Known Digest Message (128-bits). */ - static const PRUint8 md2_known_digest[] = { - 0x41,0x5a,0x12,0xb2,0x3f,0x28,0x97,0x17, - 0x0c,0x71,0x4e,0xcc,0x40,0xc8,0x1d,0x1b}; - - /* MD2 variables. */ - MD2Context * md2_context; - unsigned int md2_bytes_hashed; - PRUint8 md2_computed_digest[MD2_LENGTH]; - - - /***********************************************/ - /* MD2 Single-Round Known Answer Hashing Test. */ - /***********************************************/ - - md2_context = MD2_NewContext(); - - if( md2_context == NULL ) - return( CKR_HOST_MEMORY ); - - MD2_Begin( md2_context ); - - MD2_Update( md2_context, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - MD2_End( md2_context, md2_computed_digest, &md2_bytes_hashed, MD2_LENGTH ); - - MD2_DestroyContext( md2_context , PR_TRUE ); - - if( ( md2_bytes_hashed != MD2_LENGTH ) || - ( PORT_Memcmp( md2_computed_digest, md2_known_digest, - MD2_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - - -static CK_RV -sftk_fips_MD5_PowerUpSelfTest( void ) -{ - /* MD5 Known Digest Message (128-bits). */ - static const PRUint8 md5_known_digest[] = { - 0x25,0xc8,0xc0,0x10,0xc5,0x6e,0x68,0x28, - 0x28,0xa4,0xa5,0xd2,0x98,0x9a,0xea,0x2d}; - - /* MD5 variables. */ - PRUint8 md5_computed_digest[MD5_LENGTH]; - SECStatus md5_status; - - - /***********************************************/ - /* MD5 Single-Round Known Answer Hashing Test. */ - /***********************************************/ - - md5_status = MD5_HashBuf( md5_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( md5_status != SECSuccess ) || - ( PORT_Memcmp( md5_computed_digest, md5_known_digest, - MD5_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - -/****************************************************/ -/* Single Round HMAC SHA-X test */ -/****************************************************/ -static SECStatus -sftk_fips_HMAC(unsigned char *hmac_computed, - const PRUint8 *secret_key, - unsigned int secret_key_length, - const PRUint8 *message, - unsigned int message_length, - HASH_HashType hashAlg ) -{ - SECStatus hmac_status = SECFailure; - HMACContext *cx = NULL; - SECHashObject *hashObj = NULL; - unsigned int bytes_hashed = 0; - - hashObj = (SECHashObject *) HASH_GetRawHashObject(hashAlg); - - if (!hashObj) - return( SECFailure ); - - cx = HMAC_Create(hashObj, secret_key, - secret_key_length, - PR_TRUE); /* PR_TRUE for in FIPS mode */ - - if (cx == NULL) - return( SECFailure ); - - HMAC_Begin(cx); - HMAC_Update(cx, message, message_length); - hmac_status = HMAC_Finish(cx, hmac_computed, &bytes_hashed, - hashObj->length); - - HMAC_Destroy(cx, PR_TRUE); +static void INIT_FUNCTION sftk_startup_tests(void); - return( hmac_status ); -} +/* Windows pre-defined entry */ +#if defined(XP_WIN) && !defined(NSS_NO_INIT_SUPPORT) +#include <windows.h> -static CK_RV -sftk_fips_HMAC_PowerUpSelfTest( void ) +BOOL WINAPI DllMain( + HINSTANCE hinstDLL, // handle to DLL module + DWORD fdwReason, // reason for calling function + LPVOID lpReserved) // reserved { - static const PRUint8 HMAC_known_secret_key[] = { - "Firefox and ThunderBird are awesome!"}; - - static const PRUint8 HMAC_known_secret_key_length - = sizeof HMAC_known_secret_key; - - /* known SHA1 hmac (20 bytes) */ - static const PRUint8 known_SHA1_hmac[] = { - 0xd5, 0x85, 0xf6, 0x5b, 0x39, 0xfa, 0xb9, 0x05, - 0x3b, 0x57, 0x1d, 0x61, 0xe7, 0xb8, 0x84, 0x1e, - 0x5d, 0x0e, 0x1e, 0x11}; - - /* known SHA224 hmac (28 bytes) */ - static const PRUint8 known_SHA224_hmac[] = { - 0x1c, 0xc3, 0x06, 0x8e, 0xce, 0x37, 0x68, 0xfb, - 0x1a, 0x82, 0x4a, 0xbe, 0x2b, 0x00, 0x51, 0xf8, - 0x9d, 0xb6, 0xe0, 0x90, 0x0d, 0x00, 0xc9, 0x64, - 0x9a, 0xb8, 0x98, 0x4e}; - - /* known SHA256 hmac (32 bytes) */ - static const PRUint8 known_SHA256_hmac[] = { - 0x05, 0x75, 0x9a, 0x9e, 0x70, 0x5e, 0xe7, 0x44, - 0xe2, 0x46, 0x4b, 0x92, 0x22, 0x14, 0x22, 0xe0, - 0x1b, 0x92, 0x8a, 0x0c, 0xfe, 0xf5, 0x49, 0xe9, - 0xa7, 0x1b, 0x56, 0x7d, 0x1d, 0x29, 0x40, 0x48}; - - /* known SHA384 hmac (48 bytes) */ - static const PRUint8 known_SHA384_hmac[] = { - 0xcd, 0x56, 0x14, 0xec, 0x05, 0x53, 0x06, 0x2b, - 0x7e, 0x9c, 0x8a, 0x18, 0x5e, 0xea, 0xf3, 0x91, - 0x33, 0xfb, 0x64, 0xf6, 0xe3, 0x9f, 0x89, 0x0b, - 0xaf, 0xbe, 0x83, 0x4d, 0x3f, 0x3c, 0x43, 0x4d, - 0x4a, 0x0c, 0x56, 0x98, 0xf8, 0xca, 0xb4, 0xaa, - 0x9a, 0xf4, 0x0a, 0xaf, 0x4f, 0x69, 0xca, 0x87}; - - /* known SHA512 hmac (64 bytes) */ - static const PRUint8 known_SHA512_hmac[] = { - 0xf6, 0x0e, 0x97, 0x12, 0x00, 0x67, 0x6e, 0xb9, - 0x0c, 0xb2, 0x63, 0xf0, 0x60, 0xac, 0x75, 0x62, - 0x70, 0x95, 0x2a, 0x52, 0x22, 0xee, 0xdd, 0xd2, - 0x71, 0xb1, 0xe8, 0x26, 0x33, 0xd3, 0x13, 0x27, - 0xcb, 0xff, 0x44, 0xef, 0x87, 0x97, 0x16, 0xfb, - 0xd3, 0x0b, 0x48, 0xbe, 0x12, 0x4e, 0xda, 0xb1, - 0x89, 0x90, 0xfb, 0x06, 0x0c, 0xbe, 0xe5, 0xc4, - 0xff, 0x24, 0x37, 0x3d, 0xc7, 0xe4, 0xe4, 0x37}; - - SECStatus hmac_status; - PRUint8 hmac_computed[HASH_LENGTH_MAX]; - - /***************************************************/ - /* HMAC SHA-1 Single-Round Known Answer HMAC Test. */ - /***************************************************/ - - hmac_status = sftk_fips_HMAC(hmac_computed, - HMAC_known_secret_key, - HMAC_known_secret_key_length, - known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH, - HASH_AlgSHA1); - - if( ( hmac_status != SECSuccess ) || - ( PORT_Memcmp( hmac_computed, known_SHA1_hmac, - SHA1_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* HMAC SHA-224 Single-Round Known Answer Test. */ - /***************************************************/ - - hmac_status = sftk_fips_HMAC(hmac_computed, - HMAC_known_secret_key, - HMAC_known_secret_key_length, - known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH, - HASH_AlgSHA224); - - if( ( hmac_status != SECSuccess ) || - ( PORT_Memcmp( hmac_computed, known_SHA224_hmac, - SHA224_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* HMAC SHA-256 Single-Round Known Answer Test. */ - /***************************************************/ - - hmac_status = sftk_fips_HMAC(hmac_computed, - HMAC_known_secret_key, - HMAC_known_secret_key_length, - known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH, - HASH_AlgSHA256); - - if( ( hmac_status != SECSuccess ) || - ( PORT_Memcmp( hmac_computed, known_SHA256_hmac, - SHA256_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* HMAC SHA-384 Single-Round Known Answer Test. */ - /***************************************************/ - - hmac_status = sftk_fips_HMAC(hmac_computed, - HMAC_known_secret_key, - HMAC_known_secret_key_length, - known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH, - HASH_AlgSHA384); - - if( ( hmac_status != SECSuccess ) || - ( PORT_Memcmp( hmac_computed, known_SHA384_hmac, - SHA384_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* HMAC SHA-512 Single-Round Known Answer Test. */ - /***************************************************/ - - hmac_status = sftk_fips_HMAC(hmac_computed, - HMAC_known_secret_key, - HMAC_known_secret_key_length, - known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH, - HASH_AlgSHA512); - - if( ( hmac_status != SECSuccess ) || - ( PORT_Memcmp( hmac_computed, known_SHA512_hmac, - SHA512_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); + // Perform actions based on the reason for calling. + switch (fdwReason) { + case DLL_PROCESS_ATTACH: + // Initialize once for each new process. + // Return FALSE to fail DLL load. + sftk_startup_tests(); + break; + + case DLL_THREAD_ATTACH: + // Do thread-specific initialization. + break; + + case DLL_THREAD_DETACH: + // Do thread-specific cleanup. + break; + + case DLL_PROCESS_DETACH: + // Perform any necessary cleanup. + break; + } + return TRUE; // Successful DLL_PROCESS_ATTACH. } +#endif -static CK_RV -sftk_fips_SHA_PowerUpSelfTest( void ) -{ - /* SHA-1 Known Digest Message (160-bits). */ - static const PRUint8 sha1_known_digest[] = { - 0x0a,0x6d,0x07,0xba,0x1e,0xbd,0x8a,0x1b, - 0x72,0xf6,0xc7,0x22,0xf1,0x27,0x9f,0xf0, - 0xe0,0x68,0x47,0x7a}; - - /* SHA-224 Known Digest Message (224-bits). */ - static const PRUint8 sha224_known_digest[] = { - 0x89,0x5e,0x7f,0xfd,0x0e,0xd8,0x35,0x6f, - 0x64,0x6d,0xf2,0xde,0x5e,0xed,0xa6,0x7f, - 0x29,0xd1,0x12,0x73,0x42,0x84,0x95,0x4f, - 0x8e,0x08,0xe5,0xcb}; - - /* SHA-256 Known Digest Message (256-bits). */ - static const PRUint8 sha256_known_digest[] = { - 0x38,0xa9,0xc1,0xf0,0x35,0xf6,0x5d,0x61, - 0x11,0xd4,0x0b,0xdc,0xce,0x35,0x14,0x8d, - 0xf2,0xdd,0xaf,0xaf,0xcf,0xb7,0x87,0xe9, - 0x96,0xa5,0xd2,0x83,0x62,0x46,0x56,0x79}; - - /* SHA-384 Known Digest Message (384-bits). */ - static const PRUint8 sha384_known_digest[] = { - 0x11,0xfe,0x1c,0x00,0x89,0x48,0xde,0xb3, - 0x99,0xee,0x1c,0x18,0xb4,0x10,0xfb,0xfe, - 0xe3,0xa8,0x2c,0xf3,0x04,0xb0,0x2f,0xc8, - 0xa3,0xc4,0x5e,0xea,0x7e,0x60,0x48,0x7b, - 0xce,0x2c,0x62,0xf7,0xbc,0xa7,0xe8,0xa3, - 0xcf,0x24,0xce,0x9c,0xe2,0x8b,0x09,0x72}; - - /* SHA-512 Known Digest Message (512-bits). */ - static const PRUint8 sha512_known_digest[] = { - 0xc8,0xb3,0x27,0xf9,0x0b,0x24,0xc8,0xbf, - 0x4c,0xba,0x33,0x54,0xf2,0x31,0xbf,0xdb, - 0xab,0xfd,0xb3,0x15,0xd7,0xfa,0x48,0x99, - 0x07,0x60,0x0f,0x57,0x41,0x1a,0xdd,0x28, - 0x12,0x55,0x25,0xac,0xba,0x3a,0x99,0x12, - 0x2c,0x7a,0x8f,0x75,0x3a,0xe1,0x06,0x6f, - 0x30,0x31,0xc9,0x33,0xc6,0x1b,0x90,0x1a, - 0x6c,0x98,0x9a,0x87,0xd0,0xb2,0xf8,0x07}; - - /* SHA-X variables. */ - PRUint8 sha_computed_digest[HASH_LENGTH_MAX]; - SECStatus sha_status; - - /*************************************************/ - /* SHA-1 Single-Round Known Answer Hashing Test. */ - /*************************************************/ - - sha_status = SHA1_HashBuf( sha_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( sha_status != SECSuccess ) || - ( PORT_Memcmp( sha_computed_digest, sha1_known_digest, - SHA1_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* SHA-224 Single-Round Known Answer Hashing Test. */ - /***************************************************/ - - sha_status = SHA224_HashBuf( sha_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( sha_status != SECSuccess ) || - ( PORT_Memcmp( sha_computed_digest, sha224_known_digest, - SHA224_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* SHA-256 Single-Round Known Answer Hashing Test. */ - /***************************************************/ - - sha_status = SHA256_HashBuf( sha_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( sha_status != SECSuccess ) || - ( PORT_Memcmp( sha_computed_digest, sha256_known_digest, - SHA256_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* SHA-384 Single-Round Known Answer Hashing Test. */ - /***************************************************/ - - sha_status = SHA384_HashBuf( sha_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( sha_status != SECSuccess ) || - ( PORT_Memcmp( sha_computed_digest, sha384_known_digest, - SHA384_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - /***************************************************/ - /* SHA-512 Single-Round Known Answer Hashing Test. */ - /***************************************************/ - - sha_status = SHA512_HashBuf( sha_computed_digest, known_hash_message, - FIPS_KNOWN_HASH_MESSAGE_LENGTH ); - - if( ( sha_status != SECSuccess ) || - ( PORT_Memcmp( sha_computed_digest, sha512_known_digest, - SHA512_LENGTH ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} +/* FIPS preprocessor directives for RSA. */ +#define FIPS_RSA_TYPE siBuffer +#define FIPS_RSA_PUBLIC_EXPONENT_LENGTH 3 /* 24-bits */ +#define FIPS_RSA_PRIVATE_VERSION_LENGTH 1 /* 8-bits */ +#define FIPS_RSA_MESSAGE_LENGTH 256 /* 2048-bits */ +#define FIPS_RSA_COEFFICIENT_LENGTH 128 /* 1024-bits */ +#define FIPS_RSA_PRIME0_LENGTH 128 /* 1024-bits */ +#define FIPS_RSA_PRIME1_LENGTH 128 /* 1024-bits */ +#define FIPS_RSA_EXPONENT0_LENGTH 128 /* 1024-bits */ +#define FIPS_RSA_EXPONENT1_LENGTH 128 /* 1024-bits */ +#define FIPS_RSA_PRIVATE_EXPONENT_LENGTH 256 /* 2048-bits */ +#define FIPS_RSA_ENCRYPT_LENGTH 256 /* 2048-bits */ +#define FIPS_RSA_DECRYPT_LENGTH 256 /* 2048-bits */ +#define FIPS_RSA_SIGNATURE_LENGTH 256 /* 2048-bits */ +#define FIPS_RSA_MODULUS_LENGTH 256 /* 2048-bits */ /* -* Single round RSA Signature Known Answer Test +* Test the softoken RSA_HashSign and RSH_HashCheckSign. */ static SECStatus -sftk_fips_RSA_PowerUpSigSelfTest (HASH_HashType shaAlg, - NSSLOWKEYPublicKey *rsa_public_key, - NSSLOWKEYPrivateKey *rsa_private_key, - const unsigned char *rsa_known_msg, - const unsigned int rsa_kmsg_length, - const unsigned char *rsa_known_signature) +sftk_fips_RSA_PowerUpSigSelfTest(HASH_HashType shaAlg, + NSSLOWKEYPublicKey *rsa_public_key, + NSSLOWKEYPrivateKey *rsa_private_key, + const unsigned char *rsa_known_msg, + const unsigned int rsa_kmsg_length, + const unsigned char *rsa_known_signature) { - SECOidTag shaOid; /* SHA OID */ - unsigned char sha[HASH_LENGTH_MAX]; /* SHA digest */ - unsigned int shaLength = 0; /* length of SHA */ - unsigned int rsa_bytes_signed; - unsigned char rsa_computed_signature[FIPS_RSA_SIGNATURE_LENGTH]; - SECStatus rv; + SECOidTag shaOid; /* SHA OID */ + unsigned char sha[HASH_LENGTH_MAX]; /* SHA digest */ + unsigned int shaLength = 0; /* length of SHA */ + unsigned int rsa_bytes_signed; + unsigned char rsa_computed_signature[FIPS_RSA_SIGNATURE_LENGTH]; + SECStatus rv; if (shaAlg == HASH_AlgSHA1) { - if (SHA1_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) - != SECSuccess) { - goto loser; + if (SHA1_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) != SECSuccess) { + goto loser; } shaLength = SHA1_LENGTH; shaOid = SEC_OID_SHA1; } else if (shaAlg == HASH_AlgSHA256) { - if (SHA256_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) - != SECSuccess) { - goto loser; + if (SHA256_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) != SECSuccess) { + goto loser; } shaLength = SHA256_LENGTH; shaOid = SEC_OID_SHA256; } else if (shaAlg == HASH_AlgSHA384) { - if (SHA384_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) - != SECSuccess) { - goto loser; + if (SHA384_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) != SECSuccess) { + goto loser; } shaLength = SHA384_LENGTH; shaOid = SEC_OID_SHA384; } else if (shaAlg == HASH_AlgSHA512) { - if (SHA512_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) - != SECSuccess) { - goto loser; + if (SHA512_HashBuf(sha, rsa_known_msg, rsa_kmsg_length) != SECSuccess) { + goto loser; } shaLength = SHA512_LENGTH; shaOid = SEC_OID_SHA512; @@ -1117,18 +133,18 @@ sftk_fips_RSA_PowerUpSigSelfTest (HASH_HashType shaAlg, /*************************************************/ /* Perform RSA signature with the RSA private key. */ - rv = RSA_HashSign( shaOid, - rsa_private_key, - rsa_computed_signature, - &rsa_bytes_signed, - FIPS_RSA_SIGNATURE_LENGTH, - sha, - shaLength); - - if( ( rv != SECSuccess ) || - ( rsa_bytes_signed != FIPS_RSA_SIGNATURE_LENGTH ) || - ( PORT_Memcmp( rsa_computed_signature, rsa_known_signature, - FIPS_RSA_SIGNATURE_LENGTH ) != 0 ) ) { + rv = RSA_HashSign(shaOid, + rsa_private_key, + rsa_computed_signature, + &rsa_bytes_signed, + FIPS_RSA_SIGNATURE_LENGTH, + sha, + shaLength); + + if ((rv != SECSuccess) || + (rsa_bytes_signed != FIPS_RSA_SIGNATURE_LENGTH) || + (PORT_Memcmp(rsa_computed_signature, rsa_known_signature, + FIPS_RSA_SIGNATURE_LENGTH) != 0)) { goto loser; } @@ -1137,65 +153,64 @@ sftk_fips_RSA_PowerUpSigSelfTest (HASH_HashType shaAlg, /****************************************************/ /* Perform RSA verification with the RSA public key. */ - rv = RSA_HashCheckSign( shaOid, - rsa_public_key, - rsa_computed_signature, - rsa_bytes_signed, - sha, - shaLength); - - if( rv != SECSuccess ) { - goto loser; + rv = RSA_HashCheckSign(shaOid, + rsa_public_key, + rsa_computed_signature, + rsa_bytes_signed, + sha, + shaLength); + + if (rv != SECSuccess) { + goto loser; } - return( SECSuccess ); + return (SECSuccess); loser: - return( SECFailure ); - + return (SECFailure); } -static CK_RV -sftk_fips_RSA_PowerUpSelfTest( void ) +static SECStatus +sftk_fips_RSA_PowerUpSelfTest(void) { /* RSA Known Modulus used in both Public/Private Key Values (2048-bits). */ static const PRUint8 rsa_modulus[FIPS_RSA_MODULUS_LENGTH] = { - 0xb8, 0x15, 0x00, 0x33, 0xda, 0x0c, 0x9d, 0xa5, - 0x14, 0x8c, 0xde, 0x1f, 0x23, 0x07, 0x54, 0xe2, - 0xc6, 0xb9, 0x51, 0x04, 0xc9, 0x65, 0x24, 0x6e, - 0x0a, 0x46, 0x34, 0x5c, 0x37, 0x86, 0x6b, 0x88, - 0x24, 0x27, 0xac, 0xa5, 0x02, 0x79, 0xfb, 0xed, - 0x75, 0xc5, 0x3f, 0x6e, 0xdf, 0x05, 0x5f, 0x0f, - 0x20, 0x70, 0xa0, 0x5b, 0x85, 0xdb, 0xac, 0xb9, - 0x5f, 0x02, 0xc2, 0x64, 0x1e, 0x84, 0x5b, 0x3e, - 0xad, 0xbf, 0xf6, 0x2e, 0x51, 0xd6, 0xad, 0xf7, - 0xa7, 0x86, 0x75, 0x86, 0xec, 0xa7, 0xe1, 0xf7, - 0x08, 0xbf, 0xdc, 0x56, 0xb1, 0x3b, 0xca, 0xd8, - 0xfc, 0x51, 0xdf, 0x9a, 0x2a, 0x37, 0x06, 0xf2, - 0xd1, 0x6b, 0x9a, 0x5e, 0x2a, 0xe5, 0x20, 0x57, - 0x35, 0x9f, 0x1f, 0x98, 0xcf, 0x40, 0xc7, 0xd6, - 0x98, 0xdb, 0xde, 0xf5, 0x64, 0x53, 0xf7, 0x9d, - 0x45, 0xf3, 0xd6, 0x78, 0xb9, 0xe3, 0xa3, 0x20, - 0xcd, 0x79, 0x43, 0x35, 0xef, 0xd7, 0xfb, 0xb9, - 0x80, 0x88, 0x27, 0x2f, 0x63, 0xa8, 0x67, 0x3d, - 0x4a, 0xfa, 0x06, 0xc6, 0xd2, 0x86, 0x0b, 0xa7, - 0x28, 0xfd, 0xe0, 0x1e, 0x93, 0x4b, 0x17, 0x2e, - 0xb0, 0x11, 0x6f, 0xc6, 0x2b, 0x98, 0x0f, 0x15, - 0xe3, 0x87, 0x16, 0x7a, 0x7c, 0x67, 0x3e, 0x12, - 0x2b, 0xf8, 0xbe, 0x48, 0xc1, 0x97, 0x47, 0xf4, - 0x1f, 0x81, 0x80, 0x12, 0x28, 0xe4, 0x7b, 0x1e, - 0xb7, 0x00, 0xa4, 0xde, 0xaa, 0xfb, 0x0f, 0x77, - 0x84, 0xa3, 0xd6, 0xb2, 0x03, 0x48, 0xdd, 0x53, - 0x8b, 0x46, 0x41, 0x28, 0x52, 0xc4, 0x53, 0xf0, - 0x1c, 0x95, 0xd9, 0x36, 0xe0, 0x0f, 0x26, 0x46, - 0x9c, 0x61, 0x0e, 0x80, 0xca, 0x86, 0xaf, 0x39, - 0x95, 0xe5, 0x60, 0x43, 0x61, 0x3e, 0x2b, 0xb4, - 0xe8, 0xbd, 0x8d, 0x77, 0x62, 0xf5, 0x32, 0x43, - 0x2f, 0x4b, 0x65, 0x82, 0x14, 0xdd, 0x29, 0x5b}; + 0xb8, 0x15, 0x00, 0x33, 0xda, 0x0c, 0x9d, 0xa5, + 0x14, 0x8c, 0xde, 0x1f, 0x23, 0x07, 0x54, 0xe2, + 0xc6, 0xb9, 0x51, 0x04, 0xc9, 0x65, 0x24, 0x6e, + 0x0a, 0x46, 0x34, 0x5c, 0x37, 0x86, 0x6b, 0x88, + 0x24, 0x27, 0xac, 0xa5, 0x02, 0x79, 0xfb, 0xed, + 0x75, 0xc5, 0x3f, 0x6e, 0xdf, 0x05, 0x5f, 0x0f, + 0x20, 0x70, 0xa0, 0x5b, 0x85, 0xdb, 0xac, 0xb9, + 0x5f, 0x02, 0xc2, 0x64, 0x1e, 0x84, 0x5b, 0x3e, + 0xad, 0xbf, 0xf6, 0x2e, 0x51, 0xd6, 0xad, 0xf7, + 0xa7, 0x86, 0x75, 0x86, 0xec, 0xa7, 0xe1, 0xf7, + 0x08, 0xbf, 0xdc, 0x56, 0xb1, 0x3b, 0xca, 0xd8, + 0xfc, 0x51, 0xdf, 0x9a, 0x2a, 0x37, 0x06, 0xf2, + 0xd1, 0x6b, 0x9a, 0x5e, 0x2a, 0xe5, 0x20, 0x57, + 0x35, 0x9f, 0x1f, 0x98, 0xcf, 0x40, 0xc7, 0xd6, + 0x98, 0xdb, 0xde, 0xf5, 0x64, 0x53, 0xf7, 0x9d, + 0x45, 0xf3, 0xd6, 0x78, 0xb9, 0xe3, 0xa3, 0x20, + 0xcd, 0x79, 0x43, 0x35, 0xef, 0xd7, 0xfb, 0xb9, + 0x80, 0x88, 0x27, 0x2f, 0x63, 0xa8, 0x67, 0x3d, + 0x4a, 0xfa, 0x06, 0xc6, 0xd2, 0x86, 0x0b, 0xa7, + 0x28, 0xfd, 0xe0, 0x1e, 0x93, 0x4b, 0x17, 0x2e, + 0xb0, 0x11, 0x6f, 0xc6, 0x2b, 0x98, 0x0f, 0x15, + 0xe3, 0x87, 0x16, 0x7a, 0x7c, 0x67, 0x3e, 0x12, + 0x2b, 0xf8, 0xbe, 0x48, 0xc1, 0x97, 0x47, 0xf4, + 0x1f, 0x81, 0x80, 0x12, 0x28, 0xe4, 0x7b, 0x1e, + 0xb7, 0x00, 0xa4, 0xde, 0xaa, 0xfb, 0x0f, 0x77, + 0x84, 0xa3, 0xd6, 0xb2, 0x03, 0x48, 0xdd, 0x53, + 0x8b, 0x46, 0x41, 0x28, 0x52, 0xc4, 0x53, 0xf0, + 0x1c, 0x95, 0xd9, 0x36, 0xe0, 0x0f, 0x26, 0x46, + 0x9c, 0x61, 0x0e, 0x80, 0xca, 0x86, 0xaf, 0x39, + 0x95, 0xe5, 0x60, 0x43, 0x61, 0x3e, 0x2b, 0xb4, + 0xe8, 0xbd, 0x8d, 0x77, 0x62, 0xf5, 0x32, 0x43, + 0x2f, 0x4b, 0x65, 0x82, 0x14, 0xdd, 0x29, 0x5b + }; /* RSA Known Public Key Values (24-bits). */ - static const PRUint8 rsa_public_exponent[FIPS_RSA_PUBLIC_EXPONENT_LENGTH] - = { 0x01, 0x00, 0x01 }; + static const PRUint8 rsa_public_exponent[FIPS_RSA_PUBLIC_EXPONENT_LENGTH] = { 0x01, 0x00, 0x01 }; /* RSA Known Private Key Values (version is 8-bits), */ /* (private exponent is 2048-bits), */ /* (private prime0 is 1024-bits), */ @@ -1205,344 +220,319 @@ sftk_fips_RSA_PowerUpSelfTest( void ) /* and (private coefficient is 1024-bits). */ static const PRUint8 rsa_version[] = { 0x00 }; - static const PRUint8 rsa_private_exponent[FIPS_RSA_PRIVATE_EXPONENT_LENGTH] - = {0x29, 0x08, 0x05, 0x53, 0x89, 0x76, 0xe6, 0x6c, - 0xb5, 0x77, 0xf0, 0xca, 0xdf, 0xf3, 0xf2, 0x67, - 0xda, 0x03, 0xd4, 0x9b, 0x4c, 0x88, 0xce, 0xe5, - 0xf8, 0x44, 0x4d, 0xc7, 0x80, 0x58, 0xe5, 0xff, - 0x22, 0x8f, 0xf5, 0x5b, 0x92, 0x81, 0xbe, 0x35, - 0xdf, 0xda, 0x67, 0x99, 0x3e, 0xfc, 0xe3, 0x83, - 0x6b, 0xa7, 0xaf, 0x16, 0xb7, 0x6f, 0x8f, 0xc0, - 0x81, 0xfd, 0x0b, 0x77, 0x65, 0x95, 0xfb, 0x00, - 0xad, 0x99, 0xec, 0x35, 0xc6, 0xe8, 0x23, 0x3e, - 0xe0, 0x88, 0x88, 0x09, 0xdb, 0x16, 0x50, 0xb7, - 0xcf, 0xab, 0x74, 0x61, 0x9e, 0x7f, 0xc5, 0x67, - 0x38, 0x56, 0xc7, 0x90, 0x85, 0x78, 0x5e, 0x84, - 0x21, 0x49, 0xea, 0xce, 0xb2, 0xa0, 0xff, 0xe4, - 0x70, 0x7f, 0x57, 0x7b, 0xa8, 0x36, 0xb8, 0x54, - 0x8d, 0x1d, 0xf5, 0x44, 0x9d, 0x68, 0x59, 0xf9, - 0x24, 0x6e, 0x85, 0x8f, 0xc3, 0x5f, 0x8a, 0x2c, - 0x94, 0xb7, 0xbc, 0x0e, 0xa5, 0xef, 0x93, 0x06, - 0x38, 0xcd, 0x07, 0x0c, 0xae, 0xb8, 0x44, 0x1a, - 0xd8, 0xe7, 0xf5, 0x9a, 0x1e, 0x9c, 0x18, 0xc7, - 0x6a, 0xc2, 0x7f, 0x28, 0x01, 0x4f, 0xb4, 0xb8, - 0x90, 0x97, 0x5a, 0x43, 0x38, 0xad, 0xe8, 0x95, - 0x68, 0x83, 0x1a, 0x1b, 0x10, 0x07, 0xe6, 0x02, - 0x52, 0x1f, 0xbf, 0x76, 0x6b, 0x46, 0xd6, 0xfb, - 0xc3, 0xbe, 0xb5, 0xac, 0x52, 0x53, 0x01, 0x1c, - 0xf3, 0xc5, 0xeb, 0x64, 0xf2, 0x1e, 0xc4, 0x38, - 0xe9, 0xaa, 0xd9, 0xc3, 0x72, 0x51, 0xa5, 0x44, - 0x58, 0x69, 0x0b, 0x1b, 0x98, 0x7f, 0xf2, 0x23, - 0xff, 0xeb, 0xf0, 0x75, 0x24, 0xcf, 0xc5, 0x1e, - 0xb8, 0x6a, 0xc5, 0x2f, 0x4f, 0x23, 0x50, 0x7d, - 0x15, 0x9d, 0x19, 0x7a, 0x0b, 0x82, 0xe0, 0x21, - 0x5b, 0x5f, 0x9d, 0x50, 0x2b, 0x83, 0xe4, 0x48, - 0xcc, 0x39, 0xe5, 0xfb, 0x13, 0x7b, 0x6f, 0x81 }; + static const PRUint8 rsa_private_exponent[FIPS_RSA_PRIVATE_EXPONENT_LENGTH] = { + 0x29, 0x08, 0x05, 0x53, 0x89, 0x76, 0xe6, 0x6c, + 0xb5, 0x77, 0xf0, 0xca, 0xdf, 0xf3, 0xf2, 0x67, + 0xda, 0x03, 0xd4, 0x9b, 0x4c, 0x88, 0xce, 0xe5, + 0xf8, 0x44, 0x4d, 0xc7, 0x80, 0x58, 0xe5, 0xff, + 0x22, 0x8f, 0xf5, 0x5b, 0x92, 0x81, 0xbe, 0x35, + 0xdf, 0xda, 0x67, 0x99, 0x3e, 0xfc, 0xe3, 0x83, + 0x6b, 0xa7, 0xaf, 0x16, 0xb7, 0x6f, 0x8f, 0xc0, + 0x81, 0xfd, 0x0b, 0x77, 0x65, 0x95, 0xfb, 0x00, + 0xad, 0x99, 0xec, 0x35, 0xc6, 0xe8, 0x23, 0x3e, + 0xe0, 0x88, 0x88, 0x09, 0xdb, 0x16, 0x50, 0xb7, + 0xcf, 0xab, 0x74, 0x61, 0x9e, 0x7f, 0xc5, 0x67, + 0x38, 0x56, 0xc7, 0x90, 0x85, 0x78, 0x5e, 0x84, + 0x21, 0x49, 0xea, 0xce, 0xb2, 0xa0, 0xff, 0xe4, + 0x70, 0x7f, 0x57, 0x7b, 0xa8, 0x36, 0xb8, 0x54, + 0x8d, 0x1d, 0xf5, 0x44, 0x9d, 0x68, 0x59, 0xf9, + 0x24, 0x6e, 0x85, 0x8f, 0xc3, 0x5f, 0x8a, 0x2c, + 0x94, 0xb7, 0xbc, 0x0e, 0xa5, 0xef, 0x93, 0x06, + 0x38, 0xcd, 0x07, 0x0c, 0xae, 0xb8, 0x44, 0x1a, + 0xd8, 0xe7, 0xf5, 0x9a, 0x1e, 0x9c, 0x18, 0xc7, + 0x6a, 0xc2, 0x7f, 0x28, 0x01, 0x4f, 0xb4, 0xb8, + 0x90, 0x97, 0x5a, 0x43, 0x38, 0xad, 0xe8, 0x95, + 0x68, 0x83, 0x1a, 0x1b, 0x10, 0x07, 0xe6, 0x02, + 0x52, 0x1f, 0xbf, 0x76, 0x6b, 0x46, 0xd6, 0xfb, + 0xc3, 0xbe, 0xb5, 0xac, 0x52, 0x53, 0x01, 0x1c, + 0xf3, 0xc5, 0xeb, 0x64, 0xf2, 0x1e, 0xc4, 0x38, + 0xe9, 0xaa, 0xd9, 0xc3, 0x72, 0x51, 0xa5, 0x44, + 0x58, 0x69, 0x0b, 0x1b, 0x98, 0x7f, 0xf2, 0x23, + 0xff, 0xeb, 0xf0, 0x75, 0x24, 0xcf, 0xc5, 0x1e, + 0xb8, 0x6a, 0xc5, 0x2f, 0x4f, 0x23, 0x50, 0x7d, + 0x15, 0x9d, 0x19, 0x7a, 0x0b, 0x82, 0xe0, 0x21, + 0x5b, 0x5f, 0x9d, 0x50, 0x2b, 0x83, 0xe4, 0x48, + 0xcc, 0x39, 0xe5, 0xfb, 0x13, 0x7b, 0x6f, 0x81 + }; - static const PRUint8 rsa_prime0[FIPS_RSA_PRIME0_LENGTH] = { - 0xe4, 0xbf, 0x21, 0x62, 0x9b, 0xa9, 0x77, 0x40, - 0x8d, 0x2a, 0xce, 0xa1, 0x67, 0x5a, 0x4c, 0x96, - 0x45, 0x98, 0x67, 0xbd, 0x75, 0x22, 0x33, 0x6f, - 0xe6, 0xcb, 0x77, 0xde, 0x9e, 0x97, 0x7d, 0x96, - 0x8c, 0x5e, 0x5d, 0x34, 0xfb, 0x27, 0xfc, 0x6d, - 0x74, 0xdb, 0x9d, 0x2e, 0x6d, 0xf6, 0xea, 0xfc, - 0xce, 0x9e, 0xda, 0xa7, 0x25, 0xa2, 0xf4, 0x58, - 0x6d, 0x0a, 0x3f, 0x01, 0xc2, 0xb4, 0xab, 0x38, - 0xc1, 0x14, 0x85, 0xb6, 0xfa, 0x94, 0xc3, 0x85, - 0xf9, 0x3c, 0x2e, 0x96, 0x56, 0x01, 0xe7, 0xd6, - 0x14, 0x71, 0x4f, 0xfb, 0x4c, 0x85, 0x52, 0xc4, - 0x61, 0x1e, 0xa5, 0x1e, 0x96, 0x13, 0x0d, 0x8f, - 0x66, 0xae, 0xa0, 0xcd, 0x7d, 0x25, 0x66, 0x19, - 0x15, 0xc2, 0xcf, 0xc3, 0x12, 0x3c, 0xe8, 0xa4, - 0x52, 0x4c, 0xcb, 0x28, 0x3c, 0xc4, 0xbf, 0x95, - 0x33, 0xe3, 0x81, 0xea, 0x0c, 0x6c, 0xa2, 0x05}; - static const PRUint8 rsa_prime1[FIPS_RSA_PRIME1_LENGTH] = { - 0xce, 0x03, 0x94, 0xf4, 0xa9, 0x2c, 0x1e, 0x06, - 0xe7, 0x40, 0x30, 0x01, 0xf7, 0xbb, 0x68, 0x8c, - 0x27, 0xd2, 0x15, 0xe3, 0x28, 0x49, 0x5b, 0xa8, - 0xc1, 0x9a, 0x42, 0x7e, 0x31, 0xf9, 0x08, 0x34, - 0x81, 0xa2, 0x0f, 0x04, 0x61, 0x34, 0xe3, 0x36, - 0x92, 0xb1, 0x09, 0x2b, 0xe9, 0xef, 0x84, 0x88, - 0xbe, 0x9c, 0x98, 0x60, 0xa6, 0x60, 0x84, 0xe9, - 0x75, 0x6f, 0xcc, 0x81, 0xd1, 0x96, 0xef, 0xdd, - 0x2e, 0xca, 0xc4, 0xf5, 0x42, 0xfb, 0x13, 0x2b, - 0x57, 0xbf, 0x14, 0x5e, 0xc2, 0x7f, 0x77, 0x35, - 0x29, 0xc4, 0xe5, 0xe0, 0xf9, 0x6d, 0x15, 0x4a, - 0x42, 0x56, 0x1c, 0x3e, 0x0c, 0xc5, 0xce, 0x70, - 0x08, 0x63, 0x1e, 0x73, 0xdb, 0x7e, 0x74, 0x05, - 0x32, 0x01, 0xc6, 0x36, 0x32, 0x75, 0x6b, 0xed, - 0x9d, 0xfe, 0x7c, 0x7e, 0xa9, 0x57, 0xb4, 0xe9, - 0x22, 0xe4, 0xe7, 0xfe, 0x36, 0x07, 0x9b, 0xdf}; + static const PRUint8 rsa_prime0[FIPS_RSA_PRIME0_LENGTH] = { + 0xe4, 0xbf, 0x21, 0x62, 0x9b, 0xa9, 0x77, 0x40, + 0x8d, 0x2a, 0xce, 0xa1, 0x67, 0x5a, 0x4c, 0x96, + 0x45, 0x98, 0x67, 0xbd, 0x75, 0x22, 0x33, 0x6f, + 0xe6, 0xcb, 0x77, 0xde, 0x9e, 0x97, 0x7d, 0x96, + 0x8c, 0x5e, 0x5d, 0x34, 0xfb, 0x27, 0xfc, 0x6d, + 0x74, 0xdb, 0x9d, 0x2e, 0x6d, 0xf6, 0xea, 0xfc, + 0xce, 0x9e, 0xda, 0xa7, 0x25, 0xa2, 0xf4, 0x58, + 0x6d, 0x0a, 0x3f, 0x01, 0xc2, 0xb4, 0xab, 0x38, + 0xc1, 0x14, 0x85, 0xb6, 0xfa, 0x94, 0xc3, 0x85, + 0xf9, 0x3c, 0x2e, 0x96, 0x56, 0x01, 0xe7, 0xd6, + 0x14, 0x71, 0x4f, 0xfb, 0x4c, 0x85, 0x52, 0xc4, + 0x61, 0x1e, 0xa5, 0x1e, 0x96, 0x13, 0x0d, 0x8f, + 0x66, 0xae, 0xa0, 0xcd, 0x7d, 0x25, 0x66, 0x19, + 0x15, 0xc2, 0xcf, 0xc3, 0x12, 0x3c, 0xe8, 0xa4, + 0x52, 0x4c, 0xcb, 0x28, 0x3c, 0xc4, 0xbf, 0x95, + 0x33, 0xe3, 0x81, 0xea, 0x0c, 0x6c, 0xa2, 0x05 + }; + static const PRUint8 rsa_prime1[FIPS_RSA_PRIME1_LENGTH] = { + 0xce, 0x03, 0x94, 0xf4, 0xa9, 0x2c, 0x1e, 0x06, + 0xe7, 0x40, 0x30, 0x01, 0xf7, 0xbb, 0x68, 0x8c, + 0x27, 0xd2, 0x15, 0xe3, 0x28, 0x49, 0x5b, 0xa8, + 0xc1, 0x9a, 0x42, 0x7e, 0x31, 0xf9, 0x08, 0x34, + 0x81, 0xa2, 0x0f, 0x04, 0x61, 0x34, 0xe3, 0x36, + 0x92, 0xb1, 0x09, 0x2b, 0xe9, 0xef, 0x84, 0x88, + 0xbe, 0x9c, 0x98, 0x60, 0xa6, 0x60, 0x84, 0xe9, + 0x75, 0x6f, 0xcc, 0x81, 0xd1, 0x96, 0xef, 0xdd, + 0x2e, 0xca, 0xc4, 0xf5, 0x42, 0xfb, 0x13, 0x2b, + 0x57, 0xbf, 0x14, 0x5e, 0xc2, 0x7f, 0x77, 0x35, + 0x29, 0xc4, 0xe5, 0xe0, 0xf9, 0x6d, 0x15, 0x4a, + 0x42, 0x56, 0x1c, 0x3e, 0x0c, 0xc5, 0xce, 0x70, + 0x08, 0x63, 0x1e, 0x73, 0xdb, 0x7e, 0x74, 0x05, + 0x32, 0x01, 0xc6, 0x36, 0x32, 0x75, 0x6b, 0xed, + 0x9d, 0xfe, 0x7c, 0x7e, 0xa9, 0x57, 0xb4, 0xe9, + 0x22, 0xe4, 0xe7, 0xfe, 0x36, 0x07, 0x9b, 0xdf + }; static const PRUint8 rsa_exponent0[FIPS_RSA_EXPONENT0_LENGTH] = { - 0x04, 0x5a, 0x3a, 0xa9, 0x64, 0xaa, 0xd9, 0xd1, - 0x09, 0x9e, 0x99, 0xe5, 0xea, 0x50, 0x86, 0x8a, - 0x89, 0x72, 0x77, 0xee, 0xdb, 0xee, 0xb5, 0xa9, - 0xd8, 0x6b, 0x60, 0xb1, 0x84, 0xb4, 0xff, 0x37, - 0xc1, 0x1d, 0xfe, 0x8a, 0x06, 0x89, 0x61, 0x3d, - 0x37, 0xef, 0x01, 0xd3, 0xa3, 0x56, 0x02, 0x6c, - 0xa3, 0x05, 0xd4, 0xc5, 0x3f, 0x6b, 0x15, 0x59, - 0x25, 0x61, 0xff, 0x86, 0xea, 0x0c, 0x84, 0x01, - 0x85, 0x72, 0xfd, 0x84, 0x58, 0xca, 0x41, 0xda, - 0x27, 0xbe, 0xe4, 0x68, 0x09, 0xe4, 0xe9, 0x63, - 0x62, 0x6a, 0x31, 0x8a, 0x67, 0x8f, 0x55, 0xde, - 0xd4, 0xb6, 0x3f, 0x90, 0x10, 0x6c, 0xf6, 0x62, - 0x17, 0x23, 0x15, 0x7e, 0x33, 0x76, 0x65, 0xb5, - 0xee, 0x7b, 0x11, 0x76, 0xf5, 0xbe, 0xe0, 0xf2, - 0x57, 0x7a, 0x8c, 0x97, 0x0c, 0x68, 0xf5, 0xf8, - 0x41, 0xcf, 0x7f, 0x66, 0x53, 0xac, 0x31, 0x7d}; + 0x04, 0x5a, 0x3a, 0xa9, 0x64, 0xaa, 0xd9, 0xd1, + 0x09, 0x9e, 0x99, 0xe5, 0xea, 0x50, 0x86, 0x8a, + 0x89, 0x72, 0x77, 0xee, 0xdb, 0xee, 0xb5, 0xa9, + 0xd8, 0x6b, 0x60, 0xb1, 0x84, 0xb4, 0xff, 0x37, + 0xc1, 0x1d, 0xfe, 0x8a, 0x06, 0x89, 0x61, 0x3d, + 0x37, 0xef, 0x01, 0xd3, 0xa3, 0x56, 0x02, 0x6c, + 0xa3, 0x05, 0xd4, 0xc5, 0x3f, 0x6b, 0x15, 0x59, + 0x25, 0x61, 0xff, 0x86, 0xea, 0x0c, 0x84, 0x01, + 0x85, 0x72, 0xfd, 0x84, 0x58, 0xca, 0x41, 0xda, + 0x27, 0xbe, 0xe4, 0x68, 0x09, 0xe4, 0xe9, 0x63, + 0x62, 0x6a, 0x31, 0x8a, 0x67, 0x8f, 0x55, 0xde, + 0xd4, 0xb6, 0x3f, 0x90, 0x10, 0x6c, 0xf6, 0x62, + 0x17, 0x23, 0x15, 0x7e, 0x33, 0x76, 0x65, 0xb5, + 0xee, 0x7b, 0x11, 0x76, 0xf5, 0xbe, 0xe0, 0xf2, + 0x57, 0x7a, 0x8c, 0x97, 0x0c, 0x68, 0xf5, 0xf8, + 0x41, 0xcf, 0x7f, 0x66, 0x53, 0xac, 0x31, 0x7d + }; static const PRUint8 rsa_exponent1[FIPS_RSA_EXPONENT1_LENGTH] = { - 0x93, 0x54, 0x14, 0x6e, 0x73, 0x9d, 0x4d, 0x4b, - 0xfa, 0x8c, 0xf8, 0xc8, 0x2f, 0x76, 0x22, 0xea, - 0x38, 0x80, 0x11, 0x8f, 0x05, 0xfc, 0x90, 0x44, - 0x3b, 0x50, 0x2a, 0x45, 0x3d, 0x4f, 0xaf, 0x02, - 0x7d, 0xc2, 0x7b, 0xa2, 0xd2, 0x31, 0x94, 0x5c, - 0x2e, 0xc3, 0xd4, 0x9f, 0x47, 0x09, 0x37, 0x6a, - 0xe3, 0x85, 0xf1, 0xa3, 0x0c, 0xd8, 0xf1, 0xb4, - 0x53, 0x7b, 0xc4, 0x71, 0x02, 0x86, 0x42, 0xbb, - 0x96, 0xff, 0x03, 0xa3, 0xb2, 0x67, 0x03, 0xea, - 0x77, 0x31, 0xfb, 0x4b, 0x59, 0x24, 0xf7, 0x07, - 0x59, 0xfb, 0xa9, 0xba, 0x1e, 0x26, 0x58, 0x97, - 0x66, 0xa1, 0x56, 0x49, 0x39, 0xb1, 0x2c, 0x55, - 0x0a, 0x6a, 0x78, 0x18, 0xba, 0xdb, 0xcf, 0xf4, - 0xf7, 0x32, 0x35, 0xa2, 0x04, 0xab, 0xdc, 0xa7, - 0x6d, 0xd9, 0xd5, 0x06, 0x6f, 0xec, 0x7d, 0x40, - 0x4c, 0xe8, 0x0e, 0xd0, 0xc9, 0xaa, 0xdf, 0x59}; + 0x93, 0x54, 0x14, 0x6e, 0x73, 0x9d, 0x4d, 0x4b, + 0xfa, 0x8c, 0xf8, 0xc8, 0x2f, 0x76, 0x22, 0xea, + 0x38, 0x80, 0x11, 0x8f, 0x05, 0xfc, 0x90, 0x44, + 0x3b, 0x50, 0x2a, 0x45, 0x3d, 0x4f, 0xaf, 0x02, + 0x7d, 0xc2, 0x7b, 0xa2, 0xd2, 0x31, 0x94, 0x5c, + 0x2e, 0xc3, 0xd4, 0x9f, 0x47, 0x09, 0x37, 0x6a, + 0xe3, 0x85, 0xf1, 0xa3, 0x0c, 0xd8, 0xf1, 0xb4, + 0x53, 0x7b, 0xc4, 0x71, 0x02, 0x86, 0x42, 0xbb, + 0x96, 0xff, 0x03, 0xa3, 0xb2, 0x67, 0x03, 0xea, + 0x77, 0x31, 0xfb, 0x4b, 0x59, 0x24, 0xf7, 0x07, + 0x59, 0xfb, 0xa9, 0xba, 0x1e, 0x26, 0x58, 0x97, + 0x66, 0xa1, 0x56, 0x49, 0x39, 0xb1, 0x2c, 0x55, + 0x0a, 0x6a, 0x78, 0x18, 0xba, 0xdb, 0xcf, 0xf4, + 0xf7, 0x32, 0x35, 0xa2, 0x04, 0xab, 0xdc, 0xa7, + 0x6d, 0xd9, 0xd5, 0x06, 0x6f, 0xec, 0x7d, 0x40, + 0x4c, 0xe8, 0x0e, 0xd0, 0xc9, 0xaa, 0xdf, 0x59 + }; static const PRUint8 rsa_coefficient[FIPS_RSA_COEFFICIENT_LENGTH] = { - 0x17, 0xd7, 0xf5, 0x0a, 0xf0, 0x68, 0x97, 0x96, - 0xc4, 0x29, 0x18, 0x77, 0x9a, 0x1f, 0xe3, 0xf3, - 0x12, 0x13, 0x0f, 0x7e, 0x7b, 0xb9, 0xc1, 0x91, - 0xf9, 0xc7, 0x08, 0x56, 0x5c, 0xa4, 0xbc, 0x83, - 0x71, 0xf9, 0x78, 0xd9, 0x2b, 0xec, 0xfe, 0x6b, - 0xdc, 0x2f, 0x63, 0xc9, 0xcd, 0x50, 0x14, 0x5b, - 0xd3, 0x6e, 0x85, 0x4d, 0x0c, 0xa2, 0x0b, 0xa0, - 0x09, 0xb6, 0xca, 0x34, 0x9c, 0xc2, 0xc1, 0x4a, - 0xb0, 0xbc, 0x45, 0x93, 0xa5, 0x7e, 0x99, 0xb5, - 0xbd, 0xe4, 0x69, 0x29, 0x08, 0x28, 0xd2, 0xcd, - 0xab, 0x24, 0x78, 0x48, 0x41, 0x26, 0x0b, 0x37, - 0xa3, 0x43, 0xd1, 0x95, 0x1a, 0xd6, 0xee, 0x22, - 0x1c, 0x00, 0x0b, 0xc2, 0xb7, 0xa4, 0xa3, 0x21, - 0xa9, 0xcd, 0xe4, 0x69, 0xd3, 0x45, 0x02, 0xb1, - 0xb7, 0x3a, 0xbf, 0x51, 0x35, 0x1b, 0x78, 0xc2, - 0xcf, 0x0c, 0x0d, 0x60, 0x09, 0xa9, 0x44, 0x02}; + 0x17, 0xd7, 0xf5, 0x0a, 0xf0, 0x68, 0x97, 0x96, + 0xc4, 0x29, 0x18, 0x77, 0x9a, 0x1f, 0xe3, 0xf3, + 0x12, 0x13, 0x0f, 0x7e, 0x7b, 0xb9, 0xc1, 0x91, + 0xf9, 0xc7, 0x08, 0x56, 0x5c, 0xa4, 0xbc, 0x83, + 0x71, 0xf9, 0x78, 0xd9, 0x2b, 0xec, 0xfe, 0x6b, + 0xdc, 0x2f, 0x63, 0xc9, 0xcd, 0x50, 0x14, 0x5b, + 0xd3, 0x6e, 0x85, 0x4d, 0x0c, 0xa2, 0x0b, 0xa0, + 0x09, 0xb6, 0xca, 0x34, 0x9c, 0xc2, 0xc1, 0x4a, + 0xb0, 0xbc, 0x45, 0x93, 0xa5, 0x7e, 0x99, 0xb5, + 0xbd, 0xe4, 0x69, 0x29, 0x08, 0x28, 0xd2, 0xcd, + 0xab, 0x24, 0x78, 0x48, 0x41, 0x26, 0x0b, 0x37, + 0xa3, 0x43, 0xd1, 0x95, 0x1a, 0xd6, 0xee, 0x22, + 0x1c, 0x00, 0x0b, 0xc2, 0xb7, 0xa4, 0xa3, 0x21, + 0xa9, 0xcd, 0xe4, 0x69, 0xd3, 0x45, 0x02, 0xb1, + 0xb7, 0x3a, 0xbf, 0x51, 0x35, 0x1b, 0x78, 0xc2, + 0xcf, 0x0c, 0x0d, 0x60, 0x09, 0xa9, 0x44, 0x02 + }; /* RSA Known Plaintext Message (1024-bits). */ static const PRUint8 rsa_known_plaintext_msg[FIPS_RSA_MESSAGE_LENGTH] = { - "Known plaintext message utilized" - "for RSA Encryption & Decryption" - "blocks SHA256, SHA384 and " - "SHA512 RSA Signature KAT tests. " - "Known plaintext message utilized" - "for RSA Encryption & Decryption" - "blocks SHA256, SHA384 and " - "SHA512 RSA Signature KAT tests."}; - - /* RSA Known Ciphertext (2048-bits). */ - static const PRUint8 rsa_known_ciphertext[] = { - 0x04, 0x12, 0x46, 0xe3, 0x6a, 0xee, 0xde, 0xdd, - 0x49, 0xa1, 0xd9, 0x83, 0xf7, 0x35, 0xf9, 0x70, - 0x88, 0x03, 0x2d, 0x01, 0x8b, 0xd1, 0xbf, 0xdb, - 0xe5, 0x1c, 0x85, 0xbe, 0xb5, 0x0b, 0x48, 0x45, - 0x7a, 0xf0, 0xa0, 0xe3, 0xa2, 0xbb, 0x4b, 0xf6, - 0x27, 0xd0, 0x1b, 0x12, 0xe3, 0x77, 0x52, 0x34, - 0x9e, 0x8e, 0x03, 0xd2, 0xf8, 0x79, 0x6e, 0x39, - 0x79, 0x53, 0x3c, 0x44, 0x14, 0x94, 0xbb, 0x8d, - 0xaa, 0x14, 0x44, 0xa0, 0x7b, 0xa5, 0x8c, 0x93, - 0x5f, 0x99, 0xa4, 0xa3, 0x6e, 0x7a, 0x38, 0x40, - 0x78, 0xfa, 0x36, 0x91, 0x5e, 0x9a, 0x9c, 0xba, - 0x1e, 0xd4, 0xf9, 0xda, 0x4b, 0x0f, 0xa8, 0xa3, - 0x1c, 0xf3, 0x3a, 0xd1, 0xa5, 0xb4, 0x51, 0x16, - 0xed, 0x4b, 0xcf, 0xec, 0x93, 0x7b, 0x90, 0x21, - 0xbc, 0x3a, 0xf4, 0x0b, 0xd1, 0x3a, 0x2b, 0xba, - 0xa6, 0x7d, 0x5b, 0x53, 0xd8, 0x64, 0xf9, 0x29, - 0x7b, 0x7f, 0x77, 0x3e, 0x51, 0x4c, 0x9a, 0x94, - 0xd2, 0x4b, 0x4a, 0x8d, 0x61, 0x74, 0x97, 0xae, - 0x53, 0x6a, 0xf4, 0x90, 0xc2, 0x2c, 0x49, 0xe2, - 0xfa, 0xeb, 0x91, 0xc5, 0xe5, 0x83, 0x13, 0xc9, - 0x44, 0x4b, 0x95, 0x2c, 0x57, 0x70, 0x15, 0x5c, - 0x64, 0x8d, 0x1a, 0xfd, 0x2a, 0xc7, 0xb2, 0x9c, - 0x5c, 0x99, 0xd3, 0x4a, 0xfd, 0xdd, 0xf6, 0x82, - 0x87, 0x8c, 0x5a, 0xc4, 0xa8, 0x0d, 0x2a, 0xef, - 0xc3, 0xa2, 0x7e, 0x8e, 0x67, 0x9f, 0x6f, 0x63, - 0xdb, 0xbb, 0x1d, 0x31, 0xc4, 0xbb, 0xbc, 0x13, - 0x3f, 0x54, 0xc6, 0xf6, 0xc5, 0x28, 0x32, 0xab, - 0x96, 0x42, 0x10, 0x36, 0x40, 0x92, 0xbb, 0x57, - 0x55, 0x38, 0xf5, 0x43, 0x7e, 0x43, 0xc4, 0x65, - 0x47, 0x64, 0xaa, 0x0f, 0x4c, 0xe9, 0x49, 0x16, - 0xec, 0x6a, 0x50, 0xfd, 0x14, 0x49, 0xca, 0xdb, - 0x44, 0x54, 0xca, 0xbe, 0xa3, 0x0e, 0x5f, 0xef}; + "Known plaintext message utilized" + "for RSA Encryption & Decryption" + "blocks SHA256, SHA384 and " + "SHA512 RSA Signature KAT tests. " + "Known plaintext message utilized" + "for RSA Encryption & Decryption" + "blocks SHA256, SHA384 and " + "SHA512 RSA Signature KAT tests." + }; /* RSA Known Signed Hash (2048-bits). */ static const PRUint8 rsa_known_sha256_signature[] = { - 0x8c, 0x2d, 0x2e, 0xfb, 0x37, 0xb5, 0x6f, 0x38, - 0x9f, 0x06, 0x5a, 0xf3, 0x8c, 0xa0, 0xd0, 0x7a, - 0xde, 0xcf, 0xf9, 0x14, 0x95, 0x59, 0xd3, 0x5f, - 0x51, 0x5d, 0x5d, 0xad, 0xd8, 0x71, 0x33, 0x50, - 0x1d, 0x03, 0x3b, 0x3a, 0x32, 0x00, 0xb4, 0xde, - 0x7f, 0xe4, 0xb1, 0xe5, 0x6b, 0x83, 0xf4, 0x80, - 0x10, 0x3b, 0xb8, 0x8a, 0xdb, 0xe8, 0x0a, 0x42, - 0x9e, 0x8d, 0xd7, 0xbe, 0xed, 0xde, 0x5a, 0x3d, - 0xc6, 0xdb, 0xfe, 0x49, 0x6a, 0xe9, 0x1e, 0x75, - 0x66, 0xf1, 0x3f, 0x9e, 0x3f, 0xff, 0x05, 0x65, - 0xde, 0xca, 0x62, 0x62, 0xf3, 0xec, 0x53, 0x09, - 0xa0, 0x37, 0xd5, 0x66, 0x62, 0x72, 0x14, 0xb6, - 0x51, 0x32, 0x67, 0x50, 0xc1, 0xe1, 0x2f, 0x9e, - 0x98, 0x4e, 0x53, 0x96, 0x55, 0x4b, 0xc4, 0x92, - 0xc3, 0xb4, 0x80, 0xf0, 0x35, 0xc9, 0x00, 0x4b, - 0x5c, 0x85, 0x92, 0xb1, 0xe8, 0x6e, 0xa5, 0x51, - 0x38, 0x9f, 0xc9, 0x11, 0xb6, 0x14, 0xdf, 0x34, - 0x64, 0x40, 0x82, 0x82, 0xde, 0x16, 0x69, 0x93, - 0x89, 0x4e, 0x5c, 0x32, 0xf2, 0x0a, 0x4e, 0x9e, - 0xbd, 0x63, 0x99, 0x4f, 0xf3, 0x15, 0x90, 0xc2, - 0xfe, 0x6f, 0xb7, 0xf4, 0xad, 0xd4, 0x8e, 0x0b, - 0xd2, 0xf5, 0x22, 0xd2, 0x71, 0x65, 0x13, 0xf7, - 0x82, 0x7b, 0x75, 0xb6, 0xc1, 0xb4, 0x45, 0xbd, - 0x8f, 0x95, 0xcf, 0x5b, 0x95, 0x32, 0xef, 0x18, - 0x5f, 0xd3, 0xdf, 0x7e, 0x22, 0xdd, 0x25, 0xeb, - 0xe1, 0xbf, 0x3b, 0x9a, 0x55, 0x75, 0x4f, 0x3c, - 0x38, 0x67, 0x57, 0x04, 0x04, 0x57, 0x27, 0xf6, - 0x34, 0x0e, 0x57, 0x8a, 0x7c, 0xff, 0x7d, 0xca, - 0x8c, 0x06, 0xf8, 0x9d, 0xdb, 0xe4, 0xd8, 0x19, - 0xdd, 0x4d, 0xfd, 0x8f, 0xa0, 0x06, 0x53, 0xe8, - 0x33, 0x00, 0x70, 0x3f, 0x6b, 0xc3, 0xbd, 0x9a, - 0x78, 0xb5, 0xa9, 0xef, 0x6d, 0xda, 0x67, 0x92}; + 0x8c, 0x2d, 0x2e, 0xfb, 0x37, 0xb5, 0x6f, 0x38, + 0x9f, 0x06, 0x5a, 0xf3, 0x8c, 0xa0, 0xd0, 0x7a, + 0xde, 0xcf, 0xf9, 0x14, 0x95, 0x59, 0xd3, 0x5f, + 0x51, 0x5d, 0x5d, 0xad, 0xd8, 0x71, 0x33, 0x50, + 0x1d, 0x03, 0x3b, 0x3a, 0x32, 0x00, 0xb4, 0xde, + 0x7f, 0xe4, 0xb1, 0xe5, 0x6b, 0x83, 0xf4, 0x80, + 0x10, 0x3b, 0xb8, 0x8a, 0xdb, 0xe8, 0x0a, 0x42, + 0x9e, 0x8d, 0xd7, 0xbe, 0xed, 0xde, 0x5a, 0x3d, + 0xc6, 0xdb, 0xfe, 0x49, 0x6a, 0xe9, 0x1e, 0x75, + 0x66, 0xf1, 0x3f, 0x9e, 0x3f, 0xff, 0x05, 0x65, + 0xde, 0xca, 0x62, 0x62, 0xf3, 0xec, 0x53, 0x09, + 0xa0, 0x37, 0xd5, 0x66, 0x62, 0x72, 0x14, 0xb6, + 0x51, 0x32, 0x67, 0x50, 0xc1, 0xe1, 0x2f, 0x9e, + 0x98, 0x4e, 0x53, 0x96, 0x55, 0x4b, 0xc4, 0x92, + 0xc3, 0xb4, 0x80, 0xf0, 0x35, 0xc9, 0x00, 0x4b, + 0x5c, 0x85, 0x92, 0xb1, 0xe8, 0x6e, 0xa5, 0x51, + 0x38, 0x9f, 0xc9, 0x11, 0xb6, 0x14, 0xdf, 0x34, + 0x64, 0x40, 0x82, 0x82, 0xde, 0x16, 0x69, 0x93, + 0x89, 0x4e, 0x5c, 0x32, 0xf2, 0x0a, 0x4e, 0x9e, + 0xbd, 0x63, 0x99, 0x4f, 0xf3, 0x15, 0x90, 0xc2, + 0xfe, 0x6f, 0xb7, 0xf4, 0xad, 0xd4, 0x8e, 0x0b, + 0xd2, 0xf5, 0x22, 0xd2, 0x71, 0x65, 0x13, 0xf7, + 0x82, 0x7b, 0x75, 0xb6, 0xc1, 0xb4, 0x45, 0xbd, + 0x8f, 0x95, 0xcf, 0x5b, 0x95, 0x32, 0xef, 0x18, + 0x5f, 0xd3, 0xdf, 0x7e, 0x22, 0xdd, 0x25, 0xeb, + 0xe1, 0xbf, 0x3b, 0x9a, 0x55, 0x75, 0x4f, 0x3c, + 0x38, 0x67, 0x57, 0x04, 0x04, 0x57, 0x27, 0xf6, + 0x34, 0x0e, 0x57, 0x8a, 0x7c, 0xff, 0x7d, 0xca, + 0x8c, 0x06, 0xf8, 0x9d, 0xdb, 0xe4, 0xd8, 0x19, + 0xdd, 0x4d, 0xfd, 0x8f, 0xa0, 0x06, 0x53, 0xe8, + 0x33, 0x00, 0x70, 0x3f, 0x6b, 0xc3, 0xbd, 0x9a, + 0x78, 0xb5, 0xa9, 0xef, 0x6d, 0xda, 0x67, 0x92 + }; - /* RSA Known Signed Hash (2048-bits). */ - static const PRUint8 rsa_known_sha384_signature[] = { - 0x20, 0x2d, 0x21, 0x3a, 0xaa, 0x1e, 0x05, 0x15, - 0x5c, 0xca, 0x84, 0x86, 0xc0, 0x15, 0x81, 0xdf, - 0xd4, 0x06, 0x9f, 0xe0, 0xc1, 0xed, 0xef, 0x0f, - 0xfe, 0xb3, 0xc3, 0xbb, 0x28, 0xa5, 0x56, 0xbf, - 0xe3, 0x11, 0x5c, 0xc2, 0xc0, 0x0b, 0xfa, 0xfa, - 0x3d, 0xd3, 0x06, 0x20, 0xe2, 0xc9, 0xe4, 0x66, - 0x28, 0xb7, 0xc0, 0x3b, 0x3c, 0x96, 0xc6, 0x49, - 0x3b, 0xcf, 0x86, 0x49, 0x31, 0xaf, 0x5b, 0xa3, - 0xec, 0x63, 0x10, 0xdf, 0xda, 0x2f, 0x68, 0xac, - 0x7b, 0x3a, 0x49, 0xfa, 0xe6, 0x0d, 0xfe, 0x37, - 0x17, 0x56, 0x8e, 0x5c, 0x48, 0x97, 0x43, 0xf7, - 0xa0, 0xbc, 0xe3, 0x4b, 0x42, 0xde, 0x58, 0x1d, - 0xd9, 0x5d, 0xb3, 0x08, 0x35, 0xbd, 0xa4, 0xe1, - 0x80, 0xc3, 0x64, 0xab, 0x21, 0x97, 0xad, 0xfb, - 0x71, 0xee, 0xa3, 0x3d, 0x9c, 0xaa, 0xfa, 0x16, - 0x60, 0x46, 0x32, 0xda, 0x44, 0x2e, 0x10, 0x92, - 0x20, 0xd8, 0x98, 0x80, 0x84, 0x75, 0x5b, 0x70, - 0x91, 0x00, 0x33, 0x19, 0x69, 0xc9, 0x2a, 0xec, - 0x3d, 0xe5, 0x5f, 0x0f, 0x9a, 0xa7, 0x97, 0x1f, - 0x79, 0xc3, 0x1d, 0x65, 0x74, 0x62, 0xc5, 0xa1, - 0x23, 0x65, 0x4b, 0x84, 0xa1, 0x03, 0x98, 0xf3, - 0xf1, 0x02, 0x24, 0xca, 0xe5, 0xd4, 0xc8, 0xa2, - 0x30, 0xad, 0x72, 0x7d, 0x29, 0x60, 0x1a, 0x8e, - 0x6f, 0x23, 0xa4, 0xda, 0x68, 0xa4, 0x45, 0x9c, - 0x39, 0x70, 0x44, 0x18, 0x4b, 0x73, 0xfe, 0xf8, - 0x33, 0x53, 0x1d, 0x7e, 0x93, 0x93, 0xac, 0xc7, - 0x1e, 0x6e, 0x6b, 0xfd, 0x9e, 0xba, 0xa6, 0x71, - 0x70, 0x47, 0x6a, 0xd6, 0x82, 0x32, 0xa2, 0x6e, - 0x20, 0x72, 0xb0, 0xba, 0xec, 0x91, 0xbb, 0x6b, - 0xcc, 0x84, 0x0a, 0x33, 0x2b, 0x8a, 0x8d, 0xeb, - 0x71, 0xcd, 0xca, 0x67, 0x1b, 0xad, 0x10, 0xd4, - 0xce, 0x4f, 0xc0, 0x29, 0xec, 0xfa, 0xed, 0xfa}; + /* RSA Known Signed Hash (2048-bits). */ + static const PRUint8 rsa_known_sha384_signature[] = { + 0x20, 0x2d, 0x21, 0x3a, 0xaa, 0x1e, 0x05, 0x15, + 0x5c, 0xca, 0x84, 0x86, 0xc0, 0x15, 0x81, 0xdf, + 0xd4, 0x06, 0x9f, 0xe0, 0xc1, 0xed, 0xef, 0x0f, + 0xfe, 0xb3, 0xc3, 0xbb, 0x28, 0xa5, 0x56, 0xbf, + 0xe3, 0x11, 0x5c, 0xc2, 0xc0, 0x0b, 0xfa, 0xfa, + 0x3d, 0xd3, 0x06, 0x20, 0xe2, 0xc9, 0xe4, 0x66, + 0x28, 0xb7, 0xc0, 0x3b, 0x3c, 0x96, 0xc6, 0x49, + 0x3b, 0xcf, 0x86, 0x49, 0x31, 0xaf, 0x5b, 0xa3, + 0xec, 0x63, 0x10, 0xdf, 0xda, 0x2f, 0x68, 0xac, + 0x7b, 0x3a, 0x49, 0xfa, 0xe6, 0x0d, 0xfe, 0x37, + 0x17, 0x56, 0x8e, 0x5c, 0x48, 0x97, 0x43, 0xf7, + 0xa0, 0xbc, 0xe3, 0x4b, 0x42, 0xde, 0x58, 0x1d, + 0xd9, 0x5d, 0xb3, 0x08, 0x35, 0xbd, 0xa4, 0xe1, + 0x80, 0xc3, 0x64, 0xab, 0x21, 0x97, 0xad, 0xfb, + 0x71, 0xee, 0xa3, 0x3d, 0x9c, 0xaa, 0xfa, 0x16, + 0x60, 0x46, 0x32, 0xda, 0x44, 0x2e, 0x10, 0x92, + 0x20, 0xd8, 0x98, 0x80, 0x84, 0x75, 0x5b, 0x70, + 0x91, 0x00, 0x33, 0x19, 0x69, 0xc9, 0x2a, 0xec, + 0x3d, 0xe5, 0x5f, 0x0f, 0x9a, 0xa7, 0x97, 0x1f, + 0x79, 0xc3, 0x1d, 0x65, 0x74, 0x62, 0xc5, 0xa1, + 0x23, 0x65, 0x4b, 0x84, 0xa1, 0x03, 0x98, 0xf3, + 0xf1, 0x02, 0x24, 0xca, 0xe5, 0xd4, 0xc8, 0xa2, + 0x30, 0xad, 0x72, 0x7d, 0x29, 0x60, 0x1a, 0x8e, + 0x6f, 0x23, 0xa4, 0xda, 0x68, 0xa4, 0x45, 0x9c, + 0x39, 0x70, 0x44, 0x18, 0x4b, 0x73, 0xfe, 0xf8, + 0x33, 0x53, 0x1d, 0x7e, 0x93, 0x93, 0xac, 0xc7, + 0x1e, 0x6e, 0x6b, 0xfd, 0x9e, 0xba, 0xa6, 0x71, + 0x70, 0x47, 0x6a, 0xd6, 0x82, 0x32, 0xa2, 0x6e, + 0x20, 0x72, 0xb0, 0xba, 0xec, 0x91, 0xbb, 0x6b, + 0xcc, 0x84, 0x0a, 0x33, 0x2b, 0x8a, 0x8d, 0xeb, + 0x71, 0xcd, 0xca, 0x67, 0x1b, 0xad, 0x10, 0xd4, + 0xce, 0x4f, 0xc0, 0x29, 0xec, 0xfa, 0xed, 0xfa + }; - /* RSA Known Signed Hash (2048-bits). */ - static const PRUint8 rsa_known_sha512_signature[] = { - 0x35, 0x0e, 0x74, 0x9d, 0xeb, 0xc7, 0x67, 0x31, - 0x9f, 0xff, 0x0b, 0xbb, 0x5e, 0x66, 0xb4, 0x2f, - 0xbf, 0x72, 0x60, 0x4f, 0xe9, 0xbd, 0xec, 0xc8, - 0x17, 0x79, 0x5f, 0x39, 0x83, 0xb4, 0x54, 0x2e, - 0x01, 0xb9, 0xd3, 0x20, 0x47, 0xcb, 0xd4, 0x42, - 0xf2, 0x6e, 0x36, 0xc1, 0x97, 0xad, 0xef, 0x8e, - 0xe6, 0x51, 0xee, 0x5e, 0x9e, 0x88, 0xb4, 0x9d, - 0xda, 0x3e, 0x77, 0x4b, 0xe8, 0xae, 0x48, 0x53, - 0x2c, 0xc4, 0xd3, 0x25, 0x6b, 0x23, 0xb7, 0x54, - 0x3c, 0x95, 0x8f, 0xfb, 0x6f, 0x6d, 0xc5, 0x56, - 0x39, 0x69, 0x28, 0x0e, 0x74, 0x9b, 0x31, 0xe8, - 0x76, 0x77, 0x2b, 0xc1, 0x44, 0x89, 0x81, 0x93, - 0xfc, 0xf6, 0xec, 0x5f, 0x8f, 0x89, 0xfc, 0x1d, - 0xa4, 0x53, 0x58, 0x8c, 0xe9, 0xc0, 0xc0, 0x26, - 0xe6, 0xdf, 0x6d, 0x27, 0xb1, 0x8e, 0x3e, 0xb6, - 0x47, 0xe1, 0x02, 0x96, 0xc2, 0x5f, 0x7f, 0x3d, - 0xc5, 0x6c, 0x2f, 0xea, 0xaa, 0x5e, 0x39, 0xfc, - 0x77, 0xca, 0x00, 0x02, 0x5c, 0x64, 0x7c, 0xce, - 0x7d, 0x63, 0x82, 0x05, 0xed, 0xf7, 0x5b, 0x55, - 0x58, 0xc0, 0xeb, 0x76, 0xd7, 0x95, 0x55, 0x37, - 0x85, 0x7d, 0x17, 0xad, 0xd2, 0x11, 0xfd, 0x97, - 0x48, 0xb5, 0xc2, 0x5e, 0xc7, 0x62, 0xc0, 0xe0, - 0x68, 0xa8, 0x61, 0x14, 0x41, 0xca, 0x25, 0x3a, - 0xec, 0x48, 0x54, 0x22, 0x83, 0x2b, 0x69, 0x54, - 0xfd, 0xc8, 0x99, 0x9a, 0xee, 0x37, 0x03, 0xa3, - 0x8f, 0x0f, 0x32, 0xb0, 0xaa, 0x74, 0x39, 0x04, - 0x7c, 0xd9, 0xc2, 0x8f, 0xbe, 0xf2, 0xc4, 0xbe, - 0xdd, 0x7a, 0x7a, 0x7f, 0x72, 0xd3, 0x80, 0x59, - 0x18, 0xa0, 0xa1, 0x2d, 0x6f, 0xa3, 0xa9, 0x48, - 0xed, 0x20, 0xa6, 0xea, 0xaa, 0x10, 0x83, 0x98, - 0x0c, 0x13, 0x69, 0x6e, 0xcd, 0x31, 0x6b, 0xd0, - 0x66, 0xa6, 0x5e, 0x30, 0x0c, 0x82, 0xd5, 0x81}; + /* RSA Known Signed Hash (2048-bits). */ + static const PRUint8 rsa_known_sha512_signature[] = { + 0x35, 0x0e, 0x74, 0x9d, 0xeb, 0xc7, 0x67, 0x31, + 0x9f, 0xff, 0x0b, 0xbb, 0x5e, 0x66, 0xb4, 0x2f, + 0xbf, 0x72, 0x60, 0x4f, 0xe9, 0xbd, 0xec, 0xc8, + 0x17, 0x79, 0x5f, 0x39, 0x83, 0xb4, 0x54, 0x2e, + 0x01, 0xb9, 0xd3, 0x20, 0x47, 0xcb, 0xd4, 0x42, + 0xf2, 0x6e, 0x36, 0xc1, 0x97, 0xad, 0xef, 0x8e, + 0xe6, 0x51, 0xee, 0x5e, 0x9e, 0x88, 0xb4, 0x9d, + 0xda, 0x3e, 0x77, 0x4b, 0xe8, 0xae, 0x48, 0x53, + 0x2c, 0xc4, 0xd3, 0x25, 0x6b, 0x23, 0xb7, 0x54, + 0x3c, 0x95, 0x8f, 0xfb, 0x6f, 0x6d, 0xc5, 0x56, + 0x39, 0x69, 0x28, 0x0e, 0x74, 0x9b, 0x31, 0xe8, + 0x76, 0x77, 0x2b, 0xc1, 0x44, 0x89, 0x81, 0x93, + 0xfc, 0xf6, 0xec, 0x5f, 0x8f, 0x89, 0xfc, 0x1d, + 0xa4, 0x53, 0x58, 0x8c, 0xe9, 0xc0, 0xc0, 0x26, + 0xe6, 0xdf, 0x6d, 0x27, 0xb1, 0x8e, 0x3e, 0xb6, + 0x47, 0xe1, 0x02, 0x96, 0xc2, 0x5f, 0x7f, 0x3d, + 0xc5, 0x6c, 0x2f, 0xea, 0xaa, 0x5e, 0x39, 0xfc, + 0x77, 0xca, 0x00, 0x02, 0x5c, 0x64, 0x7c, 0xce, + 0x7d, 0x63, 0x82, 0x05, 0xed, 0xf7, 0x5b, 0x55, + 0x58, 0xc0, 0xeb, 0x76, 0xd7, 0x95, 0x55, 0x37, + 0x85, 0x7d, 0x17, 0xad, 0xd2, 0x11, 0xfd, 0x97, + 0x48, 0xb5, 0xc2, 0x5e, 0xc7, 0x62, 0xc0, 0xe0, + 0x68, 0xa8, 0x61, 0x14, 0x41, 0xca, 0x25, 0x3a, + 0xec, 0x48, 0x54, 0x22, 0x83, 0x2b, 0x69, 0x54, + 0xfd, 0xc8, 0x99, 0x9a, 0xee, 0x37, 0x03, 0xa3, + 0x8f, 0x0f, 0x32, 0xb0, 0xaa, 0x74, 0x39, 0x04, + 0x7c, 0xd9, 0xc2, 0x8f, 0xbe, 0xf2, 0xc4, 0xbe, + 0xdd, 0x7a, 0x7a, 0x7f, 0x72, 0xd3, 0x80, 0x59, + 0x18, 0xa0, 0xa1, 0x2d, 0x6f, 0xa3, 0xa9, 0x48, + 0xed, 0x20, 0xa6, 0xea, 0xaa, 0x10, 0x83, 0x98, + 0x0c, 0x13, 0x69, 0x6e, 0xcd, 0x31, 0x6b, 0xd0, + 0x66, 0xa6, 0x5e, 0x30, 0x0c, 0x82, 0xd5, 0x81 + }; - static const RSAPublicKey bl_public_key = { NULL, - { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, - FIPS_RSA_MODULUS_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, - FIPS_RSA_PUBLIC_EXPONENT_LENGTH } + static const RSAPublicKey bl_public_key = { + NULL, + { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, + FIPS_RSA_MODULUS_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, + FIPS_RSA_PUBLIC_EXPONENT_LENGTH } }; - static const RSAPrivateKey bl_private_key = { NULL, - { FIPS_RSA_TYPE, (unsigned char *)rsa_version, - FIPS_RSA_PRIVATE_VERSION_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, - FIPS_RSA_MODULUS_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, - FIPS_RSA_PUBLIC_EXPONENT_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_private_exponent, - FIPS_RSA_PRIVATE_EXPONENT_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_prime0, - FIPS_RSA_PRIME0_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_prime1, - FIPS_RSA_PRIME1_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent0, - FIPS_RSA_EXPONENT0_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent1, - FIPS_RSA_EXPONENT1_LENGTH }, - { FIPS_RSA_TYPE, (unsigned char *)rsa_coefficient, - FIPS_RSA_COEFFICIENT_LENGTH } + static const RSAPrivateKey bl_private_key = { + NULL, + { FIPS_RSA_TYPE, (unsigned char *)rsa_version, + FIPS_RSA_PRIVATE_VERSION_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus, + FIPS_RSA_MODULUS_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, + FIPS_RSA_PUBLIC_EXPONENT_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_private_exponent, + FIPS_RSA_PRIVATE_EXPONENT_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_prime0, + FIPS_RSA_PRIME0_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_prime1, + FIPS_RSA_PRIME1_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent0, + FIPS_RSA_EXPONENT0_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent1, + FIPS_RSA_EXPONENT1_LENGTH }, + { FIPS_RSA_TYPE, (unsigned char *)rsa_coefficient, + FIPS_RSA_COEFFICIENT_LENGTH } }; - /* RSA variables. */ +/* RSA variables. */ #ifdef CREATE_TEMP_ARENAS - PLArenaPool * rsa_public_arena; - PLArenaPool * rsa_private_arena; + PLArenaPool *rsa_public_arena; + PLArenaPool *rsa_private_arena; #endif - NSSLOWKEYPublicKey * rsa_public_key; - NSSLOWKEYPrivateKey * rsa_private_key; - SECStatus rsa_status; + NSSLOWKEYPublicKey *rsa_public_key; + NSSLOWKEYPrivateKey *rsa_private_key; + SECStatus rsa_status; - NSSLOWKEYPublicKey low_public_key = { NULL, NSSLOWKEYRSAKey, }; - NSSLOWKEYPrivateKey low_private_key = { NULL, NSSLOWKEYRSAKey, }; - PRUint8 rsa_computed_ciphertext[FIPS_RSA_ENCRYPT_LENGTH]; - PRUint8 rsa_computed_plaintext[FIPS_RSA_DECRYPT_LENGTH]; + NSSLOWKEYPublicKey low_public_key = { NULL, NSSLOWKEYRSAKey }; + NSSLOWKEYPrivateKey low_private_key = { NULL, NSSLOWKEYRSAKey }; /****************************************/ /* Compose RSA Public/Private Key Pair. */ /****************************************/ - low_public_key.u.rsa = bl_public_key; + low_public_key.u.rsa = bl_public_key; low_private_key.u.rsa = bl_private_key; - rsa_public_key = &low_public_key; + rsa_public_key = &low_public_key; rsa_private_key = &low_private_key; #ifdef CREATE_TEMP_ARENAS /* Create some space for the RSA public key. */ - rsa_public_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE ); + rsa_public_arena = PORT_NewArena(NSS_SOFTOKEN_DEFAULT_CHUNKSIZE); - if( rsa_public_arena == NULL ) { - PORT_SetError( SEC_ERROR_NO_MEMORY ); - return( CKR_HOST_MEMORY ); + if (rsa_public_arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (SECFailure); } /* Create some space for the RSA private key. */ - rsa_private_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE ); + rsa_private_arena = PORT_NewArena(NSS_SOFTOKEN_DEFAULT_CHUNKSIZE); - if( rsa_private_arena == NULL ) { - PORT_FreeArena( rsa_public_arena, PR_TRUE ); - PORT_SetError( SEC_ERROR_NO_MEMORY ); - return( CKR_HOST_MEMORY ); + if (rsa_private_arena == NULL) { + PORT_FreeArena(rsa_public_arena, PR_TRUE); + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (SECFailure); } rsa_public_key->arena = rsa_public_arena; @@ -1550,551 +540,115 @@ sftk_fips_RSA_PowerUpSelfTest( void ) #endif /**************************************************/ - /* RSA Single-Round Known Answer Encryption Test. */ + /* RSA Hash tests */ /**************************************************/ - /* Perform RSA Public Key Encryption. */ - rsa_status = RSA_PublicKeyOp(&rsa_public_key->u.rsa, - rsa_computed_ciphertext, - rsa_known_plaintext_msg); - - if( ( rsa_status != SECSuccess ) || - ( PORT_Memcmp( rsa_computed_ciphertext, rsa_known_ciphertext, - FIPS_RSA_ENCRYPT_LENGTH ) != 0 ) ) + rsa_status = sftk_fips_RSA_PowerUpSigSelfTest(HASH_AlgSHA256, + rsa_public_key, rsa_private_key, + rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, + rsa_known_sha256_signature); + if (rsa_status != SECSuccess) goto rsa_loser; - /**************************************************/ - /* RSA Single-Round Known Answer Decryption Test. */ - /**************************************************/ - - /* Perform RSA Private Key Decryption. */ - rsa_status = RSA_PrivateKeyOp(&rsa_private_key->u.rsa, - rsa_computed_plaintext, - rsa_known_ciphertext); - - if( ( rsa_status != SECSuccess ) || - ( PORT_Memcmp( rsa_computed_plaintext, rsa_known_plaintext_msg, - FIPS_RSA_DECRYPT_LENGTH ) != 0 ) ) - goto rsa_loser; - - rsa_status = sftk_fips_RSA_PowerUpSigSelfTest (HASH_AlgSHA256, - rsa_public_key, rsa_private_key, - rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, - rsa_known_sha256_signature); - if( rsa_status != SECSuccess ) + rsa_status = sftk_fips_RSA_PowerUpSigSelfTest(HASH_AlgSHA384, + rsa_public_key, rsa_private_key, + rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, + rsa_known_sha384_signature); + if (rsa_status != SECSuccess) goto rsa_loser; - rsa_status = sftk_fips_RSA_PowerUpSigSelfTest (HASH_AlgSHA384, - rsa_public_key, rsa_private_key, - rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, - rsa_known_sha384_signature); - if( rsa_status != SECSuccess ) - goto rsa_loser; - - rsa_status = sftk_fips_RSA_PowerUpSigSelfTest (HASH_AlgSHA512, - rsa_public_key, rsa_private_key, - rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, - rsa_known_sha512_signature); - if( rsa_status != SECSuccess ) + rsa_status = sftk_fips_RSA_PowerUpSigSelfTest(HASH_AlgSHA512, + rsa_public_key, rsa_private_key, + rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH, + rsa_known_sha512_signature); + if (rsa_status != SECSuccess) goto rsa_loser; /* Dispose of all RSA key material. */ - nsslowkey_DestroyPublicKey( rsa_public_key ); - nsslowkey_DestroyPrivateKey( rsa_private_key ); + nsslowkey_DestroyPublicKey(rsa_public_key); + nsslowkey_DestroyPrivateKey(rsa_private_key); - return( CKR_OK ); + return (SECSuccess); rsa_loser: - nsslowkey_DestroyPublicKey( rsa_public_key ); - nsslowkey_DestroyPrivateKey( rsa_private_key ); + nsslowkey_DestroyPublicKey(rsa_public_key); + nsslowkey_DestroyPrivateKey(rsa_private_key); - return( CKR_DEVICE_ERROR ); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return (SECFailure); } -#ifndef NSS_DISABLE_ECC - -static CK_RV -sftk_fips_ECDSA_Test(const PRUint8 *encodedParams, - unsigned int encodedParamsLen, - const PRUint8 *knownSignature, - unsigned int knownSignatureLen) { - - /* ECDSA Known Seed info for curves nistp256 and nistk283 */ - static const PRUint8 ecdsa_Known_Seed[] = { - 0x6a, 0x9b, 0xf6, 0xf7, 0xce, 0xed, 0x79, 0x11, - 0xf0, 0xc7, 0xc8, 0x9a, 0xa5, 0xd1, 0x57, 0xb1, - 0x7b, 0x5a, 0x3b, 0x76, 0x4e, 0x7b, 0x7c, 0xbc, - 0xf2, 0x76, 0x1c, 0x1c, 0x7f, 0xc5, 0x53, 0x2f}; - - static const PRUint8 msg[] = { - "Firefox and ThunderBird are awesome!"}; - - unsigned char sha1[SHA1_LENGTH]; /* SHA-1 hash (160 bits) */ - unsigned char sig[2*MAX_ECKEY_LEN]; - SECItem signature, digest; - SECItem encodedparams; - ECParams *ecparams = NULL; - ECPrivateKey *ecdsa_private_key = NULL; - ECPublicKey ecdsa_public_key; - SECStatus ecdsaStatus = SECSuccess; - - /* construct the ECDSA private/public key pair */ - encodedparams.type = siBuffer; - encodedparams.data = (unsigned char *) encodedParams; - encodedparams.len = encodedParamsLen; - - if (EC_DecodeParams(&encodedparams, &ecparams) != SECSuccess) { - return( CKR_DEVICE_ERROR ); - } - - /* Generates a new EC key pair. The private key is a supplied - * random value (in seed) and the public key is the result of - * performing a scalar point multiplication of that value with - * the curve's base point. - */ - ecdsaStatus = EC_NewKeyFromSeed(ecparams, &ecdsa_private_key, - ecdsa_Known_Seed, - sizeof(ecdsa_Known_Seed)); - /* free the ecparams they are no longer needed */ - PORT_FreeArena(ecparams->arena, PR_FALSE); - ecparams = NULL; - if (ecdsaStatus != SECSuccess) { - return ( CKR_DEVICE_ERROR ); - } - - /* construct public key from private key. */ - ecdsaStatus = EC_CopyParams(ecdsa_private_key->ecParams.arena, - &ecdsa_public_key.ecParams, - &ecdsa_private_key->ecParams); - if (ecdsaStatus != SECSuccess) { - goto loser; - } - ecdsa_public_key.publicValue = ecdsa_private_key->publicValue; - - /* validate public key value */ - ecdsaStatus = EC_ValidatePublicKey(&ecdsa_public_key.ecParams, - &ecdsa_public_key.publicValue); - if (ecdsaStatus != SECSuccess) { - goto loser; - } - - /* validate public key value */ - ecdsaStatus = EC_ValidatePublicKey(&ecdsa_private_key->ecParams, - &ecdsa_private_key->publicValue); - if (ecdsaStatus != SECSuccess) { - goto loser; - } +static PRBool sftk_self_tests_ran = PR_FALSE; +static PRBool sftk_self_tests_success = PR_FALSE; - /***************************************************/ - /* ECDSA Single-Round Known Answer Signature Test. */ - /***************************************************/ - - ecdsaStatus = SHA1_HashBuf(sha1, msg, sizeof msg); - if (ecdsaStatus != SECSuccess) { - goto loser; - } - digest.type = siBuffer; - digest.data = sha1; - digest.len = SHA1_LENGTH; - - memset(sig, 0, sizeof sig); - signature.type = siBuffer; - signature.data = sig; - signature.len = sizeof sig; - - ecdsaStatus = ECDSA_SignDigestWithSeed(ecdsa_private_key, &signature, - &digest, ecdsa_Known_Seed, sizeof ecdsa_Known_Seed); - if (ecdsaStatus != SECSuccess) { - goto loser; +/* + * This function is called at dll load time, the code tha makes this + * happen is platform specific on defined above. + */ +static void +sftk_startup_tests(void) +{ + SECStatus rv; + const char *libraryName = SOFTOKEN_LIB_NAME; + + PORT_Assert(!sftk_self_tests_ran); + PORT_Assert(!sftk_self_tests_success); + sftk_self_tests_ran = PR_TRUE; + sftk_self_tests_success = PR_FALSE; /* just in case */ + + /* need to initiallize the oid library before the RSA tests */ + rv = SECOID_Init(); + if (rv != SECSuccess) { + return; } - - if( ( signature.len != knownSignatureLen ) || - ( PORT_Memcmp( signature.data, knownSignature, - knownSignatureLen ) != 0 ) ) { - ecdsaStatus = SECFailure; - goto loser; + /* make sure freebl is initialized, or our RSA check + * may fail. This is normally done at freebl load time, but it's + * possible we may have shut freebl down without unloading it. */ + rv = BL_Init(); + if (rv != SECSuccess) { + return; } - - /******************************************************/ - /* ECDSA Single-Round Known Answer Verification Test. */ - /******************************************************/ - /* Perform ECDSA verification process. */ - ecdsaStatus = ECDSA_VerifyDigest(&ecdsa_public_key, &signature, &digest); - -loser: - /* free the memory for the private key arena*/ - if (ecdsa_private_key != NULL) { - PORT_FreeArena(ecdsa_private_key->ecParams.arena, PR_FALSE); + rv = RNG_RNGInit(); + if (rv != SECSuccess) { + return; } - - if (ecdsaStatus != SECSuccess) { - return CKR_DEVICE_ERROR ; - } - return( CKR_OK ); -} - -static CK_RV -sftk_fips_ECDSA_PowerUpSelfTest() { - - /* ECDSA Known curve nistp256 == SEC_OID_SECG_EC_SECP256R1 params */ - static const PRUint8 ecdsa_known_P256_EncodedParams[] = { - 0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03, - 0x01,0x07}; - - static const PRUint8 ecdsa_known_P256_signature[] = { - 0x07,0xb1,0xcb,0x57,0x20,0xa7,0x10,0xd6, - 0x9d,0x37,0x4b,0x1c,0xdc,0x35,0x90,0xff, - 0x1a,0x2d,0x98,0x95,0x1b,0x2f,0xeb,0x7f, - 0xbb,0x81,0xca,0xc0,0x69,0x75,0xea,0xc5, - 0x59,0x6a,0x62,0x49,0x3d,0x50,0xc9,0xe1, - 0x27,0x3b,0xff,0x9b,0x13,0x66,0x67,0xdd, - 0x7d,0xd1,0x0d,0x2d,0x7c,0x44,0x04,0x1b, - 0x16,0x21,0x12,0xc5,0xcb,0xbd,0x9e,0x75}; - -#ifdef NSS_ECC_MORE_THAN_SUITE_B - /* ECDSA Known curve nistk283 == SEC_OID_SECG_EC_SECT283K1 params */ - static const PRUint8 ecdsa_known_K283_EncodedParams[] = { - 0x06,0x05,0x2b,0x81,0x04,0x00,0x10}; - - static const PRUint8 ecdsa_known_K283_signature[] = { - 0x00,0x45,0x88,0xc0,0x79,0x09,0x07,0xd1, - 0x4e,0x88,0xe6,0xd5,0x2f,0x22,0x04,0x74, - 0x35,0x24,0x65,0xe8,0x15,0xde,0x90,0x66, - 0x94,0x70,0xdd,0x3a,0x14,0x70,0x02,0xd1, - 0xef,0x86,0xbd,0x15,0x00,0xd9,0xdc,0xfc, - 0x87,0x2e,0x7c,0x99,0xe2,0xe3,0x79,0xb8, - 0xd9,0x10,0x49,0x78,0x4b,0x59,0x8b,0x05, - 0x77,0xec,0x6c,0xe8,0x35,0xe6,0x2e,0xa9, - 0xf9,0x77,0x1f,0x71,0x86,0xa5,0x4a,0xd0}; -#endif - - CK_RV crv; - - /* ECDSA GF(p) prime field curve test */ - crv = sftk_fips_ECDSA_Test(ecdsa_known_P256_EncodedParams, - sizeof ecdsa_known_P256_EncodedParams, - ecdsa_known_P256_signature, - sizeof ecdsa_known_P256_signature ); - if (crv != CKR_OK) { - return( CKR_DEVICE_ERROR ); + /* check the RSA combined functions in softoken */ + rv = sftk_fips_RSA_PowerUpSelfTest(); + if (rv != SECSuccess) { + return; } - -#ifdef NSS_ECC_MORE_THAN_SUITE_B - /* ECDSA GF(2m) binary field curve test */ - crv = sftk_fips_ECDSA_Test(ecdsa_known_K283_EncodedParams, - sizeof ecdsa_known_K283_EncodedParams, - ecdsa_known_K283_signature, - sizeof ecdsa_known_K283_signature ); - if (crv != CKR_OK) { - return( CKR_DEVICE_ERROR ); + if (!BLAPI_SHVerify(libraryName, + (PRFuncPtr)&sftk_fips_RSA_PowerUpSelfTest)) { + /* something is wrong with the library, fail without enabling + * the token */ + return; } -#endif - - return( CKR_OK ); -} - -#endif /* NSS_DISABLE_ECC */ - -static CK_RV -sftk_fips_DSA_PowerUpSelfTest( void ) -{ - /* DSA Known P (1024-bits), Q (160-bits), and G (1024-bits) Values. */ - static const PRUint8 dsa_P[] = { - 0x80,0xb0,0xd1,0x9d,0x6e,0xa4,0xf3,0x28, - 0x9f,0x24,0xa9,0x8a,0x49,0xd0,0x0c,0x63, - 0xe8,0x59,0x04,0xf9,0x89,0x4a,0x5e,0xc0, - 0x6d,0xd2,0x67,0x6b,0x37,0x81,0x83,0x0c, - 0xfe,0x3a,0x8a,0xfd,0xa0,0x3b,0x08,0x91, - 0x1c,0xcb,0xb5,0x63,0xb0,0x1c,0x70,0xd0, - 0xae,0xe1,0x60,0x2e,0x12,0xeb,0x54,0xc7, - 0xcf,0xc6,0xcc,0xae,0x97,0x52,0x32,0x63, - 0xd3,0xeb,0x55,0xea,0x2f,0x4c,0xd5,0xd7, - 0x3f,0xda,0xec,0x49,0x27,0x0b,0x14,0x56, - 0xc5,0x09,0xbe,0x4d,0x09,0x15,0x75,0x2b, - 0xa3,0x42,0x0d,0x03,0x71,0xdf,0x0f,0xf4, - 0x0e,0xe9,0x0c,0x46,0x93,0x3d,0x3f,0xa6, - 0x6c,0xdb,0xca,0xe5,0xac,0x96,0xc8,0x64, - 0x5c,0xec,0x4b,0x35,0x65,0xfc,0xfb,0x5a, - 0x1b,0x04,0x1b,0xa1,0x0e,0xfd,0x88,0x15}; - - static const PRUint8 dsa_Q[] = { - 0xad,0x22,0x59,0xdf,0xe5,0xec,0x4c,0x6e, - 0xf9,0x43,0xf0,0x4b,0x2d,0x50,0x51,0xc6, - 0x91,0x99,0x8b,0xcf}; - - static const PRUint8 dsa_G[] = { - 0x78,0x6e,0xa9,0xd8,0xcd,0x4a,0x85,0xa4, - 0x45,0xb6,0x6e,0x5d,0x21,0x50,0x61,0xf6, - 0x5f,0xdf,0x5c,0x7a,0xde,0x0d,0x19,0xd3, - 0xc1,0x3b,0x14,0xcc,0x8e,0xed,0xdb,0x17, - 0xb6,0xca,0xba,0x86,0xa9,0xea,0x51,0x2d, - 0xc1,0xa9,0x16,0xda,0xf8,0x7b,0x59,0x8a, - 0xdf,0xcb,0xa4,0x67,0x00,0x44,0xea,0x24, - 0x73,0xe5,0xcb,0x4b,0xaf,0x2a,0x31,0x25, - 0x22,0x28,0x3f,0x16,0x10,0x82,0xf7,0xeb, - 0x94,0x0d,0xdd,0x09,0x22,0x14,0x08,0x79, - 0xba,0x11,0x0b,0xf1,0xff,0x2d,0x67,0xac, - 0xeb,0xb6,0x55,0x51,0x69,0x97,0xa7,0x25, - 0x6b,0x9c,0xa0,0x9b,0xd5,0x08,0x9b,0x27, - 0x42,0x1c,0x7a,0x69,0x57,0xe6,0x2e,0xed, - 0xa9,0x5b,0x25,0xe8,0x1f,0xd2,0xed,0x1f, - 0xdf,0xe7,0x80,0x17,0xba,0x0d,0x4d,0x38}; - - /* DSA Known Random Values (known random key block is 160-bits) */ - /* and (known random signature block is 160-bits). */ - static const PRUint8 dsa_known_random_key_block[] = { - "Mozilla Rules World!"}; - static const PRUint8 dsa_known_random_signature_block[] = { - "Random DSA Signature"}; - - /* DSA Known Digest (160-bits) */ - static const PRUint8 dsa_known_digest[] = { "DSA Signature Digest" }; - - /* DSA Known Signature (320-bits). */ - static const PRUint8 dsa_known_signature[] = { - 0x25,0x7c,0x3a,0x79,0x32,0x45,0xb7,0x32, - 0x70,0xca,0x62,0x63,0x2b,0xf6,0x29,0x2c, - 0x22,0x2a,0x03,0xce,0x48,0x15,0x11,0x72, - 0x7b,0x7e,0xf5,0x7a,0xf3,0x10,0x3b,0xde, - 0x34,0xc1,0x9e,0xd7,0x27,0x9e,0x77,0x38}; - - /* DSA variables. */ - DSAPrivateKey * dsa_private_key; - SECStatus dsa_status; - SECItem dsa_signature_item; - SECItem dsa_digest_item; - DSAPublicKey dsa_public_key; - PRUint8 dsa_computed_signature[FIPS_DSA_SIGNATURE_LENGTH]; - static const PQGParams dsa_pqg = { NULL, - { FIPS_DSA_TYPE, (unsigned char *)dsa_P, FIPS_DSA_PRIME_LENGTH }, - { FIPS_DSA_TYPE, (unsigned char *)dsa_Q, FIPS_DSA_SUBPRIME_LENGTH }, - { FIPS_DSA_TYPE, (unsigned char *)dsa_G, FIPS_DSA_BASE_LENGTH }}; - - /*******************************************/ - /* Generate a DSA public/private key pair. */ - /*******************************************/ - - /* Generate a DSA public/private key pair. */ - dsa_status = DSA_NewKeyFromSeed(&dsa_pqg, dsa_known_random_key_block, - &dsa_private_key); - - if( dsa_status != SECSuccess ) - return( CKR_HOST_MEMORY ); - - /* construct public key from private key. */ - dsa_public_key.params = dsa_private_key->params; - dsa_public_key.publicValue = dsa_private_key->publicValue; - - /*************************************************/ - /* DSA Single-Round Known Answer Signature Test. */ - /*************************************************/ - - dsa_signature_item.data = dsa_computed_signature; - dsa_signature_item.len = sizeof dsa_computed_signature; - - dsa_digest_item.data = (unsigned char *)dsa_known_digest; - dsa_digest_item.len = SHA1_LENGTH; - - /* Perform DSA signature process. */ - dsa_status = DSA_SignDigestWithSeed( dsa_private_key, - &dsa_signature_item, - &dsa_digest_item, - dsa_known_random_signature_block ); - - if( ( dsa_status != SECSuccess ) || - ( dsa_signature_item.len != FIPS_DSA_SIGNATURE_LENGTH ) || - ( PORT_Memcmp( dsa_computed_signature, dsa_known_signature, - FIPS_DSA_SIGNATURE_LENGTH ) != 0 ) ) { - dsa_status = SECFailure; - } else { - - /****************************************************/ - /* DSA Single-Round Known Answer Verification Test. */ - /****************************************************/ - - /* Perform DSA verification process. */ - dsa_status = DSA_VerifyDigest( &dsa_public_key, - &dsa_signature_item, - &dsa_digest_item); - } - - PORT_FreeArena(dsa_private_key->params.arena, PR_TRUE); - /* Don't free public key, it uses same arena as private key */ - - /* Verify DSA signature. */ - if( dsa_status != SECSuccess ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); - - -} - -static CK_RV -sftk_fips_RNG_PowerUpSelfTest( void ) -{ - static const PRUint8 Q[] = { - 0x85,0x89,0x9c,0x77,0xa3,0x79,0xff,0x1a, - 0x86,0x6f,0x2f,0x3e,0x2e,0xf9,0x8c,0x9c, - 0x9d,0xef,0xeb,0xed}; - static const PRUint8 GENX[] = { - 0x65,0x48,0xe3,0xca,0xac,0x64,0x2d,0xf7, - 0x7b,0xd3,0x4e,0x79,0xc9,0x7d,0xa6,0xa8, - 0xa2,0xc2,0x1f,0x8f,0xe9,0xb9,0xd3,0xa1, - 0x3f,0xf7,0x0c,0xcd,0xa6,0xca,0xbf,0xce, - 0x84,0x0e,0xb6,0xf1,0x0d,0xbe,0xa9,0xa3}; - static const PRUint8 rng_known_DSAX[] = { - 0x7a,0x86,0xf1,0x7f,0xbd,0x4e,0x6e,0xd9, - 0x0a,0x26,0x21,0xd0,0x19,0xcb,0x86,0x73, - 0x10,0x1f,0x60,0xd7}; - - - - SECStatus rng_status = SECSuccess; - PRUint8 DSAX[FIPS_DSA_SUBPRIME_LENGTH]; - - /*******************************************/ - /* Run the SP 800-90 Health tests */ - /*******************************************/ - rng_status = PRNGTEST_RunHealthTests(); - if (rng_status != SECSuccess) { - return (CKR_DEVICE_ERROR); - } - - /*******************************************/ - /* Generate DSAX fow given Q. */ - /*******************************************/ - - rng_status = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX); - - /* Verify DSAX to perform the RNG integrity check */ - if( ( rng_status != SECSuccess ) || - ( PORT_Memcmp( DSAX, rng_known_DSAX, - (FIPS_DSA_SUBPRIME_LENGTH) ) != 0 ) ) - return( CKR_DEVICE_ERROR ); - - return( CKR_OK ); -} - -static CK_RV -sftk_fipsSoftwareIntegrityTest(void) -{ - CK_RV crv = CKR_OK; - - /* make sure that our check file signatures are OK */ - if( !BLAPI_VerifySelf( NULL ) || - !BLAPI_SHVerify( SOFTOKEN_LIB_NAME, (PRFuncPtr) sftk_fips_HMAC ) ) { - crv = CKR_DEVICE_ERROR; /* better error code? checksum error? */ - } - return crv; + sftk_self_tests_success = PR_TRUE; } +/* + * this is called from nsc_Common_Initizialize entry points that gates access + * to * all other pkcs11 functions. This prevents softoken operation if our + * power on selftest failed. + */ CK_RV -sftk_fipsPowerUpSelfTest( void ) +sftk_FIPSEntryOK() { - CK_RV rv; - - /* RC2 Power-Up SelfTest(s). */ - rv = sftk_fips_RC2_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* RC4 Power-Up SelfTest(s). */ - rv = sftk_fips_RC4_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DES Power-Up SelfTest(s). */ - rv = sftk_fips_DES_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DES3 Power-Up SelfTest(s). */ - rv = sftk_fips_DES3_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* AES Power-Up SelfTest(s) for 128-bit key. */ - rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_128_KEY_SIZE); - - if( rv != CKR_OK ) - return rv; - - /* AES Power-Up SelfTest(s) for 192-bit key. */ - rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_192_KEY_SIZE); - - if( rv != CKR_OK ) - return rv; - - /* AES Power-Up SelfTest(s) for 256-bit key. */ - rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_256_KEY_SIZE); - - if( rv != CKR_OK ) - return rv; - - /* MD2 Power-Up SelfTest(s). */ - rv = sftk_fips_MD2_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* MD5 Power-Up SelfTest(s). */ - rv = sftk_fips_MD5_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* SHA-X Power-Up SelfTest(s). */ - rv = sftk_fips_SHA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* HMAC SHA-X Power-Up SelfTest(s). */ - rv = sftk_fips_HMAC_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* RSA Power-Up SelfTest(s). */ - rv = sftk_fips_RSA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* DSA Power-Up SelfTest(s). */ - rv = sftk_fips_DSA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - - /* RNG Power-Up SelfTest(s). */ - rv = sftk_fips_RNG_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; - -#ifndef NSS_DISABLE_ECC - /* ECDSA Power-Up SelfTest(s). */ - rv = sftk_fips_ECDSA_PowerUpSelfTest(); - - if( rv != CKR_OK ) - return rv; +#ifdef NSS_NO_INIT_SUPPORT + /* this should only be set on platforms that can't handle one of the INIT + * schemes. This code allows those platforms to continue to function, + * though they don't meet the strict NIST requirements. If NSS_NO_INIT_SUPPORT + * is not set, and init support has not been properly enabled, softken + * will always fail because of the test below + */ + if (!sftk_self_tests_ran) { + sftk_startup_tests(); + } #endif - - /* Software/Firmware Integrity Test. */ - rv = sftk_fipsSoftwareIntegrityTest(); - - if( rv != CKR_OK ) - return rv; - - /* Passed Power-Up SelfTest(s). */ - return( CKR_OK ); + if (!sftk_self_tests_success) { + return CKR_DEVICE_ERROR; + } + return CKR_OK; } - diff --git a/nss/lib/softoken/fipstokn.c b/nss/lib/softoken/fipstokn.c index 3cb6b79..12ff77c 100644 --- a/nss/lib/softoken/fipstokn.c +++ b/nss/lib/softoken/fipstokn.c @@ -6,11 +6,11 @@ * * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login + * slot 1 is our generic crypto support. It does not require login * (unless you've enabled FIPS). It supports Public Key ops, and all they * bulk ciphers and hashes. It can also support Private Key ops for imported * Private keys. It does not have any token storage. - * slot 2 is our private key support. It requires a login before use. It + * slot 2 is our private key support. It requires a login before use. It * can store Private Keys and Certs as token objects. Currently only private * keys and their associated Certificates are saved on the token. * @@ -38,21 +38,21 @@ #include <dlfcn.h> #define LIBAUDIT_NAME "libaudit.so.0" #ifndef AUDIT_CRYPTO_TEST_USER -#define AUDIT_CRYPTO_TEST_USER 2400 /* Crypto test results */ -#define AUDIT_CRYPTO_PARAM_CHANGE_USER 2401 /* Crypto attribute change */ -#define AUDIT_CRYPTO_LOGIN 2402 /* Logged in as crypto officer */ -#define AUDIT_CRYPTO_LOGOUT 2403 /* Logged out from crypto */ -#define AUDIT_CRYPTO_KEY_USER 2404 /* Create,delete,negotiate */ -#define AUDIT_CRYPTO_FAILURE_USER 2405 /* Fail decrypt,encrypt,randomize */ +#define AUDIT_CRYPTO_TEST_USER 2400 /* Crypto test results */ +#define AUDIT_CRYPTO_PARAM_CHANGE_USER 2401 /* Crypto attribute change */ +#define AUDIT_CRYPTO_LOGIN 2402 /* Logged in as crypto officer */ +#define AUDIT_CRYPTO_LOGOUT 2403 /* Logged out from crypto */ +#define AUDIT_CRYPTO_KEY_USER 2404 /* Create,delete,negotiate */ +#define AUDIT_CRYPTO_FAILURE_USER 2405 /* Fail decrypt,encrypt,randomize */ #endif static void *libaudit_handle; static int (*audit_open_func)(void); static void (*audit_close_func)(int fd); static int (*audit_log_user_message_func)(int audit_fd, int type, - const char *message, const char *hostname, const char *addr, - const char *tty, int result); + const char *message, const char *hostname, const char *addr, + const char *tty, int result); static int (*audit_send_user_message_func)(int fd, int type, - const char *message); + const char *message); static pthread_once_t libaudit_once_control = PTHREAD_ONCE_INIT; @@ -61,7 +61,7 @@ libaudit_init(void) { libaudit_handle = dlopen(LIBAUDIT_NAME, RTLD_LAZY); if (!libaudit_handle) { - return; + return; } audit_open_func = dlsym(libaudit_handle, "audit_open"); audit_close_func = dlsym(libaudit_handle, "audit_close"); @@ -70,28 +70,28 @@ libaudit_init(void) * audit_log_user_message, if available, is preferred. */ audit_log_user_message_func = dlsym(libaudit_handle, - "audit_log_user_message"); + "audit_log_user_message"); if (!audit_log_user_message_func) { - audit_send_user_message_func = dlsym(libaudit_handle, - "audit_send_user_message"); + audit_send_user_message_func = dlsym(libaudit_handle, + "audit_send_user_message"); } if (!audit_open_func || !audit_close_func || - (!audit_log_user_message_func && !audit_send_user_message_func)) { - dlclose(libaudit_handle); - libaudit_handle = NULL; - audit_open_func = NULL; - audit_close_func = NULL; - audit_log_user_message_func = NULL; - audit_send_user_message_func = NULL; + (!audit_log_user_message_func && !audit_send_user_message_func)) { + dlclose(libaudit_handle); + libaudit_handle = NULL; + audit_open_func = NULL; + audit_close_func = NULL; + audit_log_user_message_func = NULL; + audit_send_user_message_func = NULL; } } #endif /* LINUX */ - /* * ******************** Password Utilities ******************************* */ static PRBool isLoggedIn = PR_FALSE; +static PRBool isLevel2 = PR_TRUE; PRBool sftk_fatalError = PR_FALSE; /* @@ -115,120 +115,122 @@ PRBool sftk_fatalError = PR_FALSE; * to characters. To meet the minimum password/PIN guessing probability * requirements in FIPS 140-2, we need to check the length in characters. */ -static CK_RV sftk_newPinCheck(CK_CHAR_PTR pPin, CK_ULONG ulPinLen) { +static CK_RV +sftk_newPinCheck(CK_CHAR_PTR pPin, CK_ULONG ulPinLen) +{ unsigned int i; - int nchar = 0; /* number of characters */ - int ntrail = 0; /* number of trailing bytes to follow */ - int ndigit = 0; /* number of decimal digits */ - int nlower = 0; /* number of ASCII lowercase letters */ - int nupper = 0; /* number of ASCII uppercase letters */ - int nnonalnum = 0; /* number of ASCII non-alphanumeric characters */ - int nnonascii = 0; /* number of non-ASCII characters */ - int nclass; /* number of character classes */ + int nchar = 0; /* number of characters */ + int ntrail = 0; /* number of trailing bytes to follow */ + int ndigit = 0; /* number of decimal digits */ + int nlower = 0; /* number of ASCII lowercase letters */ + int nupper = 0; /* number of ASCII uppercase letters */ + int nnonalnum = 0; /* number of ASCII non-alphanumeric characters */ + int nnonascii = 0; /* number of non-ASCII characters */ + int nclass; /* number of character classes */ for (i = 0; i < ulPinLen; i++) { - unsigned int byte = pPin[i]; - - if (ntrail) { - if ((byte & 0xc0) != 0x80) { - /* illegal */ - nchar = -1; - break; - } - if (--ntrail == 0) { - nchar++; - nnonascii++; - } - continue; - } - if ((byte & 0x80) == 0x00) { - /* single-byte (ASCII) character */ - nchar++; - if (isdigit(byte)) { - if (i < ulPinLen - 1) { - ndigit++; - } - } else if (islower(byte)) { - nlower++; - } else if (isupper(byte)) { - if (i > 0) { - nupper++; - } - } else { - nnonalnum++; - } - } else if ((byte & 0xe0) == 0xc0) { - /* leading byte of two-byte character */ - ntrail = 1; - } else if ((byte & 0xf0) == 0xe0) { - /* leading byte of three-byte character */ - ntrail = 2; - } else if ((byte & 0xf8) == 0xf0) { - /* leading byte of four-byte character */ - ntrail = 3; - } else { - /* illegal */ - nchar = -1; - break; - } + unsigned int byte = pPin[i]; + + if (ntrail) { + if ((byte & 0xc0) != 0x80) { + /* illegal */ + nchar = -1; + break; + } + if (--ntrail == 0) { + nchar++; + nnonascii++; + } + continue; + } + if ((byte & 0x80) == 0x00) { + /* single-byte (ASCII) character */ + nchar++; + if (isdigit(byte)) { + if (i < ulPinLen - 1) { + ndigit++; + } + } else if (islower(byte)) { + nlower++; + } else if (isupper(byte)) { + if (i > 0) { + nupper++; + } + } else { + nnonalnum++; + } + } else if ((byte & 0xe0) == 0xc0) { + /* leading byte of two-byte character */ + ntrail = 1; + } else if ((byte & 0xf0) == 0xe0) { + /* leading byte of three-byte character */ + ntrail = 2; + } else if ((byte & 0xf8) == 0xf0) { + /* leading byte of four-byte character */ + ntrail = 3; + } else { + /* illegal */ + nchar = -1; + break; + } } if (nchar == -1) { - /* illegal UTF8 string */ - return CKR_PIN_INVALID; + /* illegal UTF8 string */ + return CKR_PIN_INVALID; } if (nchar < FIPS_MIN_PIN) { - return CKR_PIN_LEN_RANGE; + return CKR_PIN_LEN_RANGE; } nclass = (ndigit != 0) + (nlower != 0) + (nupper != 0) + - (nnonalnum != 0) + (nnonascii != 0); + (nnonalnum != 0) + (nnonascii != 0); if (nclass < 3) { - return CKR_PIN_LEN_RANGE; + return CKR_PIN_LEN_RANGE; } return CKR_OK; } - /* FIPS required checks before any useful cryptographic services */ -static CK_RV sftk_fipsCheck(void) { - if (sftk_fatalError) - return CKR_DEVICE_ERROR; - if (!isLoggedIn) - return CKR_USER_NOT_LOGGED_IN; +static CK_RV +sftk_fipsCheck(void) +{ + if (sftk_fatalError) + return CKR_DEVICE_ERROR; + if (isLevel2 && !isLoggedIn) + return CKR_USER_NOT_LOGGED_IN; return CKR_OK; } - -#define SFTK_FIPSCHECK() \ - CK_RV rv; \ - if ((rv = sftk_fipsCheck()) != CKR_OK) return rv; +#define SFTK_FIPSCHECK() \ + CK_RV rv; \ + if ((rv = sftk_fipsCheck()) != CKR_OK) \ + return rv; #define SFTK_FIPSFATALCHECK() \ - if (sftk_fatalError) return CKR_DEVICE_ERROR; - + if (sftk_fatalError) \ + return CKR_DEVICE_ERROR; /* grab an attribute out of a raw template */ void * -fc_getAttribute(CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_ATTRIBUTE_TYPE type) +fc_getAttribute(CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_ATTRIBUTE_TYPE type) { int i; - for (i=0; i < (int) ulCount; i++) { - if (pTemplate[i].type == type) { - return pTemplate[i].pValue; - } + for (i = 0; i < (int)ulCount; i++) { + if (pTemplate[i].type == type) { + return pTemplate[i].pValue; + } } return NULL; } - -#define __PASTE(x,y) x##y +#define __PASTE(x, y) x##y /* ------------- forward declare all the NSC_ functions ------------- */ #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO -#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(NS,name) +#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(NS, name) #define CK_NEED_ARG_LIST 1 #include "pkcs11f.h" @@ -237,7 +239,7 @@ fc_getAttribute(CK_ATTRIBUTE_PTR pTemplate, #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO -#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(F,name) +#define CK_PKCS11_FUNCTION_INFO(name) CK_RV __PASTE(F, name) #define CK_NEED_ARG_LIST 1 #include "pkcs11f.h" @@ -249,8 +251,9 @@ static CK_FUNCTION_LIST sftk_fipsTable = { #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO -#define CK_PKCS11_FUNCTION_INFO(name) __PASTE(F,name), - +#define CK_PKCS11_FUNCTION_INFO(name) \ + __PASTE(F, name) \ + , #include "pkcs11f.h" @@ -259,32 +262,31 @@ static CK_FUNCTION_LIST sftk_fipsTable = { #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO - #undef __PASTE /* CKO_NOT_A_KEY can be any object class that's not a key object. */ #define CKO_NOT_A_KEY CKO_DATA -#define SFTK_IS_KEY_OBJECT(objClass) \ - (((objClass) == CKO_PUBLIC_KEY) || \ - ((objClass) == CKO_PRIVATE_KEY) || \ - ((objClass) == CKO_SECRET_KEY)) +#define SFTK_IS_KEY_OBJECT(objClass) \ + (((objClass) == CKO_PUBLIC_KEY) || \ + ((objClass) == CKO_PRIVATE_KEY) || \ + ((objClass) == CKO_SECRET_KEY)) #define SFTK_IS_NONPUBLIC_KEY_OBJECT(objClass) \ (((objClass) == CKO_PRIVATE_KEY) || ((objClass) == CKO_SECRET_KEY)) static CK_RV sftk_get_object_class_and_fipsCheck(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_OBJECT_CLASS *pObjClass) + CK_OBJECT_HANDLE hObject, CK_OBJECT_CLASS *pObjClass) { CK_RV rv; - CK_ATTRIBUTE class; + CK_ATTRIBUTE class; class.type = CKA_CLASS; class.pValue = pObjClass; class.ulValueLen = sizeof(*pObjClass); rv = NSC_GetAttributeValue(hSession, hObject, &class, 1); if ((rv == CKR_OK) && SFTK_IS_NONPUBLIC_KEY_OBJECT(*pObjClass)) { - rv = sftk_fipsCheck(); + rv = sftk_fipsCheck(); } return rv; } @@ -295,41 +297,39 @@ int sftk_mapLinuxAuditType(NSSAuditSeverity severity, NSSAuditType auditType) { switch (auditType) { - case NSS_AUDIT_ACCESS_KEY: - case NSS_AUDIT_CHANGE_KEY: - case NSS_AUDIT_COPY_KEY: - case NSS_AUDIT_DERIVE_KEY: - case NSS_AUDIT_DESTROY_KEY: - case NSS_AUDIT_DIGEST_KEY: - case NSS_AUDIT_GENERATE_KEY: - case NSS_AUDIT_LOAD_KEY: - case NSS_AUDIT_UNWRAP_KEY: - case NSS_AUDIT_WRAP_KEY: - return AUDIT_CRYPTO_KEY_USER; - case NSS_AUDIT_CRYPT: - return (severity == NSS_AUDIT_ERROR) ? AUDIT_CRYPTO_FAILURE_USER : - AUDIT_CRYPTO_KEY_USER; - case NSS_AUDIT_FIPS_STATE: - case NSS_AUDIT_INIT_PIN: - case NSS_AUDIT_INIT_TOKEN: - case NSS_AUDIT_SET_PIN: - return AUDIT_CRYPTO_PARAM_CHANGE_USER; - case NSS_AUDIT_SELF_TEST: - return AUDIT_CRYPTO_TEST_USER; - case NSS_AUDIT_LOGIN: - return AUDIT_CRYPTO_LOGIN; - case NSS_AUDIT_LOGOUT: - return AUDIT_CRYPTO_LOGOUT; - /* we skip the fault case here so we can get compiler - * warnings if new 'NSSAuditType's are added without - * added them to this list, defaults fall through */ + case NSS_AUDIT_ACCESS_KEY: + case NSS_AUDIT_CHANGE_KEY: + case NSS_AUDIT_COPY_KEY: + case NSS_AUDIT_DERIVE_KEY: + case NSS_AUDIT_DESTROY_KEY: + case NSS_AUDIT_DIGEST_KEY: + case NSS_AUDIT_GENERATE_KEY: + case NSS_AUDIT_LOAD_KEY: + case NSS_AUDIT_UNWRAP_KEY: + case NSS_AUDIT_WRAP_KEY: + return AUDIT_CRYPTO_KEY_USER; + case NSS_AUDIT_CRYPT: + return (severity == NSS_AUDIT_ERROR) ? AUDIT_CRYPTO_FAILURE_USER : AUDIT_CRYPTO_KEY_USER; + case NSS_AUDIT_FIPS_STATE: + case NSS_AUDIT_INIT_PIN: + case NSS_AUDIT_INIT_TOKEN: + case NSS_AUDIT_SET_PIN: + return AUDIT_CRYPTO_PARAM_CHANGE_USER; + case NSS_AUDIT_SELF_TEST: + return AUDIT_CRYPTO_TEST_USER; + case NSS_AUDIT_LOGIN: + return AUDIT_CRYPTO_LOGIN; + case NSS_AUDIT_LOGOUT: + return AUDIT_CRYPTO_LOGOUT; + /* we skip the fault case here so we can get compiler + * warnings if new 'NSSAuditType's are added without + * added them to this list, defaults fall through */ } /* default */ return AUDIT_CRYPTO_PARAM_CHANGE_USER; -} +} #endif - /********************************************************************** * * FIPS 140 auditable event logging @@ -354,67 +354,68 @@ PRBool sftk_audit_enabled = PR_FALSE; */ void sftk_LogAuditMessage(NSSAuditSeverity severity, NSSAuditType auditType, - const char *msg) + const char *msg) { #ifdef NSS_AUDIT_WITH_SYSLOG int level; switch (severity) { - case NSS_AUDIT_ERROR: - level = LOG_ERR; - break; - case NSS_AUDIT_WARNING: - level = LOG_WARNING; - break; - default: - level = LOG_INFO; - break; + case NSS_AUDIT_ERROR: + level = LOG_ERR; + break; + case NSS_AUDIT_WARNING: + level = LOG_WARNING; + break; + default: + level = LOG_INFO; + break; } /* timestamp is provided by syslog in the message header */ syslog(level | LOG_USER /* facility */, - "NSS " SOFTOKEN_LIB_NAME "[pid=%d uid=%d]: %s", - (int)getpid(), (int)getuid(), msg); + "NSS " SOFTOKEN_LIB_NAME "[pid=%d uid=%d]: %s", + (int)getpid(), (int)getuid(), msg); #ifdef LINUX if (pthread_once(&libaudit_once_control, libaudit_init) != 0) { - return; + return; } if (libaudit_handle) { - int audit_fd; - int linuxAuditType; - int result = (severity != NSS_AUDIT_ERROR); /* 1=success; 0=failed */ - char *message = PR_smprintf("NSS " SOFTOKEN_LIB_NAME ": %s", msg); - if (!message) { - return; - } - audit_fd = audit_open_func(); - if (audit_fd < 0) { - PR_smprintf_free(message); - return; - } - linuxAuditType = sftk_mapLinuxAuditType(severity, auditType); - if (audit_log_user_message_func) { - audit_log_user_message_func(audit_fd, linuxAuditType, message, - NULL, NULL, NULL, result); - } else { - audit_send_user_message_func(audit_fd, linuxAuditType, message); - } - audit_close_func(audit_fd); - PR_smprintf_free(message); + int audit_fd; + int linuxAuditType; + int result = (severity != NSS_AUDIT_ERROR); /* 1=success; 0=failed */ + char *message = PR_smprintf("NSS " SOFTOKEN_LIB_NAME ": %s", msg); + if (!message) { + return; + } + audit_fd = audit_open_func(); + if (audit_fd < 0) { + PR_smprintf_free(message); + return; + } + linuxAuditType = sftk_mapLinuxAuditType(severity, auditType); + if (audit_log_user_message_func) { + audit_log_user_message_func(audit_fd, linuxAuditType, message, + NULL, NULL, NULL, result); + } else { + audit_send_user_message_func(audit_fd, linuxAuditType, message); + } + audit_close_func(audit_fd); + PR_smprintf_free(message); } #endif /* LINUX */ #else - /* do nothing */ +/* do nothing */ #endif } - /********************************************************************** * - * Start of PKCS 11 functions + * Start of PKCS 11 functions * **********************************************************************/ /* return the function list */ -CK_RV FC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) { +CK_RV +FC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) +{ CHECK_FORK(); @@ -425,307 +426,357 @@ CK_RV FC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) { /* sigh global so pkcs11 can read it */ PRBool nsf_init = PR_FALSE; +void +fc_log_init_error(CK_RV crv) +{ + if (sftk_audit_enabled) { + char msg[128]; + PR_snprintf(msg, sizeof msg, + "C_Initialize()=0x%08lX " + "power-up self-tests failed", + (PRUint32)crv); + sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); + } +} + /* FC_Initialize initializes the PKCS #11 library. */ -CK_RV FC_Initialize(CK_VOID_PTR pReserved) { +CK_RV +FC_Initialize(CK_VOID_PTR pReserved) +{ const char *envp; CK_RV crv; - sftk_ForkReset(pReserved, &crv); + if ((envp = PR_GetEnv("NSS_ENABLE_AUDIT")) != NULL) { + sftk_audit_enabled = (atoi(envp) == 1); + } - if (nsf_init) { - return CKR_CRYPTOKI_ALREADY_INITIALIZED; + /* At this point we should have already done post and integrity checks. + * if we haven't, it probably means the FIPS product has not been installed + * or the tests failed. Don't let an application try to enter FIPS mode */ + crv = sftk_FIPSEntryOK(); + if (crv != CKR_OK) { + sftk_fatalError = PR_TRUE; + fc_log_init_error(crv); + return crv; } - if ((envp = PR_GetEnv("NSS_ENABLE_AUDIT")) != NULL) { - sftk_audit_enabled = (atoi(envp) == 1); + sftk_ForkReset(pReserved, &crv); + + if (nsf_init) { + return CKR_CRYPTOKI_ALREADY_INITIALIZED; } crv = nsc_CommonInitialize(pReserved, PR_TRUE); /* not an 'else' rv can be set by either SFTK_LowInit or SFTK_SlotInit*/ if (crv != CKR_OK) { - sftk_fatalError = PR_TRUE; - return crv; + sftk_fatalError = PR_TRUE; + return crv; } sftk_fatalError = PR_FALSE; /* any error has been reset */ - - crv = sftk_fipsPowerUpSelfTest(); - if (crv != CKR_OK) { - nsc_CommonFinalize(NULL, PR_TRUE); - sftk_fatalError = PR_TRUE; - if (sftk_audit_enabled) { - char msg[128]; - PR_snprintf(msg,sizeof msg, - "C_Initialize()=0x%08lX " - "power-up self-tests failed", - (PRUint32)crv); - sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); - } - return crv; - } nsf_init = PR_TRUE; + isLevel2 = PR_TRUE; /* assume level 2 unless we learn otherwise */ return CKR_OK; } /*FC_Finalize indicates that an application is done with the PKCS #11 library.*/ -CK_RV FC_Finalize (CK_VOID_PTR pReserved) { - CK_RV crv; +CK_RV +FC_Finalize(CK_VOID_PTR pReserved) +{ + CK_RV crv; - if (sftk_ForkReset(pReserved, &crv)) { - return crv; - } + if (sftk_ForkReset(pReserved, &crv)) { + return crv; + } - if (!nsf_init) { - return CKR_OK; - } + if (!nsf_init) { + return CKR_OK; + } - crv = nsc_CommonFinalize (pReserved, PR_TRUE); + crv = nsc_CommonFinalize(pReserved, PR_TRUE); - nsf_init = (PRBool) !(crv == CKR_OK); - return crv; + nsf_init = (PRBool) !(crv == CKR_OK); + return crv; } - /* FC_GetInfo returns general information about PKCS #11. */ -CK_RV FC_GetInfo(CK_INFO_PTR pInfo) { +CK_RV +FC_GetInfo(CK_INFO_PTR pInfo) +{ CHECK_FORK(); return NSC_GetInfo(pInfo); } /* FC_GetSlotList obtains a list of slots in the system. */ -CK_RV FC_GetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { +CK_RV +FC_GetSlotList(CK_BBOOL tokenPresent, + CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) +{ CHECK_FORK(); - return nsc_CommonGetSlotList(tokenPresent,pSlotList,pulCount, - NSC_FIPS_MODULE); + return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount, + NSC_FIPS_MODULE); } - + /* FC_GetSlotInfo obtains information about a particular slot in the system. */ -CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { +CK_RV +FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) +{ CHECK_FORK(); - return NSC_GetSlotInfo(slotID,pInfo); + return NSC_GetSlotInfo(slotID, pInfo); } - /*FC_GetTokenInfo obtains information about a particular token in the system.*/ - CK_RV FC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) { +CK_RV +FC_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) +{ CK_RV crv; CHECK_FORK(); - crv = NSC_GetTokenInfo(slotID,pInfo); - if (crv == CKR_OK) - pInfo->flags |= CKF_LOGIN_REQUIRED; + crv = NSC_GetTokenInfo(slotID, pInfo); + if (crv == CKR_OK) { + if ((pInfo->flags & CKF_LOGIN_REQUIRED) == 0) { + isLevel2 = PR_FALSE; + } + } return crv; - } - - /*FC_GetMechanismList obtains a list of mechanism types supported by a token.*/ - CK_RV FC_GetMechanismList(CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pusCount) { - CHECK_FORK(); +CK_RV +FC_GetMechanismList(CK_SLOT_ID slotID, + CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pusCount) +{ + CHECK_FORK(); SFTK_FIPSFATALCHECK(); - if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID; - /* FIPS Slot supports all functions */ - return NSC_GetMechanismList(slotID,pMechanismList,pusCount); + if ((slotID == FIPS_SLOT_ID) || (slotID >= SFTK_MIN_FIPS_USER_SLOT_ID)) { + slotID = NETSCAPE_SLOT_ID; + } + /* FIPS Slots support all functions */ + return NSC_GetMechanismList(slotID, pMechanismList, pusCount); } - -/* FC_GetMechanismInfo obtains information about a particular mechanism +/* FC_GetMechanismInfo obtains information about a particular mechanism * possibly supported by a token. */ - CK_RV FC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo) { +CK_RV +FC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, + CK_MECHANISM_INFO_PTR pInfo) +{ CHECK_FORK(); SFTK_FIPSFATALCHECK(); - if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID; - /* FIPS Slot supports all functions */ - return NSC_GetMechanismInfo(slotID,type,pInfo); + if ((slotID == FIPS_SLOT_ID) || (slotID >= SFTK_MIN_FIPS_USER_SLOT_ID)) { + slotID = NETSCAPE_SLOT_ID; + } + /* FIPS Slots support all functions */ + return NSC_GetMechanismInfo(slotID, type, pInfo); } - /* FC_InitToken initializes a token. */ - CK_RV FC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, - CK_ULONG usPinLen,CK_CHAR_PTR pLabel) { +CK_RV +FC_InitToken(CK_SLOT_ID slotID, CK_CHAR_PTR pPin, + CK_ULONG usPinLen, CK_CHAR_PTR pLabel) +{ CK_RV crv; CHECK_FORK(); - crv = NSC_InitToken(slotID,pPin,usPinLen,pLabel); + crv = NSC_InitToken(slotID, pPin, usPinLen, pLabel); if (sftk_audit_enabled) { - char msg[128]; - NSSAuditSeverity severity = (crv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; - /* pLabel points to a 32-byte label, which is not null-terminated */ - PR_snprintf(msg,sizeof msg, - "C_InitToken(slotID=%lu, pLabel=\"%.32s\")=0x%08lX", - (PRUint32)slotID,pLabel,(PRUint32)crv); - sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_TOKEN, msg); + char msg[128]; + NSSAuditSeverity severity = (crv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + /* pLabel points to a 32-byte label, which is not null-terminated */ + PR_snprintf(msg, sizeof msg, + "C_InitToken(slotID=%lu, pLabel=\"%.32s\")=0x%08lX", + (PRUint32)slotID, pLabel, (PRUint32)crv); + sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_TOKEN, msg); } return crv; } - /* FC_InitPIN initializes the normal user's PIN. */ - CK_RV FC_InitPIN(CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) { +CK_RV +FC_InitPIN(CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pPin, CK_ULONG ulPinLen) +{ CK_RV rv; CHECK_FORK(); - if (sftk_fatalError) return CKR_DEVICE_ERROR; - if ((rv = sftk_newPinCheck(pPin,ulPinLen)) == CKR_OK) { - rv = NSC_InitPIN(hSession,pPin,ulPinLen); + if (sftk_fatalError) + return CKR_DEVICE_ERROR; + /* NSC_InitPIN will only work once per database. We can either initialize + * it to level1 (pin len == 0) or level2. If we initialize to level 2, then + * we need to make sure the pin meets FIPS requirements */ + if ((ulPinLen == 0) || ((rv = sftk_newPinCheck(pPin, ulPinLen)) == CKR_OK)) { + rv = NSC_InitPIN(hSession, pPin, ulPinLen); + if (rv == CKR_OK) { + isLevel2 = (ulPinLen > 0) ? PR_TRUE : PR_FALSE; + } } if (sftk_audit_enabled) { - char msg[128]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; - PR_snprintf(msg,sizeof msg, - "C_InitPIN(hSession=0x%08lX)=0x%08lX", - (PRUint32)hSession,(PRUint32)rv); - sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_PIN, msg); + char msg[128]; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + PR_snprintf(msg, sizeof msg, + "C_InitPIN(hSession=0x%08lX)=0x%08lX", + (PRUint32)hSession, (PRUint32)rv); + sftk_LogAuditMessage(severity, NSS_AUDIT_INIT_PIN, msg); } return rv; } - /* FC_SetPIN modifies the PIN of user that is currently logged in. */ /* NOTE: This is only valid for the PRIVATE_KEY_SLOT */ - CK_RV FC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, - CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) { +CK_RV +FC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, + CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) +{ CK_RV rv; CHECK_FORK(); if ((rv = sftk_fipsCheck()) == CKR_OK && - (rv = sftk_newPinCheck(pNewPin,usNewLen)) == CKR_OK) { - rv = NSC_SetPIN(hSession,pOldPin,usOldLen,pNewPin,usNewLen); + (rv = sftk_newPinCheck(pNewPin, usNewLen)) == CKR_OK) { + rv = NSC_SetPIN(hSession, pOldPin, usOldLen, pNewPin, usNewLen); + if (rv == CKR_OK) { + /* if we set the password in level1 we now go + * to level2. NOTE: we don't allow the user to + * go from level2 to level1 */ + isLevel2 = PR_TRUE; + } } if (sftk_audit_enabled) { - char msg[128]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; - PR_snprintf(msg,sizeof msg, - "C_SetPIN(hSession=0x%08lX)=0x%08lX", - (PRUint32)hSession,(PRUint32)rv); - sftk_LogAuditMessage(severity, NSS_AUDIT_SET_PIN, msg); + char msg[128]; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + PR_snprintf(msg, sizeof msg, + "C_SetPIN(hSession=0x%08lX)=0x%08lX", + (PRUint32)hSession, (PRUint32)rv); + sftk_LogAuditMessage(severity, NSS_AUDIT_SET_PIN, msg); } return rv; } /* FC_OpenSession opens a session between an application and a token. */ - CK_RV FC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, - CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession) { +CK_RV +FC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, + CK_VOID_PTR pApplication, CK_NOTIFY Notify, CK_SESSION_HANDLE_PTR phSession) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_OpenSession(slotID,flags,pApplication,Notify,phSession); + return NSC_OpenSession(slotID, flags, pApplication, Notify, phSession); } - /* FC_CloseSession closes a session between an application and a token. */ - CK_RV FC_CloseSession(CK_SESSION_HANDLE hSession) { +CK_RV +FC_CloseSession(CK_SESSION_HANDLE hSession) +{ CHECK_FORK(); return NSC_CloseSession(hSession); } - /* FC_CloseAllSessions closes all sessions with a token. */ - CK_RV FC_CloseAllSessions (CK_SLOT_ID slotID) { +CK_RV +FC_CloseAllSessions(CK_SLOT_ID slotID) +{ CHECK_FORK(); - return NSC_CloseAllSessions (slotID); + return NSC_CloseAllSessions(slotID); } - /* FC_GetSessionInfo obtains information about the session. */ - CK_RV FC_GetSessionInfo(CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo) { +CK_RV +FC_GetSessionInfo(CK_SESSION_HANDLE hSession, + CK_SESSION_INFO_PTR pInfo) +{ CK_RV rv; SFTK_FIPSFATALCHECK(); CHECK_FORK(); - rv = NSC_GetSessionInfo(hSession,pInfo); + rv = NSC_GetSessionInfo(hSession, pInfo); if (rv == CKR_OK) { - if ((isLoggedIn) && (pInfo->state == CKS_RO_PUBLIC_SESSION)) { - pInfo->state = CKS_RO_USER_FUNCTIONS; - } - if ((isLoggedIn) && (pInfo->state == CKS_RW_PUBLIC_SESSION)) { - pInfo->state = CKS_RW_USER_FUNCTIONS; - } + if ((isLoggedIn) && (pInfo->state == CKS_RO_PUBLIC_SESSION)) { + pInfo->state = CKS_RO_USER_FUNCTIONS; + } + if ((isLoggedIn) && (pInfo->state == CKS_RW_PUBLIC_SESSION)) { + pInfo->state = CKS_RW_USER_FUNCTIONS; + } } return rv; } /* FC_Login logs a user into a token. */ - CK_RV FC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, - CK_CHAR_PTR pPin, CK_ULONG usPinLen) { +CK_RV +FC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, + CK_CHAR_PTR pPin, CK_ULONG usPinLen) +{ CK_RV rv; PRBool successful; - if (sftk_fatalError) return CKR_DEVICE_ERROR; - rv = NSC_Login(hSession,userType,pPin,usPinLen); + if (sftk_fatalError) + return CKR_DEVICE_ERROR; + rv = NSC_Login(hSession, userType, pPin, usPinLen); successful = (rv == CKR_OK) || (rv == CKR_USER_ALREADY_LOGGED_IN); if (successful) - isLoggedIn = PR_TRUE; + isLoggedIn = PR_TRUE; if (sftk_audit_enabled) { - char msg[128]; - NSSAuditSeverity severity; - severity = successful ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; - PR_snprintf(msg,sizeof msg, - "C_Login(hSession=0x%08lX, userType=%lu)=0x%08lX", - (PRUint32)hSession,(PRUint32)userType,(PRUint32)rv); - sftk_LogAuditMessage(severity, NSS_AUDIT_LOGIN, msg); + char msg[128]; + NSSAuditSeverity severity; + severity = successful ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + PR_snprintf(msg, sizeof msg, + "C_Login(hSession=0x%08lX, userType=%lu)=0x%08lX", + (PRUint32)hSession, (PRUint32)userType, (PRUint32)rv); + sftk_LogAuditMessage(severity, NSS_AUDIT_LOGIN, msg); } return rv; } /* FC_Logout logs a user out from a token. */ - CK_RV FC_Logout(CK_SESSION_HANDLE hSession) { +CK_RV +FC_Logout(CK_SESSION_HANDLE hSession) +{ CK_RV rv; CHECK_FORK(); if ((rv = sftk_fipsCheck()) == CKR_OK) { - rv = NSC_Logout(hSession); - isLoggedIn = PR_FALSE; + rv = NSC_Logout(hSession); + isLoggedIn = PR_FALSE; } if (sftk_audit_enabled) { - char msg[128]; - NSSAuditSeverity severity = (rv == CKR_OK) ? - NSS_AUDIT_INFO : NSS_AUDIT_ERROR; - PR_snprintf(msg,sizeof msg, - "C_Logout(hSession=0x%08lX)=0x%08lX", - (PRUint32)hSession,(PRUint32)rv); - sftk_LogAuditMessage(severity, NSS_AUDIT_LOGOUT, msg); + char msg[128]; + NSSAuditSeverity severity = (rv == CKR_OK) ? NSS_AUDIT_INFO : NSS_AUDIT_ERROR; + PR_snprintf(msg, sizeof msg, + "C_Logout(hSession=0x%08lX)=0x%08lX", + (PRUint32)hSession, (PRUint32)rv); + sftk_LogAuditMessage(severity, NSS_AUDIT_LOGOUT, msg); } return rv; } - /* FC_CreateObject creates a new object. */ - CK_RV FC_CreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject) { - CK_OBJECT_CLASS * classptr; +CK_RV +FC_CreateObject(CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject) +{ + CK_OBJECT_CLASS *classptr; CK_RV rv = CKR_OK; CHECK_FORK(); - classptr = (CK_OBJECT_CLASS *)fc_getAttribute(pTemplate,ulCount,CKA_CLASS); - if (classptr == NULL) return CKR_TEMPLATE_INCOMPLETE; + classptr = (CK_OBJECT_CLASS *)fc_getAttribute(pTemplate, ulCount, CKA_CLASS); + if (classptr == NULL) + return CKR_TEMPLATE_INCOMPLETE; if (*classptr == CKO_NETSCAPE_NEWSLOT || *classptr == CKO_NETSCAPE_DELSLOT) { if (sftk_fatalError) @@ -738,24 +789,22 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { /* FIPS can't create keys from raw key material */ if (SFTK_IS_NONPUBLIC_KEY_OBJECT(*classptr)) { - rv = CKR_ATTRIBUTE_VALUE_INVALID; + rv = CKR_ATTRIBUTE_VALUE_INVALID; } else { - rv = NSC_CreateObject(hSession,pTemplate,ulCount,phObject); + rv = NSC_CreateObject(hSession, pTemplate, ulCount, phObject); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(*classptr)) { - sftk_AuditCreateObject(hSession,pTemplate,ulCount,phObject,rv); + sftk_AuditCreateObject(hSession, pTemplate, ulCount, phObject, rv); } return rv; } - - - - /* FC_CopyObject copies an object, creating a new object for the copy. */ - CK_RV FC_CopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject) { +CK_RV +FC_CopyObject(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject) +{ CK_RV rv; CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY; @@ -764,19 +813,20 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTK_FIPSFATALCHECK(); rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass); if (rv == CKR_OK) { - rv = NSC_CopyObject(hSession,hObject,pTemplate,ulCount,phNewObject); + rv = NSC_CopyObject(hSession, hObject, pTemplate, ulCount, phNewObject); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) { - sftk_AuditCopyObject(hSession, - hObject,pTemplate,ulCount,phNewObject,rv); + sftk_AuditCopyObject(hSession, + hObject, pTemplate, ulCount, phNewObject, rv); } return rv; } - /* FC_DestroyObject destroys an object. */ - CK_RV FC_DestroyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject) { +CK_RV +FC_DestroyObject(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject) +{ CK_RV rv; CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY; @@ -785,18 +835,19 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTK_FIPSFATALCHECK(); rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass); if (rv == CKR_OK) { - rv = NSC_DestroyObject(hSession,hObject); + rv = NSC_DestroyObject(hSession, hObject); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) { - sftk_AuditDestroyObject(hSession,hObject,rv); + sftk_AuditDestroyObject(hSession, hObject, rv); } return rv; } - /* FC_GetObjectSize gets the size of an object in bytes. */ - CK_RV FC_GetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { +CK_RV +FC_GetObjectSize(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) +{ CK_RV rv; CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY; @@ -805,18 +856,19 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTK_FIPSFATALCHECK(); rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass); if (rv == CKR_OK) { - rv = NSC_GetObjectSize(hSession, hObject, pulSize); + rv = NSC_GetObjectSize(hSession, hObject, pulSize); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) { - sftk_AuditGetObjectSize(hSession, hObject, pulSize, rv); + sftk_AuditGetObjectSize(hSession, hObject, pulSize, rv); } return rv; } - /* FC_GetAttributeValue obtains the value of one or more object attributes. */ - CK_RV FC_GetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) { +CK_RV +FC_GetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) +{ CK_RV rv; CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY; @@ -825,18 +877,19 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTK_FIPSFATALCHECK(); rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass); if (rv == CKR_OK) { - rv = NSC_GetAttributeValue(hSession,hObject,pTemplate,ulCount); + rv = NSC_GetAttributeValue(hSession, hObject, pTemplate, ulCount); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) { - sftk_AuditGetAttributeValue(hSession,hObject,pTemplate,ulCount,rv); + sftk_AuditGetAttributeValue(hSession, hObject, pTemplate, ulCount, rv); } return rv; } - /* FC_SetAttributeValue modifies the value of one or more object attributes */ - CK_RV FC_SetAttributeValue (CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) { +CK_RV +FC_SetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) +{ CK_RV rv; CK_OBJECT_CLASS objClass = CKO_NOT_A_KEY; @@ -845,387 +898,417 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTK_FIPSFATALCHECK(); rv = sftk_get_object_class_and_fipsCheck(hSession, hObject, &objClass); if (rv == CKR_OK) { - rv = NSC_SetAttributeValue(hSession,hObject,pTemplate,ulCount); + rv = NSC_SetAttributeValue(hSession, hObject, pTemplate, ulCount); } if (sftk_audit_enabled && SFTK_IS_KEY_OBJECT(objClass)) { - sftk_AuditSetAttributeValue(hSession,hObject,pTemplate,ulCount,rv); + sftk_AuditSetAttributeValue(hSession, hObject, pTemplate, ulCount, rv); } return rv; } - - -/* FC_FindObjectsInit initializes a search for token and session objects +/* FC_FindObjectsInit initializes a search for token and session objects * that match a template. */ - CK_RV FC_FindObjectsInit(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate,CK_ULONG usCount) { +CK_RV +FC_FindObjectsInit(CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usCount) +{ /* let publically readable object be found */ unsigned int i; CK_RV rv; PRBool needLogin = PR_FALSE; - CHECK_FORK(); SFTK_FIPSFATALCHECK(); - for (i=0; i < usCount; i++) { - CK_OBJECT_CLASS class; - if (pTemplate[i].type != CKA_CLASS) { - continue; - } - if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) { - continue; - } - if (pTemplate[i].pValue == NULL) { - continue; - } - class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; - if ((class == CKO_PRIVATE_KEY) || (class == CKO_SECRET_KEY)) { - needLogin = PR_TRUE; - break; - } + for (i = 0; i < usCount; i++) { + CK_OBJECT_CLASS class; + if (pTemplate[i].type != CKA_CLASS) { + continue; + } + if (pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS)) { + continue; + } + if (pTemplate[i].pValue == NULL) { + continue; + } + class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; + if ((class == CKO_PRIVATE_KEY) || (class == CKO_SECRET_KEY)) { + needLogin = PR_TRUE; + break; + } } if (needLogin) { - if ((rv = sftk_fipsCheck()) != CKR_OK) return rv; + if ((rv = sftk_fipsCheck()) != CKR_OK) + return rv; } - return NSC_FindObjectsInit(hSession,pTemplate,usCount); + return NSC_FindObjectsInit(hSession, pTemplate, usCount); } - -/* FC_FindObjects continues a search for token and session objects +/* FC_FindObjects continues a search for token and session objects * that match a template, obtaining additional object handles. */ - CK_RV FC_FindObjects(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject,CK_ULONG usMaxObjectCount, - CK_ULONG_PTR pusObjectCount) { +CK_RV +FC_FindObjects(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE_PTR phObject, CK_ULONG usMaxObjectCount, + CK_ULONG_PTR pusObjectCount) +{ CHECK_FORK(); /* let publically readable object be found */ SFTK_FIPSFATALCHECK(); - return NSC_FindObjects(hSession,phObject,usMaxObjectCount, - pusObjectCount); + return NSC_FindObjects(hSession, phObject, usMaxObjectCount, + pusObjectCount); } - /* ************** Crypto Functions: Encrypt ************************ */ /* FC_EncryptInit initializes an encryption operation. */ - CK_RV FC_EncryptInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { +CK_RV +FC_EncryptInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_EncryptInit(hSession,pMechanism,hKey); + rv = NSC_EncryptInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("Encrypt",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("Encrypt", hSession, pMechanism, hKey, rv); } return rv; } /* FC_Encrypt encrypts single-part data. */ - CK_RV FC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pusEncryptedDataLen) { +CK_RV +FC_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG usDataLen, CK_BYTE_PTR pEncryptedData, + CK_ULONG_PTR pusEncryptedDataLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_Encrypt(hSession,pData,usDataLen,pEncryptedData, - pusEncryptedDataLen); + return NSC_Encrypt(hSession, pData, usDataLen, pEncryptedData, + pusEncryptedDataLen); } - /* FC_EncryptUpdate continues a multiple-part encryption operation. */ - CK_RV FC_EncryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, CK_ULONG usPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pusEncryptedPartLen) { +CK_RV +FC_EncryptUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, CK_ULONG usPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pusEncryptedPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_EncryptUpdate(hSession,pPart,usPartLen,pEncryptedPart, - pusEncryptedPartLen); + return NSC_EncryptUpdate(hSession, pPart, usPartLen, pEncryptedPart, + pusEncryptedPartLen); } - /* FC_EncryptFinal finishes a multiple-part encryption operation. */ - CK_RV FC_EncryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pusLastEncryptedPartLen) { +CK_RV +FC_EncryptFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pusLastEncryptedPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_EncryptFinal(hSession,pLastEncryptedPart, - pusLastEncryptedPartLen); + return NSC_EncryptFinal(hSession, pLastEncryptedPart, + pusLastEncryptedPartLen); } /* ************** Crypto Functions: Decrypt ************************ */ - /* FC_DecryptInit initializes a decryption operation. */ - CK_RV FC_DecryptInit( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { +CK_RV +FC_DecryptInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_DecryptInit(hSession,pMechanism,hKey); + rv = NSC_DecryptInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("Decrypt",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("Decrypt", hSession, pMechanism, hKey, rv); } return rv; } /* FC_Decrypt decrypts encrypted data in a single part. */ - CK_RV FC_Decrypt(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData,CK_ULONG usEncryptedDataLen,CK_BYTE_PTR pData, - CK_ULONG_PTR pusDataLen) { +CK_RV +FC_Decrypt(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, CK_ULONG usEncryptedDataLen, CK_BYTE_PTR pData, + CK_ULONG_PTR pusDataLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_Decrypt(hSession,pEncryptedData,usEncryptedDataLen,pData, - pusDataLen); + return NSC_Decrypt(hSession, pEncryptedData, usEncryptedDataLen, pData, + pusDataLen); } - /* FC_DecryptUpdate continues a multiple-part decryption operation. */ - CK_RV FC_DecryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG usEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pusPartLen) { +CK_RV +FC_DecryptUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, CK_ULONG usEncryptedPartLen, + CK_BYTE_PTR pPart, CK_ULONG_PTR pusPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_DecryptUpdate(hSession,pEncryptedPart,usEncryptedPartLen, - pPart,pusPartLen); + return NSC_DecryptUpdate(hSession, pEncryptedPart, usEncryptedPartLen, + pPart, pusPartLen); } - /* FC_DecryptFinal finishes a multiple-part decryption operation. */ - CK_RV FC_DecryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, CK_ULONG_PTR pusLastPartLen) { +CK_RV +FC_DecryptFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastPart, CK_ULONG_PTR pusLastPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_DecryptFinal(hSession,pLastPart,pusLastPartLen); + return NSC_DecryptFinal(hSession, pLastPart, pusLastPartLen); } - /* ************** Crypto Functions: Digest (HASH) ************************ */ /* FC_DigestInit initializes a message-digesting operation. */ - CK_RV FC_DigestInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism) { +CK_RV +FC_DigestInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); return NSC_DigestInit(hSession, pMechanism); } - /* FC_Digest digests data in a single part. */ - CK_RV FC_Digest(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pDigest, - CK_ULONG_PTR pusDigestLen) { +CK_RV +FC_Digest(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pDigest, + CK_ULONG_PTR pusDigestLen) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_Digest(hSession,pData,usDataLen,pDigest,pusDigestLen); + return NSC_Digest(hSession, pData, usDataLen, pDigest, pusDigestLen); } - /* FC_DigestUpdate continues a multiple-part message-digesting operation. */ - CK_RV FC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { +CK_RV +FC_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG usPartLen) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_DigestUpdate(hSession,pPart,usPartLen); + return NSC_DigestUpdate(hSession, pPart, usPartLen); } - /* FC_DigestFinal finishes a multiple-part message-digesting operation. */ - CK_RV FC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, - CK_ULONG_PTR pusDigestLen) { +CK_RV +FC_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, + CK_ULONG_PTR pusDigestLen) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_DigestFinal(hSession,pDigest,pusDigestLen); + return NSC_DigestFinal(hSession, pDigest, pusDigestLen); } - /* ************** Crypto Functions: Sign ************************ */ /* FC_SignInit initializes a signature (private key encryption) operation, - * where the signature is (will be) an appendix to the data, + * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature */ - CK_RV FC_SignInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { +CK_RV +FC_SignInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_SignInit(hSession,pMechanism,hKey); + rv = NSC_SignInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("Sign",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("Sign", hSession, pMechanism, hKey, rv); } return rv; } - /* FC_Sign signs (encrypts with private key) data in a single part, - * where the signature is (will be) an appendix to the data, + * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature */ - CK_RV FC_Sign(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData,CK_ULONG usDataLen,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pusSignatureLen) { +CK_RV +FC_Sign(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, CK_ULONG usDataLen, CK_BYTE_PTR pSignature, + CK_ULONG_PTR pusSignatureLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_Sign(hSession,pData,usDataLen,pSignature,pusSignatureLen); + return NSC_Sign(hSession, pData, usDataLen, pSignature, pusSignatureLen); } - /* FC_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, + * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature */ - CK_RV FC_SignUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { +CK_RV +FC_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG usPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_SignUpdate(hSession,pPart,usPartLen); + return NSC_SignUpdate(hSession, pPart, usPartLen); } - -/* FC_SignFinal finishes a multiple-part signature operation, +/* FC_SignFinal finishes a multiple-part signature operation, * returning the signature. */ - CK_RV FC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pusSignatureLen) { +CK_RV +FC_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, + CK_ULONG_PTR pusSignatureLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_SignFinal(hSession,pSignature,pusSignatureLen); + return NSC_SignFinal(hSession, pSignature, pusSignatureLen); } /* ************** Crypto Functions: Sign Recover ************************ */ /* FC_SignRecoverInit initializes a signature operation, - * where the (digest) data can be recovered from the signature. + * where the (digest) data can be recovered from the signature. * E.g. encryption with the user's private key */ - CK_RV FC_SignRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { +CK_RV +FC_SignRecoverInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_SignRecoverInit(hSession,pMechanism,hKey); + rv = NSC_SignRecoverInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("SignRecover",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("SignRecover", hSession, pMechanism, hKey, rv); } return rv; } - /* FC_SignRecover signs data in a single operation - * where the (digest) data can be recovered from the signature. + * where the (digest) data can be recovered from the signature. * E.g. encryption with the user's private key */ - CK_RV FC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen) { +CK_RV +FC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pusSignatureLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_SignRecover(hSession,pData,usDataLen,pSignature,pusSignatureLen); + return NSC_SignRecover(hSession, pData, usDataLen, pSignature, pusSignatureLen); } /* ************** Crypto Functions: verify ************************ */ -/* FC_VerifyInit initializes a verification operation, - * where the signature is an appendix to the data, +/* FC_VerifyInit initializes a verification operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature (e.g. DSA) */ - CK_RV FC_VerifyInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { +CK_RV +FC_VerifyInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_VerifyInit(hSession,pMechanism,hKey); + rv = NSC_VerifyInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("Verify",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("Verify", hSession, pMechanism, hKey, rv); } return rv; } - -/* FC_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, +/* FC_Verify verifies a signature in a single-part operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature */ - CK_RV FC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen) { +CK_RV +FC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG usDataLen, CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen) +{ /* make sure we're legal */ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_Verify(hSession,pData,usDataLen,pSignature,usSignatureLen); + return NSC_Verify(hSession, pData, usDataLen, pSignature, usSignatureLen); } - -/* FC_VerifyUpdate continues a multiple-part verification operation, - * where the signature is an appendix to the data, +/* FC_VerifyUpdate continues a multiple-part verification operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature */ - CK_RV FC_VerifyUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG usPartLen) { +CK_RV +FC_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG usPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_VerifyUpdate(hSession,pPart,usPartLen); + return NSC_VerifyUpdate(hSession, pPart, usPartLen); } - -/* FC_VerifyFinal finishes a multiple-part verification operation, +/* FC_VerifyFinal finishes a multiple-part verification operation, * checking the signature. */ - CK_RV FC_VerifyFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen) { +CK_RV +FC_VerifyFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_VerifyFinal(hSession,pSignature,usSignatureLen); + return NSC_VerifyFinal(hSession, pSignature, usSignatureLen); } /* ************** Crypto Functions: Verify Recover ************************ */ -/* FC_VerifyRecoverInit initializes a signature verification operation, - * where the data is recovered from the signature. +/* FC_VerifyRecoverInit initializes a signature verification operation, + * where the data is recovered from the signature. * E.g. Decryption with the user's public key */ - CK_RV FC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) { +CK_RV +FC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_VerifyRecoverInit(hSession,pMechanism,hKey); + rv = NSC_VerifyRecoverInit(hSession, pMechanism, hKey); if (sftk_audit_enabled) { - sftk_AuditCryptInit("VerifyRecover",hSession,pMechanism,hKey,rv); + sftk_AuditCryptInit("VerifyRecover", hSession, pMechanism, hKey, rv); } return rv; } - -/* FC_VerifyRecover verifies a signature in a single-part operation, - * where the data is recovered from the signature. +/* FC_VerifyRecover verifies a signature in a single-part operation, + * where the data is recovered from the signature. * E.g. Decryption with the user's public key */ - CK_RV FC_VerifyRecover(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG usSignatureLen, - CK_BYTE_PTR pData,CK_ULONG_PTR pusDataLen) { +CK_RV +FC_VerifyRecover(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, CK_ULONG usSignatureLen, + CK_BYTE_PTR pData, CK_ULONG_PTR pusDataLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_VerifyRecover(hSession,pSignature,usSignatureLen,pData, - pusDataLen); + return NSC_VerifyRecover(hSession, pSignature, usSignatureLen, pData, + pusDataLen); } /* @@ -1233,9 +1316,11 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { */ /* FC_GenerateKey generates a secret key, creating a new key object. */ - CK_RV FC_GenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey) { +CK_RV +FC_GenerateKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phKey) +{ CK_BBOOL *boolptr; SFTK_FIPSCHECK(); @@ -1243,84 +1328,86 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { /* all secret keys must be sensitive, if the upper level code tries to say * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, ulCount, CKA_SENSITIVE); + boolptr = (CK_BBOOL *)fc_getAttribute(pTemplate, ulCount, CKA_SENSITIVE); if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } + if (!(*boolptr)) { + return CKR_ATTRIBUTE_VALUE_INVALID; + } } - rv = NSC_GenerateKey(hSession,pMechanism,pTemplate,ulCount,phKey); + rv = NSC_GenerateKey(hSession, pMechanism, pTemplate, ulCount, phKey); if (sftk_audit_enabled) { - sftk_AuditGenerateKey(hSession,pMechanism,pTemplate,ulCount,phKey,rv); + sftk_AuditGenerateKey(hSession, pMechanism, pTemplate, ulCount, phKey, rv); } return rv; } - -/* FC_GenerateKeyPair generates a public-key/private-key pair, +/* FC_GenerateKeyPair generates a public-key/private-key pair, * creating new key objects. */ - CK_RV FC_GenerateKeyPair (CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG usPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG usPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey) { +CK_RV +FC_GenerateKeyPair(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG usPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG usPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, + CK_OBJECT_HANDLE_PTR phPrivateKey) +{ CK_BBOOL *boolptr; CK_RV crv; SFTK_FIPSCHECK(); CHECK_FORK(); - /* all private keys must be sensitive, if the upper level code tries to say * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pPrivateKeyTemplate, - usPrivateKeyAttributeCount, CKA_SENSITIVE); + boolptr = (CK_BBOOL *)fc_getAttribute(pPrivateKeyTemplate, + usPrivateKeyAttributeCount, CKA_SENSITIVE); if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } + if (!(*boolptr)) { + return CKR_ATTRIBUTE_VALUE_INVALID; + } } - crv = NSC_GenerateKeyPair (hSession,pMechanism,pPublicKeyTemplate, - usPublicKeyAttributeCount,pPrivateKeyTemplate, - usPrivateKeyAttributeCount,phPublicKey,phPrivateKey); + crv = NSC_GenerateKeyPair(hSession, pMechanism, pPublicKeyTemplate, + usPublicKeyAttributeCount, pPrivateKeyTemplate, + usPrivateKeyAttributeCount, phPublicKey, phPrivateKey); if (crv == CKR_GENERAL_ERROR) { - /* pairwise consistency check failed. */ - sftk_fatalError = PR_TRUE; + /* pairwise consistency check failed. */ + sftk_fatalError = PR_TRUE; } if (sftk_audit_enabled) { - sftk_AuditGenerateKeyPair(hSession,pMechanism,pPublicKeyTemplate, - usPublicKeyAttributeCount,pPrivateKeyTemplate, - usPrivateKeyAttributeCount,phPublicKey,phPrivateKey,crv); + sftk_AuditGenerateKeyPair(hSession, pMechanism, pPublicKeyTemplate, + usPublicKeyAttributeCount, pPrivateKeyTemplate, + usPrivateKeyAttributeCount, phPublicKey, phPrivateKey, crv); } return crv; } - /* FC_WrapKey wraps (i.e., encrypts) a key. */ - CK_RV FC_WrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen) { +CK_RV +FC_WrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, + CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_WrapKey(hSession,pMechanism,hWrappingKey,hKey,pWrappedKey, - pulWrappedKeyLen); + rv = NSC_WrapKey(hSession, pMechanism, hWrappingKey, hKey, pWrappedKey, + pulWrappedKeyLen); if (sftk_audit_enabled) { - sftk_AuditWrapKey(hSession,pMechanism,hWrappingKey,hKey,pWrappedKey, - pulWrappedKeyLen,rv); + sftk_AuditWrapKey(hSession, pMechanism, hWrappingKey, hKey, pWrappedKey, + pulWrappedKeyLen, rv); } return rv; } - /* FC_UnwrapKey unwraps (decrypts) a wrapped key, creating a new key object. */ - CK_RV FC_UnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) { +CK_RV +FC_UnwrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, + CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) +{ CK_BBOOL *boolptr; SFTK_FIPSCHECK(); @@ -1328,28 +1415,29 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { /* all secret keys must be sensitive, if the upper level code tries to say * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, - ulAttributeCount, CKA_SENSITIVE); + boolptr = (CK_BBOOL *)fc_getAttribute(pTemplate, + ulAttributeCount, CKA_SENSITIVE); if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } + if (!(*boolptr)) { + return CKR_ATTRIBUTE_VALUE_INVALID; + } } - rv = NSC_UnwrapKey(hSession,pMechanism,hUnwrappingKey,pWrappedKey, - ulWrappedKeyLen,pTemplate,ulAttributeCount,phKey); + rv = NSC_UnwrapKey(hSession, pMechanism, hUnwrappingKey, pWrappedKey, + ulWrappedKeyLen, pTemplate, ulAttributeCount, phKey); if (sftk_audit_enabled) { - sftk_AuditUnwrapKey(hSession,pMechanism,hUnwrappingKey,pWrappedKey, - ulWrappedKeyLen,pTemplate,ulAttributeCount,phKey,rv); + sftk_AuditUnwrapKey(hSession, pMechanism, hUnwrappingKey, pWrappedKey, + ulWrappedKeyLen, pTemplate, ulAttributeCount, phKey, rv); } return rv; } - /* FC_DeriveKey derives a key from a base key, creating a new key object. */ - CK_RV FC_DeriveKey( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) { +CK_RV +FC_DeriveKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) +{ CK_BBOOL *boolptr; SFTK_FIPSCHECK(); @@ -1357,18 +1445,18 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { /* all secret keys must be sensitive, if the upper level code tries to say * otherwise, reject it. */ - boolptr = (CK_BBOOL *) fc_getAttribute(pTemplate, - ulAttributeCount, CKA_SENSITIVE); + boolptr = (CK_BBOOL *)fc_getAttribute(pTemplate, + ulAttributeCount, CKA_SENSITIVE); if (boolptr != NULL) { - if (!(*boolptr)) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } + if (!(*boolptr)) { + return CKR_ATTRIBUTE_VALUE_INVALID; + } } - rv = NSC_DeriveKey(hSession,pMechanism,hBaseKey,pTemplate, - ulAttributeCount, phKey); + rv = NSC_DeriveKey(hSession, pMechanism, hBaseKey, pTemplate, + ulAttributeCount, phKey); if (sftk_audit_enabled) { - sftk_AuditDeriveKey(hSession,pMechanism,hBaseKey,pTemplate, - ulAttributeCount,phKey,rv); + sftk_AuditDeriveKey(hSession, pMechanism, hBaseKey, pTemplate, + ulAttributeCount, phKey, rv); } return rv; } @@ -1377,61 +1465,66 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { **************************** Radom Functions: ************************ */ -/* FC_SeedRandom mixes additional seed material into the token's random number +/* FC_SeedRandom mixes additional seed material into the token's random number * generator. */ - CK_RV FC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, - CK_ULONG usSeedLen) { +CK_RV +FC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, + CK_ULONG usSeedLen) +{ CK_RV crv; SFTK_FIPSFATALCHECK(); CHECK_FORK(); - crv = NSC_SeedRandom(hSession,pSeed,usSeedLen); + crv = NSC_SeedRandom(hSession, pSeed, usSeedLen); if (crv != CKR_OK) { - sftk_fatalError = PR_TRUE; + sftk_fatalError = PR_TRUE; } return crv; } - /* FC_GenerateRandom generates random data. */ - CK_RV FC_GenerateRandom(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) { +CK_RV +FC_GenerateRandom(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) +{ CK_RV crv; CHECK_FORK(); SFTK_FIPSFATALCHECK(); - crv = NSC_GenerateRandom(hSession,pRandomData,ulRandomLen); + crv = NSC_GenerateRandom(hSession, pRandomData, ulRandomLen); if (crv != CKR_OK) { - sftk_fatalError = PR_TRUE; - if (sftk_audit_enabled) { - char msg[128]; - PR_snprintf(msg,sizeof msg, - "C_GenerateRandom(hSession=0x%08lX, pRandomData=%p, " - "ulRandomLen=%lu)=0x%08lX " - "self-test: continuous RNG test failed", - (PRUint32)hSession,pRandomData, - (PRUint32)ulRandomLen,(PRUint32)crv); - sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); - } + sftk_fatalError = PR_TRUE; + if (sftk_audit_enabled) { + char msg[128]; + PR_snprintf(msg, sizeof msg, + "C_GenerateRandom(hSession=0x%08lX, pRandomData=%p, " + "ulRandomLen=%lu)=0x%08lX " + "self-test: continuous RNG test failed", + (PRUint32)hSession, pRandomData, + (PRUint32)ulRandomLen, (PRUint32)crv); + sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); + } } return crv; } - -/* FC_GetFunctionStatus obtains an updated status of a function running +/* FC_GetFunctionStatus obtains an updated status of a function running * in parallel with an application. */ - CK_RV FC_GetFunctionStatus(CK_SESSION_HANDLE hSession) { +CK_RV +FC_GetFunctionStatus(CK_SESSION_HANDLE hSession) +{ SFTK_FIPSCHECK(); CHECK_FORK(); return NSC_GetFunctionStatus(hSession); } - /* FC_CancelFunction cancels a function running in parallel */ - CK_RV FC_CancelFunction(CK_SESSION_HANDLE hSession) { +CK_RV +FC_CancelFunction(CK_SESSION_HANDLE hSession) +{ SFTK_FIPSCHECK(); CHECK_FORK(); @@ -1442,31 +1535,36 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { **************************** Version 1.1 Functions: ************************ */ -/* FC_GetOperationState saves the state of the cryptographic +/* FC_GetOperationState saves the state of the cryptographic *operation in a session. */ -CK_RV FC_GetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) { +CK_RV +FC_GetOperationState(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_GetOperationState(hSession,pOperationState,pulOperationStateLen); + return NSC_GetOperationState(hSession, pOperationState, pulOperationStateLen); } - -/* FC_SetOperationState restores the state of the cryptographic operation +/* FC_SetOperationState restores the state of the cryptographic operation * in a session. */ -CK_RV FC_SetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) { +CK_RV +FC_SetOperationState(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, + CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) +{ SFTK_FIPSFATALCHECK(); CHECK_FORK(); - return NSC_SetOperationState(hSession,pOperationState,ulOperationStateLen, - hEncryptionKey,hAuthenticationKey); + return NSC_SetOperationState(hSession, pOperationState, ulOperationStateLen, + hEncryptionKey, hAuthenticationKey); } /* FC_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV FC_FindObjectsFinal(CK_SESSION_HANDLE hSession) { +CK_RV +FC_FindObjectsFinal(CK_SESSION_HANDLE hSession) +{ /* let publically readable object be found */ SFTK_FIPSFATALCHECK(); CHECK_FORK(); @@ -1474,76 +1572,83 @@ CK_RV FC_FindObjectsFinal(CK_SESSION_HANDLE hSession) { return NSC_FindObjectsFinal(hSession); } - /* Dual-function cryptographic operations */ -/* FC_DigestEncryptUpdate continues a multiple-part digesting and encryption +/* FC_DigestEncryptUpdate continues a multiple-part digesting and encryption * operation. */ -CK_RV FC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) { +CK_RV +FC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_DigestEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart, - pulEncryptedPartLen); + return NSC_DigestEncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, + pulEncryptedPartLen); } - -/* FC_DecryptDigestUpdate continues a multiple-part decryption and digesting +/* FC_DecryptDigestUpdate continues a multiple-part decryption and digesting * operation. */ -CK_RV FC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { +CK_RV +FC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_DecryptDigestUpdate(hSession, pEncryptedPart,ulEncryptedPartLen, - pPart,pulPartLen); + return NSC_DecryptDigestUpdate(hSession, pEncryptedPart, ulEncryptedPartLen, + pPart, pulPartLen); } -/* FC_SignEncryptUpdate continues a multiple-part signing and encryption +/* FC_SignEncryptUpdate continues a multiple-part signing and encryption * operation. */ -CK_RV FC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) { +CK_RV +FC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_SignEncryptUpdate(hSession,pPart,ulPartLen,pEncryptedPart, - pulEncryptedPartLen); + return NSC_SignEncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, + pulEncryptedPartLen); } -/* FC_DecryptVerifyUpdate continues a multiple-part decryption and verify +/* FC_DecryptVerifyUpdate continues a multiple-part decryption and verify * operation. */ -CK_RV FC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { +CK_RV +FC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, + CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - return NSC_DecryptVerifyUpdate(hSession,pEncryptedData,ulEncryptedDataLen, - pData,pulDataLen); + return NSC_DecryptVerifyUpdate(hSession, pEncryptedData, ulEncryptedDataLen, + pData, pulDataLen); } - /* FC_DigestKey continues a multi-part message-digesting operation, * by digesting the value of a secret key as part of the data already digested. */ -CK_RV FC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { +CK_RV +FC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) +{ SFTK_FIPSCHECK(); CHECK_FORK(); - rv = NSC_DigestKey(hSession,hKey); + rv = NSC_DigestKey(hSession, hKey); if (sftk_audit_enabled) { - sftk_AuditDigestKey(hSession,hKey,rv); + sftk_AuditDigestKey(hSession, hKey, rv); } return rv; } - -CK_RV FC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved) +CK_RV +FC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, + CK_VOID_PTR pReserved) { CHECK_FORK(); diff --git a/nss/lib/softoken/jpakesftk.c b/nss/lib/softoken/jpakesftk.c index 4f91c72..7ed1e34 100644 --- a/nss/lib/softoken/jpakesftk.c +++ b/nss/lib/softoken/jpakesftk.c @@ -9,7 +9,8 @@ #include "softoken.h" static CK_RV -jpake_mapStatus(SECStatus rv, CK_RV invalidArgsMapping) { +jpake_mapStatus(SECStatus rv, CK_RV invalidArgsMapping) +{ int err; if (rv == SECSuccess) return CKR_OK; @@ -17,9 +18,12 @@ jpake_mapStatus(SECStatus rv, CK_RV invalidArgsMapping) { switch (err) { /* XXX: SEC_ERROR_INVALID_ARGS might be caused by invalid template parameters. */ - case SEC_ERROR_INVALID_ARGS: return invalidArgsMapping; - case SEC_ERROR_BAD_SIGNATURE: return CKR_SIGNATURE_INVALID; - case SEC_ERROR_NO_MEMORY: return CKR_HOST_MEMORY; + case SEC_ERROR_INVALID_ARGS: + return invalidArgsMapping; + case SEC_ERROR_BAD_SIGNATURE: + return CKR_SIGNATURE_INVALID; + case SEC_ERROR_NO_MEMORY: + return CKR_HOST_MEMORY; } return CKR_FUNCTION_FAILED; } @@ -27,15 +31,15 @@ jpake_mapStatus(SECStatus rv, CK_RV invalidArgsMapping) { /* If key is not NULL then the gx value will be stored as an attribute with the type given by the gxAttrType parameter. */ static CK_RV -jpake_Sign(PLArenaPool * arena, const PQGParams * pqg, HASH_HashType hashType, - const SECItem * signerID, const SECItem * x, - CK_NSS_JPAKEPublicValue * out) +jpake_Sign(PLArenaPool *arena, const PQGParams *pqg, HASH_HashType hashType, + const SECItem *signerID, const SECItem *x, + CK_NSS_JPAKEPublicValue *out) { SECItem gx, gv, r; CK_RV crv; PORT_Assert(arena != NULL); - + gx.data = NULL; gv.data = NULL; r.data = NULL; @@ -45,9 +49,9 @@ jpake_Sign(PLArenaPool * arena, const PQGParams * pqg, HASH_HashType hashType, if (crv == CKR_OK) { if ((out->pGX != NULL && out->ulGXLen >= gx.len) || (out->pGV != NULL && out->ulGVLen >= gv.len) || - (out->pR != NULL && out->ulRLen >= r.len)) { - PORT_Memcpy(out->pGX, gx.data, gx.len); - PORT_Memcpy(out->pGV, gv.data, gv.len); + (out->pR != NULL && out->ulRLen >= r.len)) { + PORT_Memcpy(out->pGX, gx.data, gx.len); + PORT_Memcpy(out->pGV, gv.data, gv.len); PORT_Memcpy(out->pR, r.data, r.len); out->ulGXLen = gx.len; out->ulGVLen = gv.len; @@ -55,40 +59,45 @@ jpake_Sign(PLArenaPool * arena, const PQGParams * pqg, HASH_HashType hashType, } else { crv = CKR_MECHANISM_PARAM_INVALID; } - } + } return crv; } static CK_RV -jpake_Verify(PLArenaPool * arena, const PQGParams * pqg, - HASH_HashType hashType, const SECItem * signerID, - const CK_BYTE * peerIDData, CK_ULONG peerIDLen, - const CK_NSS_JPAKEPublicValue * publicValueIn) +jpake_Verify(PLArenaPool *arena, const PQGParams *pqg, + HASH_HashType hashType, const SECItem *signerID, + const CK_BYTE *peerIDData, CK_ULONG peerIDLen, + const CK_NSS_JPAKEPublicValue *publicValueIn) { SECItem peerID, gx, gv, r; - peerID.data = (unsigned char *) peerIDData; peerID.len = peerIDLen; - gx.data = publicValueIn->pGX; gx.len = publicValueIn->ulGXLen; - gv.data = publicValueIn->pGV; gv.len = publicValueIn->ulGVLen; - r.data = publicValueIn->pR; r.len = publicValueIn->ulRLen; + peerID.data = (unsigned char *)peerIDData; + peerID.len = peerIDLen; + gx.data = publicValueIn->pGX; + gx.len = publicValueIn->ulGXLen; + gv.data = publicValueIn->pGV; + gv.len = publicValueIn->ulGVLen; + r.data = publicValueIn->pR; + r.len = publicValueIn->ulRLen; return jpake_mapStatus(JPAKE_Verify(arena, pqg, hashType, signerID, &peerID, &gx, &gv, &r), CKR_MECHANISM_PARAM_INVALID); } -#define NUM_ELEM(x) (sizeof (x) / sizeof (x)[0]) +#define NUM_ELEM(x) (sizeof(x) / sizeof(x)[0]) /* If the template has the key type set, ensure that it was set to the correct * value. If the template did not have the key type set, set it to the * correct value. */ static CK_RV -jpake_enforceKeyType(SFTKObject * key, CK_KEY_TYPE keyType) { +jpake_enforceKeyType(SFTKObject *key, CK_KEY_TYPE keyType) +{ CK_RV crv; - SFTKAttribute * keyTypeAttr = sftk_FindAttribute(key, CKA_KEY_TYPE); + SFTKAttribute *keyTypeAttr = sftk_FindAttribute(key, CKA_KEY_TYPE); if (keyTypeAttr != NULL) { crv = *(CK_KEY_TYPE *)keyTypeAttr->attrib.pValue == keyType - ? CKR_OK - : CKR_TEMPLATE_INCONSISTENT; + ? CKR_OK + : CKR_TEMPLATE_INCONSISTENT; sftk_FreeAttribute(keyTypeAttr); } else { crv = sftk_forceAttribute(key, CKA_KEY_TYPE, &keyType, sizeof keyType); @@ -97,11 +106,11 @@ jpake_enforceKeyType(SFTKObject * key, CK_KEY_TYPE keyType) { } static CK_RV -jpake_MultipleSecItem2Attribute(SFTKObject * key, const SFTKItemTemplate * attrs, +jpake_MultipleSecItem2Attribute(SFTKObject *key, const SFTKItemTemplate *attrs, size_t attrsCount) { size_t i; - + for (i = 0; i < attrsCount; ++i) { CK_RV crv = sftk_forceAttribute(key, attrs[i].type, attrs[i].item->data, attrs[i].item->len); @@ -112,12 +121,12 @@ jpake_MultipleSecItem2Attribute(SFTKObject * key, const SFTKItemTemplate * attrs } CK_RV -jpake_Round1(HASH_HashType hashType, CK_NSS_JPAKERound1Params * params, - SFTKObject * key) +jpake_Round1(HASH_HashType hashType, CK_NSS_JPAKERound1Params *params, + SFTKObject *key) { CK_RV crv; PQGParams pqg; - PLArenaPool * arena; + PLArenaPool *arena; SECItem signerID; SFTKItemTemplate templateAttrs[] = { { CKA_PRIME, &pqg.prime }, @@ -127,7 +136,7 @@ jpake_Round1(HASH_HashType hashType, CK_NSS_JPAKERound1Params * params, }; SECItem x2, gx1, gx2; const SFTKItemTemplate generatedAttrs[] = { - { CKA_NSS_JPAKE_X2, &x2 }, + { CKA_NSS_JPAKE_X2, &x2 }, { CKA_NSS_JPAKE_GX1, &gx1 }, { CKA_NSS_JPAKE_GX2, &gx2 }, }; @@ -170,7 +179,7 @@ jpake_Round1(HASH_HashType hashType, CK_NSS_JPAKERound1Params * params, gx1.len = params->gx1.ulGXLen; gx2.data = params->gx2.pGX; gx2.len = params->gx2.ulGXLen; - crv = jpake_MultipleSecItem2Attribute(key, generatedAttrs, + crv = jpake_MultipleSecItem2Attribute(key, generatedAttrs, NUM_ELEM(generatedAttrs)); } @@ -179,19 +188,19 @@ jpake_Round1(HASH_HashType hashType, CK_NSS_JPAKERound1Params * params, } CK_RV -jpake_Round2(HASH_HashType hashType, CK_NSS_JPAKERound2Params * params, - SFTKObject * sourceKey, SFTKObject * key) +jpake_Round2(HASH_HashType hashType, CK_NSS_JPAKERound2Params *params, + SFTKObject *sourceKey, SFTKObject *key) { CK_RV crv; - PLArenaPool * arena; + PLArenaPool *arena; PQGParams pqg; SECItem signerID, x2, gx1, gx2; - SFTKItemTemplate sourceAttrs[] = { + SFTKItemTemplate sourceAttrs[] = { { CKA_PRIME, &pqg.prime }, { CKA_SUBPRIME, &pqg.subPrime }, { CKA_BASE, &pqg.base }, { CKA_NSS_JPAKE_SIGNERID, &signerID }, - { CKA_NSS_JPAKE_X2, &x2 }, + { CKA_NSS_JPAKE_X2, &x2 }, { CKA_NSS_JPAKE_GX1, &gx1 }, { CKA_NSS_JPAKE_GX2, &gx2 }, }; @@ -200,7 +209,7 @@ jpake_Round2(HASH_HashType hashType, CK_NSS_JPAKERound2Params * params, { CKA_NSS_JPAKE_SIGNERID, &signerID }, { CKA_PRIME, &pqg.prime }, { CKA_SUBPRIME, &pqg.subPrime }, - { CKA_NSS_JPAKE_X2, &x2 }, + { CKA_NSS_JPAKE_X2, &x2 }, { CKA_NSS_JPAKE_X2S, &x2s }, { CKA_NSS_JPAKE_GX1, &gx1 }, { CKA_NSS_JPAKE_GX2, &gx2 }, @@ -251,7 +260,7 @@ jpake_Round2(HASH_HashType hashType, CK_NSS_JPAKERound2Params * params, pqg.base.data = NULL; x2s.data = NULL; crv = jpake_mapStatus(JPAKE_Round2(arena, &pqg.prime, &pqg.subPrime, - &gx1, &gx3, &gx4, &pqg.base, + &gx1, &gx3, &gx4, &pqg.base, &x2, &s, &x2s), CKR_MECHANISM_PARAM_INVALID); } @@ -281,10 +290,10 @@ jpake_Round2(HASH_HashType hashType, CK_NSS_JPAKERound2Params * params, } CK_RV -jpake_Final(HASH_HashType hashType, const CK_NSS_JPAKEFinalParams * param, - SFTKObject * sourceKey, SFTKObject * key) +jpake_Final(HASH_HashType hashType, const CK_NSS_JPAKEFinalParams *param, + SFTKObject *sourceKey, SFTKObject *key) { - PLArenaPool * arena; + PLArenaPool *arena; SECItem K; PQGParams pqg; CK_RV crv; @@ -294,7 +303,7 @@ jpake_Final(HASH_HashType hashType, const CK_NSS_JPAKEFinalParams * param, { CKA_NSS_JPAKE_SIGNERID, &signerID }, { CKA_PRIME, &pqg.prime }, { CKA_SUBPRIME, &pqg.subPrime }, - { CKA_NSS_JPAKE_X2, &x2 }, + { CKA_NSS_JPAKE_X2, &x2 }, { CKA_NSS_JPAKE_X2S, &x2s }, { CKA_NSS_JPAKE_GX1, &gx1 }, { CKA_NSS_JPAKE_GX2, &gx2 }, @@ -309,7 +318,7 @@ jpake_Final(HASH_HashType hashType, const CK_NSS_JPAKEFinalParams * param, arena = PORT_NewArena(NSS_SOFTOKEN_DEFAULT_CHUNKSIZE); if (arena == NULL) crv = CKR_HOST_MEMORY; - + /* TODO: verify key type CKK_NSS_JPAKE_ROUND2 */ crv = sftk_MultipleAttribute2SecItem(arena, sourceKey, sourceAttrs, diff --git a/nss/lib/softoken/legacydb/cdbhdl.h b/nss/lib/softoken/legacydb/cdbhdl.h index 018048b..e7243db 100644 --- a/nss/lib/softoken/legacydb/cdbhdl.h +++ b/nss/lib/softoken/legacydb/cdbhdl.h @@ -20,32 +20,32 @@ struct NSSLOWCERTCertDBHandleStr { DB *permCertDB; PZMonitor *dbMon; PRBool dbVerify; - PRInt32 ref; /* reference count */ + PRInt32 ref; /* reference count */ }; #ifdef DBM_USING_NSPR -#define NO_RDONLY PR_RDONLY -#define NO_RDWR PR_RDWR -#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) +#define NO_RDONLY PR_RDONLY +#define NO_RDWR PR_RDWR +#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) #else -#define NO_RDONLY O_RDONLY -#define NO_RDWR O_RDWR -#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) +#define NO_RDONLY O_RDONLY +#define NO_RDWR O_RDWR +#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) #endif -typedef DB * (*rdbfunc)(const char *appName, const char *prefix, - const char *type, int flags); +typedef DB *(*rdbfunc)(const char *appName, const char *prefix, + const char *type, int flags); typedef int (*rdbstatusfunc)(void); #define RDB_FAIL 1 #define RDB_RETRY 2 -DB * rdbopen(const char *appName, const char *prefix, - const char *type, int flags, int *status); +DB *rdbopen(const char *appName, const char *prefix, + const char *type, int flags, int *status); -DB *dbsopen (const char *dbname , int flags, int mode, DBTYPE type, - const void * appData); -SECStatus db_Copy(DB *dest,DB *src); +DB *dbsopen(const char *dbname, int flags, int mode, DBTYPE type, + const void *appData); +SECStatus db_Copy(DB *dest, DB *src); int db_InitComplete(DB *db); #endif diff --git a/nss/lib/softoken/legacydb/dbmshim.c b/nss/lib/softoken/legacydb/dbmshim.c index f299216..40728d5 100644 --- a/nss/lib/softoken/legacydb/dbmshim.c +++ b/nss/lib/softoken/legacydb/dbmshim.c @@ -28,16 +28,16 @@ * . . | | * Byte 37 . -+ -+ */ -#define DBS_BLOCK_SIZE (16*1024) /* 16 k */ +#define DBS_BLOCK_SIZE (16 * 1024) /* 16 k */ #define DBS_MAX_ENTRY_SIZE (DBS_BLOCK_SIZE - (2048)) /* 14 k */ -#define DBS_CACHE_SIZE DBS_BLOCK_SIZE*8 -#define ROUNDDIV(x,y) (x+(y-1))/y +#define DBS_CACHE_SIZE DBS_BLOCK_SIZE * 8 +#define ROUNDDIV(x, y) (x + (y - 1)) / y #define BLOB_HEAD_LEN 4 #define BLOB_LENGTH_START BLOB_HEAD_LEN #define BLOB_LENGTH_LEN 4 -#define BLOB_NAME_START BLOB_LENGTH_START+BLOB_LENGTH_LEN -#define BLOB_NAME_LEN 1+ROUNDDIV(SHA1_LENGTH,3)*4+1 -#define BLOB_BUF_LEN BLOB_HEAD_LEN+BLOB_LENGTH_LEN+BLOB_NAME_LEN +#define BLOB_NAME_START BLOB_LENGTH_START + BLOB_LENGTH_LEN +#define BLOB_NAME_LEN 1 + ROUNDDIV(SHA1_LENGTH, 3) * 4 + 1 +#define BLOB_BUF_LEN BLOB_HEAD_LEN + BLOB_LENGTH_LEN + BLOB_NAME_LEN /* a Shim data structure. This data structure has a db built into it. */ typedef struct DBSStr DBS; @@ -52,8 +52,6 @@ struct DBSStr { PRUint32 dbs_len; char staticBlobArea[BLOB_BUF_LEN]; }; - - /* * return true if the Datablock contains a blobtype @@ -63,9 +61,9 @@ dbs_IsBlob(DBT *blobData) { unsigned char *addr = (unsigned char *)blobData->data; if (blobData->size < BLOB_BUF_LEN) { - return PR_FALSE; + return PR_FALSE; } - return addr && ((certDBEntryType) addr[1] == certDBEntryTypeBlob); + return addr && ((certDBEntryType)addr[1] == certDBEntryTypeBlob); } /* @@ -88,13 +86,12 @@ dbs_getBlobSize(DBT *blobData) { unsigned char *addr = (unsigned char *)blobData->data; - return (PRUint32)(addr[BLOB_LENGTH_START+3] << 24) | - (addr[BLOB_LENGTH_START+2] << 16) | - (addr[BLOB_LENGTH_START+1] << 8) | - addr[BLOB_LENGTH_START]; + return (PRUint32)(addr[BLOB_LENGTH_START + 3] << 24) | + (addr[BLOB_LENGTH_START + 2] << 16) | + (addr[BLOB_LENGTH_START + 1] << 8) | + addr[BLOB_LENGTH_START]; } - /* We are using base64 data for the filename, but base64 data can include a * '/' which is interpreted as a path separator on many platforms. Replace it * with an inocuous '-'. We don't need to convert back because we never actual @@ -104,10 +101,11 @@ dbs_getBlobSize(DBT *blobData) static void dbs_replaceSlash(char *cp, int len) { - while (len--) { - if (*cp == '/') *cp = '-'; - cp++; - } + while (len--) { + if (*cp == '/') + *cp = '-'; + cp++; + } } /* @@ -115,33 +113,32 @@ dbs_replaceSlash(char *cp, int len) * NOTE: The data element is static data (keeping with the dbm model). */ static void -dbs_mkBlob(DBS *dbsp,const DBT *key, const DBT *data, DBT *blobData) +dbs_mkBlob(DBS *dbsp, const DBT *key, const DBT *data, DBT *blobData) { - unsigned char sha1_data[SHA1_LENGTH]; - char *b = dbsp->staticBlobArea; - PRUint32 length = data->size; - SECItem sha1Item; - - b[0] = CERT_DB_FILE_VERSION; /* certdb version number */ - b[1] = (char) certDBEntryTypeBlob; /* type */ - b[2] = 0; /* flags */ - b[3] = 0; /* reserved */ - b[BLOB_LENGTH_START] = length & 0xff; - b[BLOB_LENGTH_START+1] = (length >> 8) & 0xff; - b[BLOB_LENGTH_START+2] = (length >> 16) & 0xff; - b[BLOB_LENGTH_START+3] = (length >> 24) & 0xff; - sha1Item.data = sha1_data; - sha1Item.len = SHA1_LENGTH; - SHA1_HashBuf(sha1_data,key->data,key->size); - b[BLOB_NAME_START]='b'; /* Make sure we start with a alpha */ - NSSBase64_EncodeItem(NULL,&b[BLOB_NAME_START+1],BLOB_NAME_LEN-1,&sha1Item); - b[BLOB_BUF_LEN-1] = 0; - dbs_replaceSlash(&b[BLOB_NAME_START+1],BLOB_NAME_LEN-1); - blobData->data = b; - blobData->size = BLOB_BUF_LEN; - return; + unsigned char sha1_data[SHA1_LENGTH]; + char *b = dbsp->staticBlobArea; + PRUint32 length = data->size; + SECItem sha1Item; + + b[0] = CERT_DB_FILE_VERSION; /* certdb version number */ + b[1] = (char)certDBEntryTypeBlob; /* type */ + b[2] = 0; /* flags */ + b[3] = 0; /* reserved */ + b[BLOB_LENGTH_START] = length & 0xff; + b[BLOB_LENGTH_START + 1] = (length >> 8) & 0xff; + b[BLOB_LENGTH_START + 2] = (length >> 16) & 0xff; + b[BLOB_LENGTH_START + 3] = (length >> 24) & 0xff; + sha1Item.data = sha1_data; + sha1Item.len = SHA1_LENGTH; + SHA1_HashBuf(sha1_data, key->data, key->size); + b[BLOB_NAME_START] = 'b'; /* Make sure we start with a alpha */ + NSSBase64_EncodeItem(NULL, &b[BLOB_NAME_START + 1], BLOB_NAME_LEN - 1, &sha1Item); + b[BLOB_BUF_LEN - 1] = 0; + dbs_replaceSlash(&b[BLOB_NAME_START + 1], BLOB_NAME_LEN - 1); + blobData->data = b; + blobData->size = BLOB_BUF_LEN; + return; } - /* * construct a path to the actual blob. The string returned must be @@ -150,26 +147,26 @@ dbs_mkBlob(DBS *dbsp,const DBT *key, const DBT *data, DBT *blobData) * Note: this file does lots of consistancy checks on the DBT. The * routines that call this depend on these checks, so they don't worry * about them (success of this routine implies a good blobdata record). - */ + */ static char * -dbs_getBlobFilePath(char *blobdir,DBT *blobData) +dbs_getBlobFilePath(char *blobdir, DBT *blobData) { const char *name; if (blobdir == NULL) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; + PR_SetError(SEC_ERROR_BAD_DATABASE, 0); + return NULL; } if (!dbs_IsBlob(blobData)) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; + PR_SetError(SEC_ERROR_BAD_DATABASE, 0); + return NULL; } name = dbs_getBlobFileName(blobData); if (!name || *name == 0) { - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - return NULL; + PR_SetError(SEC_ERROR_BAD_DATABASE, 0); + return NULL; } - return PR_smprintf("%s" PATH_SEPARATOR "%s", blobdir, name); + return PR_smprintf("%s" PATH_SEPARATOR "%s", blobdir, name); } /* @@ -182,7 +179,7 @@ dbs_removeBlob(DBS *dbsp, DBT *blobData) file = dbs_getBlobFilePath(dbsp->blobdir, blobData); if (!file) { - return; + return; } PR_Delete(file); PR_smprintf_free(file); @@ -195,8 +192,8 @@ dbs_removeBlob(DBS *dbsp, DBT *blobData) static int dbs_DirMode(int mode) { - int x_bits = (mode >> 2) & 0111; - return mode | x_bits; + int x_bits = (mode >> 2) & 0111; + return mode | x_bits; } /* @@ -214,43 +211,42 @@ dbs_writeBlob(DBS *dbsp, int mode, DBT *blobData, const DBT *data) file = dbs_getBlobFilePath(dbsp->blobdir, blobData); if (!file) { - goto loser; + goto loser; } if (PR_Access(dbsp->blobdir, PR_ACCESS_EXISTS) != PR_SUCCESS) { - status = PR_MkDir(dbsp->blobdir,dbs_DirMode(mode)); - if (status != PR_SUCCESS) { - goto loser; - } + status = PR_MkDir(dbsp->blobdir, dbs_DirMode(mode)); + if (status != PR_SUCCESS) { + goto loser; + } } - filed = PR_OpenFile(file,PR_CREATE_FILE|PR_TRUNCATE|PR_WRONLY, mode); + filed = PR_OpenFile(file, PR_CREATE_FILE | PR_TRUNCATE | PR_WRONLY, mode); if (filed == NULL) { - error = PR_GetError(); - goto loser; + error = PR_GetError(); + goto loser; } - len = PR_Write(filed,data->data,data->size); + len = PR_Write(filed, data->data, data->size); error = PR_GetError(); PR_Close(filed); if (len < (int)data->size) { - goto loser; + goto loser; } PR_smprintf_free(file); return 0; loser: if (file) { - PR_Delete(file); - PR_smprintf_free(file); + PR_Delete(file); + PR_smprintf_free(file); } /* don't let close or delete reset the error */ - PR_SetError(error,0); + PR_SetError(error, 0); return -1; } - /* * we need to keep a address map in memory between calls to DBM. * remember what we have mapped can close it when we get another dbm - * call. + * call. * * NOTE: Not all platforms support mapped files. This code is designed to * detect this at runtime. If map files aren't supported the OS will indicate @@ -263,15 +259,15 @@ static void dbs_freemap(DBS *dbsp) { if (dbsp->dbs_mapfile) { - PR_MemUnmap(dbsp->dbs_addr,dbsp->dbs_len); - PR_CloseFileMap(dbsp->dbs_mapfile); - dbsp->dbs_mapfile = NULL; - dbsp->dbs_addr = NULL; - dbsp->dbs_len = 0; + PR_MemUnmap(dbsp->dbs_addr, dbsp->dbs_len); + PR_CloseFileMap(dbsp->dbs_mapfile); + dbsp->dbs_mapfile = NULL; + dbsp->dbs_addr = NULL; + dbsp->dbs_len = 0; } else if (dbsp->dbs_addr) { - PORT_Free(dbsp->dbs_addr); - dbsp->dbs_addr = NULL; - dbsp->dbs_len = 0; + PORT_Free(dbsp->dbs_addr); + dbsp->dbs_addr = NULL; + dbsp->dbs_len = 0; } return; } @@ -295,23 +291,22 @@ dbs_EmulateMap(PRFileDesc *filed, int len) addr = PORT_Alloc(len); if (addr == NULL) { - return NULL; + return NULL; } - dataRead = PR_Read(filed,addr,len); + dataRead = PR_Read(filed, addr, len); if (dataRead != len) { - PORT_Free(addr); - if (dataRead > 0) { - /* PR_Read didn't set an error, we need to */ - PR_SetError(SEC_ERROR_BAD_DATABASE,0); - } - return NULL; + PORT_Free(addr); + if (dataRead > 0) { + /* PR_Read didn't set an error, we need to */ + PR_SetError(SEC_ERROR_BAD_DATABASE, 0); + } + return NULL; } return addr; } - /* * pull a database record off the disk * data points to the blob record on input and the real record (if we could @@ -329,32 +324,33 @@ dbs_readBlob(DBS *dbsp, DBT *data) file = dbs_getBlobFilePath(dbsp->blobdir, data); if (!file) { - goto loser; + goto loser; } - filed = PR_OpenFile(file,PR_RDONLY,0); - PR_smprintf_free(file); file = NULL; + filed = PR_OpenFile(file, PR_RDONLY, 0); + PR_smprintf_free(file); + file = NULL; if (filed == NULL) { - goto loser; + goto loser; } len = dbs_getBlobSize(data); mapfile = PR_CreateFileMap(filed, len, PR_PROT_READONLY); if (mapfile == NULL) { - /* USE PR_GetError instead of PORT_GetError here - * because we are getting the error from PR_xxx - * function */ - if (PR_GetError() != PR_NOT_IMPLEMENTED_ERROR) { - goto loser; - } - addr = dbs_EmulateMap(filed, len); + /* USE PR_GetError instead of PORT_GetError here + * because we are getting the error from PR_xxx + * function */ + if (PR_GetError() != PR_NOT_IMPLEMENTED_ERROR) { + goto loser; + } + addr = dbs_EmulateMap(filed, len); } else { - addr = PR_MemMap(mapfile, 0, len); + addr = PR_MemMap(mapfile, 0, len); } if (addr == NULL) { - goto loser; + goto loser; } PR_Close(filed); - dbs_setmap(dbsp,mapfile,addr,len); + dbs_setmap(dbsp, mapfile, addr, len); data->data = addr; data->size = len; @@ -364,12 +360,12 @@ loser: /* preserve the error code */ error = PR_GetError(); if (mapfile) { - PR_CloseFileMap(mapfile); + PR_CloseFileMap(mapfile); } if (filed) { - PR_Close(filed); + PR_Close(filed); } - PR_SetError(error,0); + PR_SetError(error, 0); return -1; } @@ -382,16 +378,15 @@ dbs_get(const DB *dbs, const DBT *key, DBT *data, unsigned int flags) int ret; DBS *dbsp = (DBS *)dbs; DB *db = (DB *)dbs->internal; - dbs_freemap(dbsp); - - ret = (* db->get)(db, key, data, flags); + + ret = (*db->get)(db, key, data, flags); if ((ret == 0) && dbs_IsBlob(data)) { - ret = dbs_readBlob(dbsp,data); + ret = dbs_readBlob(dbsp, data); } - return(ret); + return (ret); } static int @@ -406,30 +401,30 @@ dbs_put(const DB *dbs, DBT *key, const DBT *data, unsigned int flags) /* If the db is readonly, just pass the data down to rdb and let it fail */ if (!dbsp->readOnly) { - DBT oldData; - int ret1; + DBT oldData; + int ret1; - /* make sure the current record is deleted if it's a blob */ - ret1 = (*db->get)(db,key,&oldData,0); + /* make sure the current record is deleted if it's a blob */ + ret1 = (*db->get)(db, key, &oldData, 0); if ((ret1 == 0) && flags == R_NOOVERWRITE) { - /* let DBM return the error to maintain consistancy */ - return (* db->put)(db, key, data, flags); - } - if ((ret1 == 0) && dbs_IsBlob(&oldData)) { - dbs_removeBlob(dbsp, &oldData); - } - - if (data->size > DBS_MAX_ENTRY_SIZE) { - dbs_mkBlob(dbsp,key,data,&blob); - ret = dbs_writeBlob(dbsp, dbsp->mode, &blob, data); - data = &blob; - } + /* let DBM return the error to maintain consistancy */ + return (*db->put)(db, key, data, flags); + } + if ((ret1 == 0) && dbs_IsBlob(&oldData)) { + dbs_removeBlob(dbsp, &oldData); + } + + if (data->size > DBS_MAX_ENTRY_SIZE) { + dbs_mkBlob(dbsp, key, data, &blob); + ret = dbs_writeBlob(dbsp, dbsp->mode, &blob, data); + data = &blob; + } } if (ret == 0) { - ret = (* db->put)(db, key, data, flags); + ret = (*db->put)(db, key, data, flags); } - return(ret); + return (ret); } static int @@ -440,7 +435,7 @@ dbs_sync(const DB *dbs, unsigned int flags) dbs_freemap(dbsp); - return (* db->sync)(db, flags); + return (*db->sync)(db, flags); } static int @@ -453,14 +448,14 @@ dbs_del(const DB *dbs, const DBT *key, unsigned int flags) dbs_freemap(dbsp); if (!dbsp->readOnly) { - DBT oldData; - ret = (*db->get)(db,key,&oldData,0); - if ((ret == 0) && dbs_IsBlob(&oldData)) { - dbs_removeBlob(dbsp,&oldData); - } + DBT oldData; + ret = (*db->get)(db, key, &oldData, 0); + if ((ret == 0) && dbs_IsBlob(&oldData)) { + dbs_removeBlob(dbsp, &oldData); + } } - return (* db->del)(db, key, flags); + return (*db->del)(db, key, flags); } static int @@ -469,16 +464,16 @@ dbs_seq(const DB *dbs, DBT *key, DBT *data, unsigned int flags) int ret; DBS *dbsp = (DBS *)dbs; DB *db = (DB *)dbs->internal; - + dbs_freemap(dbsp); - - ret = (* db->seq)(db, key, data, flags); + + ret = (*db->seq)(db, key, data, flags); if ((ret == 0) && dbs_IsBlob(data)) { - /* don't return a blob read as an error so traversals keep going */ - (void) dbs_readBlob(dbsp,data); + /* don't return a blob read as an error so traversals keep going */ + (void)dbs_readBlob(dbsp, data); } - return(ret); + return (ret); } static int @@ -489,7 +484,7 @@ dbs_close(DB *dbs) int ret; dbs_freemap(dbsp); - ret = (* db->close)(db); + ret = (*db->close)(db); PORT_Free(dbsp->blobdir); PORT_Free(dbsp); return ret; @@ -500,13 +495,13 @@ dbs_fd(const DB *dbs) { DB *db = (DB *)dbs->internal; - return (* db->fd)(db); + return (*db->fd)(db); } /* * the naming convention we use is * change the .xxx into .dir. (for nss it's always .db); - * if no .extension exists or is equal to .dir, add a .dir + * if no .extension exists or is equal to .dir, add a .dir * the returned data must be freed. */ #define DIRSUFFIX ".dir" @@ -522,35 +517,35 @@ dbs_mkBlobDirName(const char *dbname) * or the end of the string. NOTE: Windows should check for both separators * here. For now this is safe because we know NSS always uses a '.' */ - for (cp = &dbname[dbname_len]; - (cp > dbname) && (*cp != '.') && (*cp != *PATH_SEPARATOR) ; - cp--) - /* Empty */ ; + for (cp = &dbname[dbname_len]; + (cp > dbname) && (*cp != '.') && (*cp != *PATH_SEPARATOR); + cp--) + /* Empty */; if (*cp == '.') { - dbname_end = cp - dbname; - if (PORT_Strcmp(cp,DIRSUFFIX) == 0) { - dbname_end = dbname_len; - } + dbname_end = cp - dbname; + if (PORT_Strcmp(cp, DIRSUFFIX) == 0) { + dbname_end = dbname_len; + } } - blobDir = PORT_ZAlloc(dbname_end+sizeof(DIRSUFFIX)); + blobDir = PORT_ZAlloc(dbname_end + sizeof(DIRSUFFIX)); if (blobDir == NULL) { - return NULL; + return NULL; } - PORT_Memcpy(blobDir,dbname,dbname_end); - PORT_Memcpy(&blobDir[dbname_end],DIRSUFFIX,sizeof(DIRSUFFIX)); + PORT_Memcpy(blobDir, dbname, dbname_end); + PORT_Memcpy(&blobDir[dbname_end], DIRSUFFIX, sizeof(DIRSUFFIX)); return blobDir; } #define DBM_DEFAULT 0 static const HASHINFO dbs_hashInfo = { - DBS_BLOCK_SIZE, /* bucket size, must be greater than = to - * or maximum entry size (+ header) - * we allow before blobing */ - DBM_DEFAULT, /* Fill Factor */ - DBM_DEFAULT, /* number of elements */ - DBS_CACHE_SIZE, /* cache size */ - DBM_DEFAULT, /* hash function */ - DBM_DEFAULT, /* byte order */ + DBS_BLOCK_SIZE, /* bucket size, must be greater than = to + * or maximum entry size (+ header) + * we allow before blobing */ + DBM_DEFAULT, /* Fill Factor */ + DBM_DEFAULT, /* number of elements */ + DBS_CACHE_SIZE, /* cache size */ + DBM_DEFAULT, /* hash function */ + DBM_DEFAULT, /* byte order */ }; /* @@ -559,9 +554,9 @@ static const HASHINFO dbs_hashInfo = { */ DB * dbsopen(const char *dbname, int flags, int mode, DBTYPE type, - const void *userData) + const void *userData) { - DB *db = NULL,*dbs = NULL; + DB *db = NULL, *dbs = NULL; DBS *dbsp = NULL; /* NOTE: we are overriding userData with dbs_hashInfo. since all known @@ -569,13 +564,13 @@ dbsopen(const char *dbname, int flags, int mode, DBTYPE type, dbsp = (DBS *)PORT_ZAlloc(sizeof(DBS)); if (!dbsp) { - return NULL; + return NULL; } dbs = &dbsp->db; - dbsp->blobdir=dbs_mkBlobDirName(dbname); + dbsp->blobdir = dbs_mkBlobDirName(dbname); if (dbsp->blobdir == NULL) { - goto loser; + goto loser; } dbsp->mode = mode; dbsp->readOnly = (PRBool)(flags == NO_RDONLY); @@ -586,9 +581,9 @@ dbsopen(const char *dbname, int flags, int mode, DBTYPE type, /* the real dbm call */ db = dbopen(dbname, flags, mode, type, &dbs_hashInfo); if (db == NULL) { - goto loser; + goto loser; } - dbs->internal = (void *) db; + dbs->internal = (void *)db; dbs->type = type; dbs->close = dbs_close; dbs->get = dbs_get; @@ -601,13 +596,11 @@ dbsopen(const char *dbname, int flags, int mode, DBTYPE type, return dbs; loser: if (db) { - (*db->close)(db); + (*db->close)(db); } - if (dbsp) { - if (dbsp->blobdir) { - PORT_Free(dbsp->blobdir); - } - PORT_Free(dbsp); + if (dbsp->blobdir) { + PORT_Free(dbsp->blobdir); } + PORT_Free(dbsp); return NULL; } diff --git a/nss/lib/softoken/legacydb/keydb.c b/nss/lib/softoken/legacydb/keydb.c index d54f10c..178e333 100644 --- a/nss/lib/softoken/legacydb/keydb.c +++ b/nss/lib/softoken/legacydb/keydb.c @@ -20,105 +20,104 @@ */ #define SALT_STRING "global-salt" #define VERSION_STRING "Version" -#define KEYDB_PW_CHECK_STRING "password-check" -#define KEYDB_PW_CHECK_LEN 14 -#define KEYDB_FAKE_PW_CHECK_STRING "fake-password-check" -#define KEYDB_FAKE_PW_CHECK_LEN 19 +#define KEYDB_PW_CHECK_STRING "password-check" +#define KEYDB_PW_CHECK_LEN 14 +#define KEYDB_FAKE_PW_CHECK_STRING "fake-password-check" +#define KEYDB_FAKE_PW_CHECK_LEN 19 /* Size of the global salt for key database */ -#define SALT_LENGTH 16 +#define SALT_LENGTH 16 SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYEncryptedPrivateKeyInfo) }, + 0, NULL, sizeof(NSSLOWKEYEncryptedPrivateKeyInfo) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(NSSLOWKEYEncryptedPrivateKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYEncryptedPrivateKeyInfo,encryptedData) }, + offsetof(NSSLOWKEYEncryptedPrivateKeyInfo, encryptedData) }, { 0 } }; const SEC_ASN1Template nsslowkey_PointerToEncryptedPrivateKeyInfoTemplate[] = { - { SEC_ASN1_POINTER, 0, nsslowkey_EncryptedPrivateKeyInfoTemplate } + { SEC_ASN1_POINTER, 0, nsslowkey_EncryptedPrivateKeyInfoTemplate } }; - /* ====== Default key databse encryption algorithm ====== */ static void sec_destroy_dbkey(NSSLOWKEYDBKey *dbkey) { - if ( dbkey && dbkey->arena ) { - PORT_FreeArena(dbkey->arena, PR_FALSE); + if (dbkey && dbkey->arena) { + PORT_FreeArena(dbkey->arena, PR_FALSE); } } static void free_dbt(DBT *dbt) { - if ( dbt ) { - PORT_Free(dbt->data); - PORT_Free(dbt); + if (dbt) { + PORT_Free(dbt->data); + PORT_Free(dbt); } - + return; } -static int keydb_Get(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, - unsigned int flags); -static int keydb_Put(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, - unsigned int flags); +static int keydb_Get(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, + unsigned int flags); +static int keydb_Put(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, + unsigned int flags); static int keydb_Sync(NSSLOWKEYDBHandle *db, unsigned int flags); static int keydb_Del(NSSLOWKEYDBHandle *db, DBT *key, unsigned int flags); -static int keydb_Seq(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, - unsigned int flags); +static int keydb_Seq(NSSLOWKEYDBHandle *db, DBT *key, DBT *data, + unsigned int flags); static void keydb_Close(NSSLOWKEYDBHandle *db); /* * format of key database entries for version 3 of database: - * byte offset field - * ----------- ----- - * 0 version - * 1 salt-len - * 2 nn-len - * 3.. salt-data - * ... nickname - * ... encrypted-key-data + * byte offset field + * ----------- ----- + * 0 version + * 1 salt-len + * 2 nn-len + * 3.. salt-data + * ... nickname + * ... encrypted-key-data */ static DBT * -encode_dbkey(NSSLOWKEYDBKey *dbkey,unsigned char version) +encode_dbkey(NSSLOWKEYDBKey *dbkey, unsigned char version) { DBT *bufitem = NULL; unsigned char *buf; int nnlen; char *nn; - + bufitem = (DBT *)PORT_ZAlloc(sizeof(DBT)); - if ( bufitem == NULL ) { - goto loser; + if (bufitem == NULL) { + goto loser; } - - if ( dbkey->nickname ) { - nn = dbkey->nickname; - nnlen = PORT_Strlen(nn) + 1; + + if (dbkey->nickname) { + nn = dbkey->nickname; + nnlen = PORT_Strlen(nn) + 1; } else { - nn = ""; - nnlen = 1; + nn = ""; + nnlen = 1; } - + /* compute the length of the record */ /* 1 + 1 + 1 == version number header + salt length + nn len */ bufitem->size = dbkey->salt.len + nnlen + dbkey->derPK.len + 1 + 1 + 1; - + bufitem->data = (void *)PORT_ZAlloc(bufitem->size); - if ( bufitem->data == NULL ) { - goto loser; + if (bufitem->data == NULL) { + goto loser; } buf = (unsigned char *)bufitem->data; - + /* set version number */ buf[0] = version; @@ -131,23 +130,25 @@ encode_dbkey(NSSLOWKEYDBKey *dbkey,unsigned char version) buf[2] = nnlen; /* copy salt */ - PORT_Memcpy(&buf[3], dbkey->salt.data, dbkey->salt.len); + if (dbkey->salt.len > 0) { + PORT_Memcpy(&buf[3], dbkey->salt.data, dbkey->salt.len); + } /* copy nickname */ PORT_Memcpy(&buf[3 + dbkey->salt.len], nn, nnlen); /* copy encrypted key */ PORT_Memcpy(&buf[3 + dbkey->salt.len + nnlen], dbkey->derPK.data, - dbkey->derPK.len); - - return(bufitem); - + dbkey->derPK.len); + + return (bufitem); + loser: - if ( bufitem ) { - free_dbt(bufitem); + if (bufitem) { + free_dbt(bufitem); } - - return(NULL); + + return (NULL); } static NSSLOWKEYDBKey * @@ -160,69 +161,69 @@ decode_dbkey(DBT *bufitem, int expectedVersion) int keyoff; int nnlen; int saltoff; - + buf = (unsigned char *)bufitem->data; version = buf[0]; - - if ( version != expectedVersion ) { - goto loser; + + if (version != expectedVersion) { + goto loser; } - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } - + dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey)); - if ( dbkey == NULL ) { - goto loser; + if (dbkey == NULL) { + goto loser; } dbkey->arena = arena; dbkey->salt.data = NULL; dbkey->derPK.data = NULL; - + dbkey->salt.len = buf[1]; dbkey->salt.data = (unsigned char *)PORT_ArenaZAlloc(arena, dbkey->salt.len); - if ( dbkey->salt.data == NULL ) { - goto loser; + if (dbkey->salt.data == NULL) { + goto loser; } saltoff = 2; keyoff = 2 + dbkey->salt.len; - - if ( expectedVersion >= 3 ) { - nnlen = buf[2]; - if ( nnlen ) { - dbkey->nickname = (char *)PORT_ArenaZAlloc(arena, nnlen + 1); - if ( dbkey->nickname ) { - PORT_Memcpy(dbkey->nickname, &buf[keyoff+1], nnlen); - } - } - keyoff += ( nnlen + 1 ); - saltoff = 3; + + if (expectedVersion >= 3) { + nnlen = buf[2]; + if (nnlen) { + dbkey->nickname = (char *)PORT_ArenaZAlloc(arena, nnlen + 1); + if (dbkey->nickname) { + PORT_Memcpy(dbkey->nickname, &buf[keyoff + 1], nnlen); + } + } + keyoff += (nnlen + 1); + saltoff = 3; } PORT_Memcpy(dbkey->salt.data, &buf[saltoff], dbkey->salt.len); - + dbkey->derPK.len = bufitem->size - keyoff; - dbkey->derPK.data = (unsigned char *)PORT_ArenaZAlloc(arena,dbkey->derPK.len); - if ( dbkey->derPK.data == NULL ) { - goto loser; + dbkey->derPK.data = (unsigned char *)PORT_ArenaZAlloc(arena, dbkey->derPK.len); + if (dbkey->derPK.data == NULL) { + goto loser; } - + PORT_Memcpy(dbkey->derPK.data, &buf[keyoff], dbkey->derPK.len); - - return(dbkey); - + + return (dbkey); + loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } static NSSLOWKEYDBKey * @@ -231,19 +232,19 @@ get_dbkey(NSSLOWKEYDBHandle *handle, DBT *index) NSSLOWKEYDBKey *dbkey; DBT entry; int ret; - + /* get it from the database */ ret = keydb_Get(handle, index, &entry, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; + if (ret) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return NULL; } /* set up dbkey struct */ dbkey = decode_dbkey(&entry, handle->version); - return(dbkey); + return (dbkey); } static SECStatus @@ -251,44 +252,44 @@ put_dbkey(NSSLOWKEYDBHandle *handle, DBT *index, NSSLOWKEYDBKey *dbkey, PRBool u { DBT *keydata = NULL; int status; - + keydata = encode_dbkey(dbkey, handle->version); - if ( keydata == NULL ) { - goto loser; + if (keydata == NULL) { + goto loser; } - + /* put it in the database */ - if ( update ) { - status = keydb_Put(handle, index, keydata, 0); + if (update) { + status = keydb_Put(handle, index, keydata, 0); } else { - status = keydb_Put(handle, index, keydata, R_NOOVERWRITE); + status = keydb_Put(handle, index, keydata, R_NOOVERWRITE); } - - if ( status ) { - goto loser; + + if (status) { + goto loser; } /* sync the database */ status = keydb_Sync(handle, 0); - if ( status ) { - goto loser; + if (status) { + goto loser; } free_dbt(keydata); - return(SECSuccess); + return (SECSuccess); loser: - if ( keydata ) { - free_dbt(keydata); + if (keydata) { + free_dbt(keydata); } - - return(SECFailure); + + return (SECFailure); } SECStatus -nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, - SECStatus (* keyfunc)(DBT *k, DBT *d, void *pdata), - void *udata ) +nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, + SECStatus (*keyfunc)(DBT *k, DBT *d, void *pdata), + void *udata) { DBT data; DBT key; @@ -296,39 +297,39 @@ nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, int ret; if (handle == NULL) { - return(SECFailure); + return (SECFailure); } ret = keydb_Seq(handle, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + if (ret) { + return (SECFailure); } - + do { - /* skip version record */ - if ( data.size > 1 ) { - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - - /* skip password check */ - if ( key.size == KEYDB_PW_CHECK_LEN ) { - if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, - KEYDB_PW_CHECK_LEN) == 0 ) { - continue; - } - } - - status = (* keyfunc)(&key, &data, udata); - if (status != SECSuccess) { - return(status); - } - } - } while ( keydb_Seq(handle, &key, &data, R_NEXT) == 0 ); - - return(SECSuccess); + /* skip version record */ + if (data.size > 1) { + if (key.size == (sizeof(SALT_STRING) - 1)) { + if (PORT_Memcmp(key.data, SALT_STRING, key.size) == 0) { + continue; + } + } + + /* skip password check */ + if (key.size == KEYDB_PW_CHECK_LEN) { + if (PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, + KEYDB_PW_CHECK_LEN) == 0) { + continue; + } + } + + status = (*keyfunc)(&key, &data, udata); + if (status != SECSuccess) { + return (status); + } + } + } while (keydb_Seq(handle, &key, &data, R_NEXT) == 0); + + return (SECSuccess); } #ifdef notdef @@ -348,19 +349,19 @@ sec_add_key_to_list(DBT *key, DBT *data, void *arg) keyList *keylist; keyNode *node; void *keydata; - + keylist = (keyList *)arg; /* allocate the node struct */ - node = (keyNode*)PORT_ArenaZAlloc(keylist->arena, sizeof(keyNode)); - if ( node == NULL ) { - return(SECFailure); + node = (keyNode *)PORT_ArenaZAlloc(keylist->arena, sizeof(keyNode)); + if (node == NULL) { + return (SECFailure); } - + /* allocate room for key data */ keydata = PORT_ArenaZAlloc(keylist->arena, key->size); - if ( keydata == NULL ) { - return(SECFailure); + if (keydata == NULL) { + return (SECFailure); } /* link node into list */ @@ -371,8 +372,8 @@ sec_add_key_to_list(DBT *key, DBT *data, void *arg) PORT_Memcpy(keydata, key->data, key->size); node->key.size = key->size; node->key.data = keydata; - - return(SECSuccess); + + return (SECSuccess); } #endif @@ -380,22 +381,22 @@ static SECItem * decodeKeyDBGlobalSalt(DBT *saltData) { SECItem *saltitem; - + saltitem = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if ( saltitem == NULL ) { - return(NULL); + if (saltitem == NULL) { + return (NULL); } - + saltitem->data = (unsigned char *)PORT_ZAlloc(saltData->size); - if ( saltitem->data == NULL ) { - PORT_Free(saltitem); - return(NULL); + if (saltitem->data == NULL) { + PORT_Free(saltitem); + return (NULL); } - + saltitem->len = saltData->size; PORT_Memcpy(saltitem->data, saltData->data, saltitem->len); - - return(saltitem); + + return (saltitem); } static SECItem * @@ -404,16 +405,16 @@ GetKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle) DBT saltKey; DBT saltData; int ret; - + saltKey.data = SALT_STRING; saltKey.size = sizeof(SALT_STRING) - 1; ret = keydb_Get(handle, &saltKey, &saltData, 0); - if ( ret ) { - return(NULL); + if (ret) { + return (NULL); } - return(decodeKeyDBGlobalSalt(&saltData)); + return (decodeKeyDBGlobalSalt(&saltData)); } static SECStatus @@ -422,7 +423,7 @@ StoreKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle, SECItem *salt) DBT saltKey; DBT saltData; int status; - + saltKey.data = SALT_STRING; saltKey.size = sizeof(SALT_STRING) - 1; @@ -431,11 +432,11 @@ StoreKeyDBGlobalSalt(NSSLOWKEYDBHandle *handle, SECItem *salt) /* put global salt into the database now */ status = keydb_Put(handle, &saltKey, &saltData, 0); - if ( status ) { - return(SECFailure); + if (status) { + return (SECFailure); } - return(SECSuccess); + return (SECSuccess); } static SECStatus @@ -445,24 +446,23 @@ makeGlobalVersion(NSSLOWKEYDBHandle *handle) DBT versionData; DBT versionKey; int status; - + version = NSSLOWKEY_DB_FILE_VERSION; versionData.data = &version; versionData.size = 1; versionKey.data = VERSION_STRING; - versionKey.size = sizeof(VERSION_STRING)-1; - + versionKey.size = sizeof(VERSION_STRING) - 1; + /* put version string into the database now */ status = keydb_Put(handle, &versionKey, &versionData, 0); - if ( status ) { - return(SECFailure); + if (status) { + return (SECFailure); } handle->version = version; - return(SECSuccess); + return (SECSuccess); } - static SECStatus makeGlobalSalt(NSSLOWKEYDBHandle *handle) { @@ -470,7 +470,7 @@ makeGlobalSalt(NSSLOWKEYDBHandle *handle) DBT saltData; unsigned char saltbuf[16]; int status; - + saltKey.data = SALT_STRING; saltKey.size = sizeof(SALT_STRING) - 1; @@ -480,16 +480,16 @@ makeGlobalSalt(NSSLOWKEYDBHandle *handle) /* put global salt into the database now */ status = keydb_Put(handle, &saltKey, &saltData, 0); - if ( status ) { - return(SECFailure); + if (status) { + return (SECFailure); } - return(SECSuccess); + return (SECSuccess); } static SECStatus encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg, - SECItem *encCheck); + SECItem *encCheck); static unsigned char nsslowkey_version(NSSLOWKEYDBHandle *handle) @@ -498,24 +498,24 @@ nsslowkey_version(NSSLOWKEYDBHandle *handle) DBT versionData; int ret; versionKey.data = VERSION_STRING; - versionKey.size = sizeof(VERSION_STRING)-1; + versionKey.size = sizeof(VERSION_STRING) - 1; if (handle->db == NULL) { - return 255; + return 255; } /* lookup version string in database */ - ret = keydb_Get( handle, &versionKey, &versionData, 0 ); + ret = keydb_Get(handle, &versionKey, &versionData, 0); /* error accessing the database */ - if ( ret < 0 ) { - return 255; + if (ret < 0) { + return 255; } - if ( ret >= 1 ) { - return 0; + if (ret >= 1) { + return 0; } - return *( (unsigned char *)versionData.data); + return *((unsigned char *)versionData.data); } static PRBool @@ -527,49 +527,48 @@ seckey_HasAServerKey(NSSLOWKEYDBHandle *handle) PRBool found = PR_FALSE; ret = keydb_Seq(handle, &key, &data, R_FIRST); - if ( ret ) { - return PR_FALSE; + if (ret) { + return PR_FALSE; } - + do { - /* skip version record */ - if ( data.size > 1 ) { - /* skip salt */ - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - /* skip pw check entry */ - if ( key.size == KEYDB_PW_CHECK_LEN ) { - if ( PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, - KEYDB_PW_CHECK_LEN) == 0 ) { - continue; - } - } - - /* keys stored by nickname will have 0 as the last byte of the - * db key. Other keys must be stored by modulus. We will not - * update those because they are left over from a keygen that - * never resulted in a cert. - */ - if ( ((unsigned char *)key.data)[key.size-1] != 0 ) { - continue; - } - - if (PORT_Strcmp(key.data,"Server-Key") == 0) { - found = PR_TRUE; - break; - } - - } - } while ( keydb_Seq(handle, &key, &data, R_NEXT) == 0 ); + /* skip version record */ + if (data.size > 1) { + /* skip salt */ + if (key.size == (sizeof(SALT_STRING) - 1)) { + if (PORT_Memcmp(key.data, SALT_STRING, key.size) == 0) { + continue; + } + } + /* skip pw check entry */ + if (key.size == KEYDB_PW_CHECK_LEN) { + if (PORT_Memcmp(key.data, KEYDB_PW_CHECK_STRING, + KEYDB_PW_CHECK_LEN) == 0) { + continue; + } + } + + /* keys stored by nickname will have 0 as the last byte of the + * db key. Other keys must be stored by modulus. We will not + * update those because they are left over from a keygen that + * never resulted in a cert. + */ + if (((unsigned char *)key.data)[key.size - 1] != 0) { + continue; + } + + if (PORT_Strcmp(key.data, "Server-Key") == 0) { + found = PR_TRUE; + break; + } + } + } while (keydb_Seq(handle, &key, &data, R_NEXT) == 0); return found; } /* forward declare local create function */ -static NSSLOWKEYDBHandle * nsslowkey_NewHandle(DB *dbHandle); +static NSSLOWKEYDBHandle *nsslowkey_NewHandle(DB *dbHandle); /* * currently updates key database from v2 to v3 @@ -591,15 +590,15 @@ nsslowkey_UpdateKeyDBPass1(NSSLOWKEYDBHandle *handle) int ret; SECItem checkitem; - if ( handle->updatedb == NULL ) { - return SECSuccess; + if (handle->updatedb == NULL) { + return SECSuccess; } - /* create a full DB Handle for our update so we + /* create a full DB Handle for our update so we * can use the correct locks for the db primatives */ update = nsslowkey_NewHandle(handle->updatedb); - if ( update == NULL) { - return SECSuccess; + if (update == NULL) { + return SECSuccess; } /* update has now inherited the database handle */ @@ -610,22 +609,22 @@ nsslowkey_UpdateKeyDBPass1(NSSLOWKEYDBHandle *handle) */ version = nsslowkey_version(update); if (version != 2) { - goto done; + goto done; } saltKey.data = SALT_STRING; saltKey.size = sizeof(SALT_STRING) - 1; ret = keydb_Get(update, &saltKey, &saltData, 0); - if ( ret ) { - /* no salt in old db, so it is corrupted */ - goto done; + if (ret) { + /* no salt in old db, so it is corrupted */ + goto done; } oldSalt = decodeKeyDBGlobalSalt(&saltData); - if ( oldSalt == NULL ) { - /* bad salt in old db, so it is corrupted */ - goto done; + if (oldSalt == NULL) { + /* bad salt in old db, so it is corrupted */ + goto done; } /* @@ -633,117 +632,116 @@ nsslowkey_UpdateKeyDBPass1(NSSLOWKEYDBHandle *handle) */ checkKey.data = KEYDB_PW_CHECK_STRING; checkKey.size = KEYDB_PW_CHECK_LEN; - - ret = keydb_Get(update, &checkKey, &checkData, 0 ); + + ret = keydb_Get(update, &checkKey, &checkData, 0); if (ret) { - /* - * if we have a key, but no KEYDB_PW_CHECK_STRING, then this must - * be an old server database, and it does have a password associated - * with it. Put a fake entry in so we can identify this db when we do - * get the password for it. - */ - if (seckey_HasAServerKey(update)) { - DBT fcheckKey; - DBT fcheckData; - - /* - * include a fake string - */ - fcheckKey.data = KEYDB_FAKE_PW_CHECK_STRING; - fcheckKey.size = KEYDB_FAKE_PW_CHECK_LEN; - fcheckData.data = "1"; - fcheckData.size = 1; - /* put global salt into the new database now */ - ret = keydb_Put( handle, &saltKey, &saltData, 0); - if ( ret ) { - goto done; - } - ret = keydb_Put( handle, &fcheckKey, &fcheckData, 0); - if ( ret ) { - goto done; - } - } else { - goto done; - } + /* + * if we have a key, but no KEYDB_PW_CHECK_STRING, then this must + * be an old server database, and it does have a password associated + * with it. Put a fake entry in so we can identify this db when we do + * get the password for it. + */ + if (seckey_HasAServerKey(update)) { + DBT fcheckKey; + DBT fcheckData; + + /* + * include a fake string + */ + fcheckKey.data = KEYDB_FAKE_PW_CHECK_STRING; + fcheckKey.size = KEYDB_FAKE_PW_CHECK_LEN; + fcheckData.data = "1"; + fcheckData.size = 1; + /* put global salt into the new database now */ + ret = keydb_Put(handle, &saltKey, &saltData, 0); + if (ret) { + goto done; + } + ret = keydb_Put(handle, &fcheckKey, &fcheckData, 0); + if (ret) { + goto done; + } + } else { + goto done; + } } else { - /* put global salt into the new database now */ - ret = keydb_Put( handle, &saltKey, &saltData, 0); - if ( ret ) { - goto done; - } - - dbkey = decode_dbkey(&checkData, 2); - if ( dbkey == NULL ) { - goto done; - } - checkitem = dbkey->derPK; - dbkey->derPK.data = NULL; - - /* format the new pw check entry */ - rv = encodePWCheckEntry(NULL, &dbkey->derPK, SEC_OID_RC4, &checkitem); - if ( rv != SECSuccess ) { - goto done; - } - - rv = put_dbkey(handle, &checkKey, dbkey, PR_TRUE); - if ( rv != SECSuccess ) { - goto done; - } - - /* free the dbkey */ - sec_destroy_dbkey(dbkey); - dbkey = NULL; - } - - + /* put global salt into the new database now */ + ret = keydb_Put(handle, &saltKey, &saltData, 0); + if (ret) { + goto done; + } + + dbkey = decode_dbkey(&checkData, 2); + if (dbkey == NULL) { + goto done; + } + checkitem = dbkey->derPK; + dbkey->derPK.data = NULL; + + /* format the new pw check entry */ + rv = encodePWCheckEntry(NULL, &dbkey->derPK, SEC_OID_RC4, &checkitem); + if (rv != SECSuccess) { + goto done; + } + + rv = put_dbkey(handle, &checkKey, dbkey, PR_TRUE); + if (rv != SECSuccess) { + goto done; + } + + /* free the dbkey */ + sec_destroy_dbkey(dbkey); + dbkey = NULL; + } + /* now traverse the database */ ret = keydb_Seq(update, &key, &data, R_FIRST); - if ( ret ) { - goto done; + if (ret) { + goto done; } - + do { - /* skip version record */ - if ( data.size > 1 ) { - /* skip salt */ - if ( key.size == ( sizeof(SALT_STRING) - 1 ) ) { - if ( PORT_Memcmp(key.data, SALT_STRING, key.size) == 0 ) { - continue; - } - } - /* skip pw check entry */ - if ( key.size == checkKey.size ) { - if ( PORT_Memcmp(key.data, checkKey.data, key.size) == 0 ) { - continue; - } - } - - /* keys stored by nickname will have 0 as the last byte of the - * db key. Other keys must be stored by modulus. We will not - * update those because they are left over from a keygen that - * never resulted in a cert. - */ - if ( ((unsigned char *)key.data)[key.size-1] != 0 ) { - continue; - } - - dbkey = decode_dbkey(&data, 2); - if ( dbkey == NULL ) { - continue; - } - - /* This puts the key into the new database with the same - * index (nickname) that it had before. The second pass - * of the update will have the password. It will decrypt - * and re-encrypt the entries using a new algorithm. - */ - dbkey->nickname = (char *)key.data; - rv = put_dbkey(handle, &key, dbkey, PR_FALSE); - dbkey->nickname = NULL; - - sec_destroy_dbkey(dbkey); - } - } while ( keydb_Seq(update, &key, &data, R_NEXT) == 0 ); + /* skip version record */ + if (data.size > 1) { + /* skip salt */ + if (key.size == (sizeof(SALT_STRING) - 1)) { + if (PORT_Memcmp(key.data, SALT_STRING, key.size) == 0) { + continue; + } + } + /* skip pw check entry */ + if (key.size == checkKey.size) { + if (PORT_Memcmp(key.data, checkKey.data, key.size) == 0) { + continue; + } + } + + /* keys stored by nickname will have 0 as the last byte of the + * db key. Other keys must be stored by modulus. We will not + * update those because they are left over from a keygen that + * never resulted in a cert. + */ + if (((unsigned char *)key.data)[key.size - 1] != 0) { + continue; + } + + dbkey = decode_dbkey(&data, 2); + if (dbkey == NULL) { + continue; + } + + /* This puts the key into the new database with the same + * index (nickname) that it had before. The second pass + * of the update will have the password. It will decrypt + * and re-encrypt the entries using a new algorithm. + */ + dbkey->nickname = (char *)key.data; + rv = put_dbkey(handle, &key, dbkey, PR_FALSE); + dbkey->nickname = NULL; + + sec_destroy_dbkey(dbkey); + } + } while (keydb_Seq(update, &key, &data, R_NEXT) == 0); dbkey = NULL; @@ -752,21 +750,21 @@ done: ret = keydb_Sync(handle, 0); nsslowkey_CloseKeyDB(update); - - if ( oldSalt ) { - SECITEM_FreeItem(oldSalt, PR_TRUE); + + if (oldSalt) { + SECITEM_FreeItem(oldSalt, PR_TRUE); } - - if ( dbkey ) { - sec_destroy_dbkey(dbkey); + + if (dbkey) { + sec_destroy_dbkey(dbkey); } - return(SECSuccess); + return (SECSuccess); } static SECStatus -openNewDB(const char *appName, const char *prefix, const char *dbname, - NSSLOWKEYDBHandle *handle, NSSLOWKEYDBNameFunc namecb, void *cbarg) +openNewDB(const char *appName, const char *prefix, const char *dbname, + NSSLOWKEYDBHandle *handle, NSSLOWKEYDBNameFunc namecb, void *cbarg) { SECStatus rv = SECFailure; int status = RDB_FAIL; @@ -776,21 +774,21 @@ openNewDB(const char *appName, const char *prefix, const char *dbname, int ret; if (appName) { - handle->db = rdbopen( appName, prefix, "key", NO_CREATE, &status); + handle->db = rdbopen(appName, prefix, "key", NO_CREATE, &status); } else { - handle->db = dbopen( dbname, NO_CREATE, 0600, DB_HASH, 0 ); + handle->db = dbopen(dbname, NO_CREATE, 0600, DB_HASH, 0); } /* if create fails then we lose */ - if ( handle->db == NULL ) { - return (status == RDB_RETRY) ? SECWouldBlock: SECFailure; + if (handle->db == NULL) { + return (status == RDB_RETRY) ? SECWouldBlock : SECFailure; } /* force a transactional read, which will verify that one and only one * process attempts the update. */ if (nsslowkey_version(handle) == NSSLOWKEY_DB_FILE_VERSION) { - /* someone else has already updated the database for us */ - db_InitComplete(handle->db); - return SECSuccess; + /* someone else has already updated the database for us */ + db_InitComplete(handle->db); + return SECSuccess; } /* @@ -799,76 +797,75 @@ openNewDB(const char *appName, const char *prefix, const char *dbname, */ if (appName) { NSSLOWKEYDBHandle *updateHandle; - updatedb = dbopen( dbname, NO_RDONLY, 0600, DB_HASH, 0 ); - if (!updatedb) { - goto noupdate; - } + updatedb = dbopen(dbname, NO_RDONLY, 0600, DB_HASH, 0); + if (!updatedb) { + goto noupdate; + } - /* nsslowkey_version needs a full handle because it calls + /* nsslowkey_version needs a full handle because it calls * the kdb_Get() function, which needs to lock. */ updateHandle = nsslowkey_NewHandle(updatedb); - if (!updateHandle) { - updatedb->close(updatedb); - goto noupdate; - } - - handle->version = nsslowkey_version(updateHandle); - if (handle->version != NSSLOWKEY_DB_FILE_VERSION) { - nsslowkey_CloseKeyDB(updateHandle); - goto noupdate; - } - - /* copy the new DB from the old one */ - db_Copy(handle->db, updatedb); - nsslowkey_CloseKeyDB(updateHandle); - db_InitComplete(handle->db); - return SECSuccess; + if (!updateHandle) { + updatedb->close(updatedb); + goto noupdate; + } + + handle->version = nsslowkey_version(updateHandle); + if (handle->version != NSSLOWKEY_DB_FILE_VERSION) { + nsslowkey_CloseKeyDB(updateHandle); + goto noupdate; + } + + /* copy the new DB from the old one */ + db_Copy(handle->db, updatedb); + nsslowkey_CloseKeyDB(updateHandle); + db_InitComplete(handle->db); + return SECSuccess; } noupdate: /* update the version number */ rv = makeGlobalVersion(handle); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* * try to update from v2 db */ updname = (*namecb)(cbarg, 2); - if ( updname != NULL ) { - handle->updatedb = dbopen( updname, NO_RDONLY, 0600, DB_HASH, 0 ); - PORT_Free( updname ); - - if ( handle->updatedb ) { - /* - * Try to update the db using a null password. If the db - * doesn't have a password, then this will work. If it does - * have a password, then this will fail and we will do the - * update later - */ - rv = nsslowkey_UpdateKeyDBPass1(handle); - if ( rv == SECSuccess ) { - updated = PR_TRUE; - } - } - + if (updname != NULL) { + handle->updatedb = dbopen(updname, NO_RDONLY, 0600, DB_HASH, 0); + PORT_Free(updname); + + if (handle->updatedb) { + /* + * Try to update the db using a null password. If the db + * doesn't have a password, then this will work. If it does + * have a password, then this will fail and we will do the + * update later + */ + rv = nsslowkey_UpdateKeyDBPass1(handle); + if (rv == SECSuccess) { + updated = PR_TRUE; + } + } } /* we are using the old salt if we updated from an old db */ - if ( ! updated ) { - rv = makeGlobalSalt(handle); - if ( rv != SECSuccess ) { - goto loser; - } + if (!updated) { + rv = makeGlobalSalt(handle); + if (rv != SECSuccess) { + goto loser; + } } - + /* sync the database */ ret = keydb_Sync(handle, 0); - if ( ret ) { - rv = SECFailure; - goto loser; + if (ret) { + rv = SECFailure; + goto loser; } rv = SECSuccess; @@ -877,16 +874,16 @@ loser: return rv; } - static DB * -openOldDB(const char *appName, const char *prefix, const char *dbname, - PRBool openflags) { +openOldDB(const char *appName, const char *prefix, const char *dbname, + PRBool openflags) +{ DB *db = NULL; if (appName) { - db = rdbopen( appName, prefix, "key", openflags, NULL); + db = rdbopen(appName, prefix, "key", openflags, NULL); } else { - db = dbopen( dbname, openflags, 0600, DB_HASH, 0 ); + db = dbopen(dbname, openflags, 0600, DB_HASH, 0); } return db; @@ -899,11 +896,11 @@ verifyVersion(NSSLOWKEYDBHandle *handle) int version = nsslowkey_version(handle); handle->version = version; - if (version != NSSLOWKEY_DB_FILE_VERSION ) { - if (handle->db) { - keydb_Close(handle); - handle->db = NULL; - } + if (version != NSSLOWKEY_DB_FILE_VERSION) { + if (handle->db) { + keydb_Close(handle); + handle->db = NULL; + } } return handle->db != NULL; } @@ -912,10 +909,10 @@ static NSSLOWKEYDBHandle * nsslowkey_NewHandle(DB *dbHandle) { NSSLOWKEYDBHandle *handle; - handle = (NSSLOWKEYDBHandle *)PORT_ZAlloc (sizeof(NSSLOWKEYDBHandle)); + handle = (NSSLOWKEYDBHandle *)PORT_ZAlloc(sizeof(NSSLOWKEYDBHandle)); if (handle == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } handle->appname = NULL; @@ -931,68 +928,63 @@ nsslowkey_NewHandle(DB *dbHandle) NSSLOWKEYDBHandle * nsslowkey_OpenKeyDB(PRBool readOnly, const char *appName, const char *prefix, - NSSLOWKEYDBNameFunc namecb, void *cbarg) + NSSLOWKEYDBNameFunc namecb, void *cbarg) { NSSLOWKEYDBHandle *handle = NULL; SECStatus rv; int openflags; char *dbname = NULL; - handle = nsslowkey_NewHandle(NULL); openflags = readOnly ? NO_RDONLY : NO_RDWR; - dbname = (*namecb)(cbarg, NSSLOWKEY_DB_FILE_VERSION); - if ( dbname == NULL ) { - goto loser; + if (dbname == NULL) { + goto loser; } - handle->appname = appName ? PORT_Strdup(appName) : NULL ; - handle->dbname = (appName == NULL) ? PORT_Strdup(dbname) : - (prefix ? PORT_Strdup(prefix) : NULL); + handle->appname = appName ? PORT_Strdup(appName) : NULL; + handle->dbname = (appName == NULL) ? PORT_Strdup(dbname) : (prefix ? PORT_Strdup(prefix) : NULL); handle->readOnly = readOnly; - - handle->db = openOldDB(appName, prefix, dbname, openflags); if (handle->db) { - verifyVersion(handle); - if (handle->version == 255) { - goto loser; - } + verifyVersion(handle); + if (handle->version == 255) { + goto loser; + } } /* if first open fails, try to create a new DB */ - if ( handle->db == NULL ) { - if ( readOnly ) { - goto loser; - } - - rv = openNewDB(appName, prefix, dbname, handle, namecb, cbarg); - /* two processes started to initialize the database at the same time. - * The multiprocess code blocked the second one, then had it retry to - * see if it can just open the database normally */ - if (rv == SECWouldBlock) { - handle->db = openOldDB(appName,prefix,dbname, openflags); - verifyVersion(handle); - if (handle->db == NULL) { - goto loser; - } - } else if (rv != SECSuccess) { - goto loser; - } + if (handle->db == NULL) { + if (readOnly) { + goto loser; + } + + rv = openNewDB(appName, prefix, dbname, handle, namecb, cbarg); + /* two processes started to initialize the database at the same time. + * The multiprocess code blocked the second one, then had it retry to + * see if it can just open the database normally */ + if (rv == SECWouldBlock) { + handle->db = openOldDB(appName, prefix, dbname, openflags); + verifyVersion(handle); + if (handle->db == NULL) { + goto loser; + } + } else if (rv != SECSuccess) { + goto loser; + } } handle->global_salt = GetKeyDBGlobalSalt(handle); - if ( dbname ) - PORT_Free( dbname ); + if (dbname) + PORT_Free(dbname); return handle; loser: - if ( dbname ) - PORT_Free( dbname ); + if (dbname) + PORT_Free(dbname); PORT_SetError(SEC_ERROR_BAD_DATABASE); nsslowkey_CloseKeyDB(handle); return NULL; @@ -1005,22 +997,24 @@ void nsslowkey_CloseKeyDB(NSSLOWKEYDBHandle *handle) { if (handle != NULL) { - if (handle->db != NULL) { - keydb_Close(handle); - } - if (handle->updatedb) { - handle->updatedb->close(handle->updatedb); + if (handle->db != NULL) { + keydb_Close(handle); } - if (handle->dbname) PORT_Free(handle->dbname); - if (handle->appname) PORT_Free(handle->appname); - if (handle->global_salt) { - SECITEM_FreeItem(handle->global_salt,PR_TRUE); - } - if (handle->lock != NULL) { - SKIP_AFTER_FORK(PZ_DestroyLock(handle->lock)); - } - - PORT_Free(handle); + if (handle->updatedb) { + handle->updatedb->close(handle->updatedb); + } + if (handle->dbname) + PORT_Free(handle->dbname); + if (handle->appname) + PORT_Free(handle->appname); + if (handle->global_salt) { + SECITEM_FreeItem(handle->global_salt, PR_TRUE); + } + if (handle->lock != NULL) { + SKIP_AFTER_FORK(PZ_DestroyLock(handle->lock)); + } + + PORT_Free(handle); } } @@ -1043,8 +1037,8 @@ nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, const SECItem *pubkey) int ret; if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (SECFailure); } /* set up db key and data */ @@ -1053,44 +1047,44 @@ nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, const SECItem *pubkey) /* delete it from the database */ ret = keydb_Del(handle, &namekey, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); + if (ret) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (SECFailure); } /* sync the database */ ret = keydb_Sync(handle, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); + if (ret) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (SECFailure); } - return(SECSuccess); + return (SECSuccess); } /* * Store a key in the database, indexed by its public key modulus.(value!) */ SECStatus -nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SDB *sdb) +nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, + NSSLOWKEYPrivateKey *privkey, + SECItem *pubKeyData, + char *nickname, + SDB *sdb) { - return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, - nickname, sdb, PR_FALSE); + return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, + nickname, sdb, PR_FALSE); } SECStatus -nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SDB *sdb) +nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, + NSSLOWKEYPrivateKey *privkey, + SECItem *pubKeyData, + char *nickname, + SDB *sdb) { - return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, - nickname, sdb, PR_TRUE); + return nsslowkey_StoreKeyByPublicKeyAlg(handle, privkey, pubKeyData, + nickname, sdb, PR_TRUE); } /* see if the symetric CKA_ID already Exists. @@ -1105,10 +1099,10 @@ nsslowkey_KeyForIDExists(NSSLOWKEYDBHandle *handle, SECItem *id) namekey.data = (char *)id->data; namekey.size = id->len; status = keydb_Get(handle, &namekey, &dummy, 0); - if ( status ) { - return PR_FALSE; + if (status) { + return PR_FALSE; } - + return PR_TRUE; } @@ -1122,64 +1116,64 @@ nsslowkey_KeyForCertExists(NSSLOWKEYDBHandle *handle, NSSLOWCERTCertificate *cer DBT namekey; DBT dummy; int status; - + /* get cert's public key */ pubkey = nsslowcert_ExtractPublicKey(cert); - if ( pubkey == NULL ) { - return PR_FALSE; + if (pubkey == NULL) { + return PR_FALSE; } /* TNH - make key from NSSLOWKEYPublicKey */ switch (pubkey->keyType) { - case NSSLOWKEYRSAKey: - namekey.data = pubkey->u.rsa.modulus.data; - namekey.size = pubkey->u.rsa.modulus.len; - break; - case NSSLOWKEYDSAKey: - namekey.data = pubkey->u.dsa.publicValue.data; - namekey.size = pubkey->u.dsa.publicValue.len; - break; - case NSSLOWKEYDHKey: - namekey.data = pubkey->u.dh.publicValue.data; - namekey.size = pubkey->u.dh.publicValue.len; - break; + case NSSLOWKEYRSAKey: + namekey.data = pubkey->u.rsa.modulus.data; + namekey.size = pubkey->u.rsa.modulus.len; + break; + case NSSLOWKEYDSAKey: + namekey.data = pubkey->u.dsa.publicValue.data; + namekey.size = pubkey->u.dsa.publicValue.len; + break; + case NSSLOWKEYDHKey: + namekey.data = pubkey->u.dh.publicValue.data; + namekey.size = pubkey->u.dh.publicValue.len; + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - namekey.data = pubkey->u.ec.publicValue.data; - namekey.size = pubkey->u.ec.publicValue.len; - break; + case NSSLOWKEYECKey: + namekey.data = pubkey->u.ec.publicValue.data; + namekey.size = pubkey->u.ec.publicValue.len; + break; #endif /* NSS_DISABLE_ECC */ - default: - /* XXX We don't do Fortezza or DH yet. */ - return PR_FALSE; + default: + /* XXX We don't do Fortezza or DH yet. */ + return PR_FALSE; } if (handle->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,namekey.data,namekey.size); - /* NOTE: don't use pubkey after this! it's now thrashed */ - PORT_Memcpy(namekey.data,buf,sizeof(buf)); - namekey.size = sizeof(buf); + unsigned char buf[SHA1_LENGTH]; + SHA1_HashBuf(buf, namekey.data, namekey.size); + /* NOTE: don't use pubkey after this! it's now thrashed */ + PORT_Memcpy(namekey.data, buf, sizeof(buf)); + namekey.size = sizeof(buf); } status = keydb_Get(handle, &namekey, &dummy, 0); /* some databases have the key stored as a signed value */ if (status) { - unsigned char *buf = (unsigned char *)PORT_Alloc(namekey.size+1); - if (buf) { - PORT_Memcpy(&buf[1], namekey.data, namekey.size); - buf[0] = 0; - namekey.data = buf; - namekey.size ++; - status = keydb_Get(handle, &namekey, &dummy, 0); - PORT_Free(buf); - } + unsigned char *buf = (unsigned char *)PORT_Alloc(namekey.size + 1); + if (buf) { + PORT_Memcpy(&buf[1], namekey.data, namekey.size); + buf[0] = 0; + namekey.data = buf; + namekey.size++; + status = keydb_Get(handle, &namekey, &dummy, 0); + PORT_Free(buf); + } } lg_nsslowkey_DestroyPublicKey(pubkey); - if ( status ) { - return PR_FALSE; + if (status) { + return PR_FALSE; } - + return PR_TRUE; } @@ -1189,12 +1183,12 @@ typedef struct NSSLowPasswordDataParamStr { } NSSLowPasswordDataParam; static const SEC_ASN1Template NSSLOWPasswordParamTemplate[] = -{ - {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLowPasswordDataParam) }, - {SEC_ASN1_OCTET_STRING, offsetof(NSSLowPasswordDataParam, salt) }, - {SEC_ASN1_INTEGER, offsetof(NSSLowPasswordDataParam, iter) }, - {0} -}; + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLowPasswordDataParam) }, + { SEC_ASN1_OCTET_STRING, offsetof(NSSLowPasswordDataParam, salt) }, + { SEC_ASN1_INTEGER, offsetof(NSSLowPasswordDataParam, iter) }, + { 0 } + }; struct LGEncryptedDataInfoStr { SECAlgorithmID algorithm; SECItem encryptedData; @@ -1203,12 +1197,12 @@ typedef struct LGEncryptedDataInfoStr LGEncryptedDataInfo; const SEC_ASN1Template lg_EncryptedDataInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(LGEncryptedDataInfo) }, + 0, NULL, sizeof(LGEncryptedDataInfo) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(LGEncryptedDataInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(LGEncryptedDataInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(LGEncryptedDataInfo,encryptedData) }, + offsetof(LGEncryptedDataInfo, encryptedData) }, { 0 } }; @@ -1224,24 +1218,24 @@ nsslowkey_EncodePW(SECOidTag alg, const SECItem *salt, SECItem *data) SECStatus rv; param.salt = *salt; - param.iter.type = siBuffer; /* encode as signed integer */ + param.iter.type = siBuffer; /* encode as signed integer */ param.iter.data = &one; param.iter.len = 1; edi.encryptedData = *data; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - return NULL; + return NULL; } encParam = SEC_ASN1EncodeItem(arena, NULL, ¶m, - NSSLOWPasswordParamTemplate); + NSSLOWPasswordParamTemplate); if (encParam == NULL) { - goto loser; + goto loser; } rv = SECOID_SetAlgorithmID(arena, &edi.algorithm, alg, encParam); if (rv != SECSuccess) { - goto loser; + goto loser; } epw = SEC_ASN1EncodeItem(NULL, NULL, &edi, lg_EncryptedDataInfoTemplate); @@ -1260,69 +1254,68 @@ nsslowkey_DecodePW(const SECItem *derData, SECOidTag *alg, SECItem *salt) SECStatus rv; salt->data = NULL; - param.iter.type = siBuffer; /* decode as signed integer */ + param.iter.type = siBuffer; /* decode as signed integer */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - return NULL; + return NULL; } - rv = SEC_QuickDERDecodeItem(arena, &edi, lg_EncryptedDataInfoTemplate, - derData); + rv = SEC_QuickDERDecodeItem(arena, &edi, lg_EncryptedDataInfoTemplate, + derData); if (rv != SECSuccess) { - goto loser; + goto loser; } *alg = SECOID_GetAlgorithmTag(&edi.algorithm); rv = SEC_QuickDERDecodeItem(arena, ¶m, NSSLOWPasswordParamTemplate, - &edi.algorithm.parameters); + &edi.algorithm.parameters); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = SECITEM_CopyItem(NULL, salt, ¶m.salt); if (rv != SECSuccess) { - goto loser; + goto loser; } pwe = SECITEM_DupItem(&edi.encryptedData); loser: if (!pwe && salt->data) { - PORT_Free(salt->data); - salt->data = NULL; + PORT_Free(salt->data); + salt->data = NULL; } PORT_FreeArena(arena, PR_FALSE); return pwe; } - /* * check to see if the user has a password */ static SECStatus -nsslowkey_GetPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entry) +nsslowkey_GetPWCheckEntry(NSSLOWKEYDBHandle *handle, NSSLOWKEYPasswordEntry *entry) { DBT checkkey; /*, checkdata; */ NSSLOWKEYDBKey *dbkey = NULL; - SECItem *global_salt = NULL; - SECItem *item = NULL; - SECItem entryData, oid; - SECItem none = { siBuffer, NULL, 0 }; + SECItem *global_salt = NULL; + SECItem *item = NULL; + SECItem entryData, oid; + SECItem none = { siBuffer, NULL, 0 }; SECStatus rv = SECFailure; SECOidTag algorithm; if (handle == NULL) { - /* PORT_SetError */ - return(SECFailure); + /* PORT_SetError */ + return (SECFailure); } global_salt = GetKeyDBGlobalSalt(handle); if (!global_salt) { - global_salt = &none; + global_salt = &none; } if (global_salt->len > sizeof(entry->data)) { - /* PORT_SetError */ - goto loser; + /* PORT_SetError */ + goto loser; } - + PORT_Memcpy(entry->data, global_salt->data, global_salt->len); entry->salt.data = entry->data; entry->salt.len = global_salt->len; @@ -1332,24 +1325,24 @@ nsslowkey_GetPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entr checkkey.size = KEYDB_PW_CHECK_LEN; dbkey = get_dbkey(handle, &checkkey); if (dbkey == NULL) { - /* handle 'FAKE' check here */ - goto loser; + /* handle 'FAKE' check here */ + goto loser; } oid.len = dbkey->derPK.data[0]; oid.data = &dbkey->derPK.data[1]; - if (dbkey->derPK.len < (KEYDB_PW_CHECK_LEN + 1 +oid.len)) { - goto loser; + if (dbkey->derPK.len < (KEYDB_PW_CHECK_LEN + 1 + oid.len)) { + goto loser; } algorithm = SECOID_FindOIDTag(&oid); entryData.type = siBuffer; - entryData.len = dbkey->derPK.len - (oid.len+1); - entryData.data = &dbkey->derPK.data[oid.len+1]; + entryData.len = dbkey->derPK.len - (oid.len + 1); + entryData.data = &dbkey->derPK.data[oid.len + 1]; item = nsslowkey_EncodePW(algorithm, &dbkey->salt, &entryData); if (!item || (item->len + entry->salt.len) > sizeof(entry->data)) { - goto loser; + goto loser; } PORT_Memcpy(entry->value.data, item->data, item->len); entry->value.len = item->len; @@ -1357,13 +1350,13 @@ nsslowkey_GetPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entr loser: if (item) { - SECITEM_FreeItem(item, PR_TRUE); + SECITEM_FreeItem(item, PR_TRUE); } if (dbkey) { - sec_destroy_dbkey(dbkey); + sec_destroy_dbkey(dbkey); } if (global_salt != &none) { - SECITEM_FreeItem(global_salt,PR_TRUE); + SECITEM_FreeItem(global_salt, PR_TRUE); } return rv; } @@ -1372,20 +1365,20 @@ loser: * check to see if the user has a password */ static SECStatus -nsslowkey_PutPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entry) +nsslowkey_PutPWCheckEntry(NSSLOWKEYDBHandle *handle, NSSLOWKEYPasswordEntry *entry) { DBT checkkey; NSSLOWKEYDBKey *dbkey = NULL; - SECItem *item = NULL; - SECItem salt; + SECItem *item = NULL; + SECItem salt; SECOidTag algid = SEC_OID_UNKNOWN; SECStatus rv = SECFailure; PLArenaPool *arena; int ret; if (handle == NULL) { - /* PORT_SetError */ - return(SECFailure); + /* PORT_SetError */ + return (SECFailure); } checkkey.data = KEYDB_PW_CHECK_STRING; @@ -1394,80 +1387,79 @@ nsslowkey_PutPWCheckEntry(NSSLOWKEYDBHandle *handle,NSSLOWKEYPasswordEntry *entr salt.data = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - return SECFailure; + return SECFailure; } item = nsslowkey_DecodePW(&entry->value, &algid, &salt); if (item == NULL) { - goto loser; + goto loser; } dbkey = PORT_ArenaZNew(arena, NSSLOWKEYDBKey); if (dbkey == NULL) { - goto loser; + goto loser; } dbkey->arena = arena; rv = SECITEM_CopyItem(arena, &dbkey->salt, &salt); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = encodePWCheckEntry(arena, &dbkey->derPK, algid, item); if (rv != SECSuccess) { - goto loser; + goto loser; } rv = put_dbkey(handle, &checkkey, dbkey, PR_TRUE); if (rv != SECSuccess) { - goto loser; + goto loser; } if (handle->global_salt) { - SECITEM_FreeItem(handle->global_salt, PR_TRUE); - handle->global_salt = NULL; + SECITEM_FreeItem(handle->global_salt, PR_TRUE); + handle->global_salt = NULL; } rv = StoreKeyDBGlobalSalt(handle, &entry->salt); if (rv != SECSuccess) { - goto loser; + goto loser; } ret = keydb_Sync(handle, 0); - if ( ret ) { - rv = SECFailure; - goto loser; + if (ret) { + rv = SECFailure; + goto loser; } handle->global_salt = GetKeyDBGlobalSalt(handle); loser: if (item) { - SECITEM_FreeItem(item, PR_TRUE); + SECITEM_FreeItem(item, PR_TRUE); } if (arena) { - PORT_FreeArena(arena, PR_TRUE); + PORT_FreeArena(arena, PR_TRUE); } if (salt.data) { - PORT_Free(salt.data); + PORT_Free(salt.data); } return rv; } #ifdef EC_DEBUG -#define SEC_PRINT(str1, str2, num, sitem) \ +#define SEC_PRINT(str1, str2, num, sitem) \ printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \ - str1, str2, num, sitem->len); \ - for (i = 0; i < sitem->len; i++) { \ - printf("%02x:", sitem->data[i]); \ - } \ - printf("\n") + str1, str2, num, sitem->len); \ + for (i = 0; i < sitem->len; i++) { \ + printf("%02x:", sitem->data[i]); \ + } \ + printf("\n") #else -#define SEC_PRINT(a, b, c, d) +#define SEC_PRINT(a, b, c, d) #endif /* EC_DEBUG */ - -SECStatus -seckey_encrypt_private_key( PLArenaPool *permarena, NSSLOWKEYPrivateKey *pk, - SDB *sdbpw, SECItem *result) +SECStatus +seckey_encrypt_private_key(PLArenaPool *permarena, NSSLOWKEYPrivateKey *pk, + SDB *sdbpw, SECItem *result) { NSSLOWKEYPrivateKeyInfo *pki = NULL; SECStatus rv = SECFailure; @@ -1483,187 +1475,186 @@ seckey_encrypt_private_key( PLArenaPool *permarena, NSSLOWKEYPrivateKey *pk, #endif temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if(temparena == NULL) - goto loser; + if (temparena == NULL) + goto loser; /* allocate structures */ - pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, - sizeof(NSSLOWKEYPrivateKeyInfo)); + pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, + sizeof(NSSLOWKEYPrivateKeyInfo)); der_item = (SECItem *)PORT_ArenaZAlloc(temparena, sizeof(SECItem)); - if((pki == NULL) || (der_item == NULL)) - goto loser; - + if ((pki == NULL) || (der_item == NULL)) + goto loser; /* setup private key info */ - dummy = SEC_ASN1EncodeInteger(temparena, &(pki->version), - NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); - if(dummy == NULL) - goto loser; + dummy = SEC_ASN1EncodeInteger(temparena, &(pki->version), + NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); + if (dummy == NULL) + goto loser; /* Encode the key, and set the algorithm (with params) */ switch (pk->keyType) { - case NSSLOWKEYRSAKey: - lg_prepare_low_rsa_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - lg_nsslowkey_RSAPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_PKCS1_RSA_ENCRYPTION, 0); - if (rv == SECFailure) { - goto loser; - } - - break; - case NSSLOWKEYDSAKey: - lg_prepare_low_dsa_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - lg_nsslowkey_DSAPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); - dummy = SEC_ASN1EncodeItem(temparena, NULL, &pk->u.dsa.params, - lg_nsslowkey_PQGParamsTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_ANSIX9_DSA_SIGNATURE, dummy); - if (rv == SECFailure) { - goto loser; - } - - break; - case NSSLOWKEYDHKey: - lg_prepare_low_dh_priv_key_for_asn1(pk); - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - lg_nsslowkey_DHPrivateKeyTemplate); - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_X942_DIFFIE_HELMAN_KEY, dummy); - if (rv == SECFailure) { - goto loser; - } - break; + case NSSLOWKEYRSAKey: + lg_prepare_low_rsa_priv_key_for_asn1(pk); + dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, + lg_nsslowkey_RSAPrivateKeyTemplate); + if (dummy == NULL) { + rv = SECFailure; + goto loser; + } + + rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), + SEC_OID_PKCS1_RSA_ENCRYPTION, 0); + if (rv == SECFailure) { + goto loser; + } + + break; + case NSSLOWKEYDSAKey: + lg_prepare_low_dsa_priv_key_for_asn1(pk); + dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, + lg_nsslowkey_DSAPrivateKeyTemplate); + if (dummy == NULL) { + rv = SECFailure; + goto loser; + } + + lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); + dummy = SEC_ASN1EncodeItem(temparena, NULL, &pk->u.dsa.params, + lg_nsslowkey_PQGParamsTemplate); + if (dummy == NULL) { + rv = SECFailure; + goto loser; + } + + rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), + SEC_OID_ANSIX9_DSA_SIGNATURE, dummy); + if (rv == SECFailure) { + goto loser; + } + + break; + case NSSLOWKEYDHKey: + lg_prepare_low_dh_priv_key_for_asn1(pk); + dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, + lg_nsslowkey_DHPrivateKeyTemplate); + if (dummy == NULL) { + rv = SECFailure; + goto loser; + } + + rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), + SEC_OID_X942_DIFFIE_HELMAN_KEY, dummy); + if (rv == SECFailure) { + goto loser; + } + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - lg_prepare_low_ec_priv_key_for_asn1(pk); - /* Public value is encoded as a bit string so adjust length - * to be in bits before ASN encoding and readjust - * immediately after. - * - * Since the SECG specification recommends not including the - * parameters as part of ECPrivateKey, we zero out the curveOID - * length before encoding and restore it later. - */ - pk->u.ec.publicValue.len <<= 3; - savelen = pk->u.ec.ecParams.curveOID.len; - pk->u.ec.ecParams.curveOID.len = 0; - dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, - lg_nsslowkey_ECPrivateKeyTemplate); - pk->u.ec.ecParams.curveOID.len = savelen; - pk->u.ec.publicValue.len >>= 3; - - if (dummy == NULL) { - rv = SECFailure; - goto loser; - } - - dummy = &pk->u.ec.ecParams.DEREncoding; - - /* At this point dummy should contain the encoded params */ - rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), - SEC_OID_ANSIX962_EC_PUBLIC_KEY, dummy); - - if (rv == SECFailure) { - goto loser; - } - + case NSSLOWKEYECKey: + lg_prepare_low_ec_priv_key_for_asn1(pk); + /* Public value is encoded as a bit string so adjust length + * to be in bits before ASN encoding and readjust + * immediately after. + * + * Since the SECG specification recommends not including the + * parameters as part of ECPrivateKey, we zero out the curveOID + * length before encoding and restore it later. + */ + pk->u.ec.publicValue.len <<= 3; + savelen = pk->u.ec.ecParams.curveOID.len; + pk->u.ec.ecParams.curveOID.len = 0; + dummy = SEC_ASN1EncodeItem(temparena, &(pki->privateKey), pk, + lg_nsslowkey_ECPrivateKeyTemplate); + pk->u.ec.ecParams.curveOID.len = savelen; + pk->u.ec.publicValue.len >>= 3; + + if (dummy == NULL) { + rv = SECFailure; + goto loser; + } + + dummy = &pk->u.ec.ecParams.DEREncoding; + + /* At this point dummy should contain the encoded params */ + rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm), + SEC_OID_ANSIX962_EC_PUBLIC_KEY, dummy); + + if (rv == SECFailure) { + goto loser; + } + #ifdef EC_DEBUG - fordebug = &(pki->privateKey); - SEC_PRINT("seckey_encrypt_private_key()", "PrivateKey", - pk->keyType, fordebug); + fordebug = &(pki->privateKey); + SEC_PRINT("seckey_encrypt_private_key()", "PrivateKey", + pk->keyType, fordebug); #endif - break; + break; #endif /* NSS_DISABLE_ECC */ - default: - /* We don't support DH or Fortezza private keys yet */ - PORT_Assert(PR_FALSE); - break; + default: + /* We don't support DH or Fortezza private keys yet */ + PORT_Assert(PR_FALSE); + break; } /* setup encrypted private key info */ - dummy = SEC_ASN1EncodeItem(temparena, der_item, pki, - lg_nsslowkey_PrivateKeyInfoTemplate); + dummy = SEC_ASN1EncodeItem(temparena, der_item, pki, + lg_nsslowkey_PrivateKeyInfoTemplate); - SEC_PRINT("seckey_encrypt_private_key()", "PrivateKeyInfo", - pk->keyType, der_item); + SEC_PRINT("seckey_encrypt_private_key()", "PrivateKeyInfo", + pk->keyType, der_item); - if(dummy == NULL) { - rv = SECFailure; - goto loser; + if (dummy == NULL) { + rv = SECFailure; + goto loser; } rv = lg_util_encrypt(temparena, sdbpw, dummy, &cipherText); if (rv != SECSuccess) { - goto loser; + goto loser; } - rv = SECITEM_CopyItem ( permarena, result, cipherText); + rv = SECITEM_CopyItem(permarena, result, cipherText); loser: - if(temparena != NULL) - PORT_FreeArena(temparena, PR_TRUE); + if (temparena != NULL) + PORT_FreeArena(temparena, PR_TRUE); return rv; } -static SECStatus +static SECStatus seckey_put_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, SDB *sdbpw, - NSSLOWKEYPrivateKey *pk, char *nickname, PRBool update) + NSSLOWKEYPrivateKey *pk, char *nickname, PRBool update) { NSSLOWKEYDBKey *dbkey = NULL; PLArenaPool *arena = NULL; SECStatus rv = SECFailure; - if((keydb == NULL) || (index == NULL) || (sdbpw == NULL) || - (pk == NULL)) - return SECFailure; - + if ((keydb == NULL) || (index == NULL) || (sdbpw == NULL) || + (pk == NULL)) + return SECFailure; + arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if(arena == NULL) - return SECFailure; + if (arena == NULL) + return SECFailure; dbkey = (NSSLOWKEYDBKey *)PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYDBKey)); - if(dbkey == NULL) - goto loser; + if (dbkey == NULL) + goto loser; dbkey->arena = arena; dbkey->nickname = nickname; rv = seckey_encrypt_private_key(arena, pk, sdbpw, &dbkey->derPK); - if(rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; rv = put_dbkey(keydb, index, dbkey, update); - /* let success fall through */ +/* let success fall through */ loser: - if(arena != NULL) - PORT_FreeArena(arena, PR_TRUE); + if (arena != NULL) + PORT_FreeArena(arena, PR_TRUE); return rv; } @@ -1673,19 +1664,19 @@ loser: * Note that the nickname is optional. It was only used by keyutil. */ SECStatus -nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SDB *sdbpw, - PRBool update) +nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, + NSSLOWKEYPrivateKey *privkey, + SECItem *pubKeyData, + char *nickname, + SDB *sdbpw, + PRBool update) { DBT namekey; SECStatus rv; if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (SECFailure); } /* set up db key and data */ @@ -1694,14 +1685,14 @@ nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, /* encrypt the private key */ rv = seckey_put_private_key(handle, &namekey, sdbpw, privkey, nickname, - update); - - return(rv); + update); + + return (rv); } static NSSLOWKEYPrivateKey * -seckey_decrypt_private_key(SECItem*epki, - SDB *sdbpw) +seckey_decrypt_private_key(SECItem *epki, + SDB *sdbpw) { NSSLOWKEYPrivateKey *pk = NULL; NSSLOWKEYPrivateKeyInfo *pki = NULL; @@ -1712,174 +1703,174 @@ seckey_decrypt_private_key(SECItem*epki, SECItem *fordebug = NULL; #endif - if((epki == NULL) || (sdbpw == NULL)) - goto loser; + if ((epki == NULL) || (sdbpw == NULL)) + goto loser; temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if((temparena == NULL) || (permarena == NULL)) - goto loser; + if ((temparena == NULL) || (permarena == NULL)) + goto loser; /* allocate temporary items */ - pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, - sizeof(NSSLOWKEYPrivateKeyInfo)); + pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(temparena, + sizeof(NSSLOWKEYPrivateKeyInfo)); /* allocate permanent arena items */ pk = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(permarena, - sizeof(NSSLOWKEYPrivateKey)); + sizeof(NSSLOWKEYPrivateKey)); - if((pk == NULL) || (pki == NULL)) - goto loser; + if ((pk == NULL) || (pki == NULL)) + goto loser; pk->arena = permarena; rv = lg_util_decrypt(sdbpw, epki, &dest); if (rv != SECSuccess) { - goto loser; + goto loser; } - - if(dest != NULL) - { + + if (dest != NULL) { SECItem newPrivateKey; SECItem newAlgParms; SEC_PRINT("seckey_decrypt_private_key()", "PrivateKeyInfo", -1, - dest); - - rv = SEC_QuickDERDecodeItem(temparena, pki, - lg_nsslowkey_PrivateKeyInfoTemplate, dest); - if(rv == SECSuccess) - { - switch(SECOID_GetAlgorithmTag(&pki->algorithm)) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - pk->keyType = NSSLOWKEYRSAKey; - lg_prepare_low_rsa_priv_key_for_asn1(pk); - if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, - &pki->privateKey) ) break; - rv = SEC_QuickDERDecodeItem(permarena, pk, - lg_nsslowkey_RSAPrivateKeyTemplate, - &newPrivateKey); - if (rv == SECSuccess) { - break; - } - /* Try decoding with the alternative template, but only allow - * a zero-length modulus for a secret key object. - * See bug 715073. - */ - rv = SEC_QuickDERDecodeItem(permarena, pk, - lg_nsslowkey_RSAPrivateKeyTemplate2, - &newPrivateKey); - /* A publicExponent of 0 is the defining property of a secret - * key disguised as an RSA key. When decoding with the - * alternative template, only accept a secret key with an - * improperly encoded modulus and a publicExponent of 0. - */ - if (rv == SECSuccess) { - if (pk->u.rsa.modulus.len == 2 && - pk->u.rsa.modulus.data[0] == SEC_ASN1_INTEGER && - pk->u.rsa.modulus.data[1] == 0 && - pk->u.rsa.publicExponent.len == 1 && - pk->u.rsa.publicExponent.data[0] == 0) { - /* Fix the zero-length integer by setting it to 0. */ - pk->u.rsa.modulus.data = pk->u.rsa.publicExponent.data; - pk->u.rsa.modulus.len = pk->u.rsa.publicExponent.len; - } else { - PORT_SetError(SEC_ERROR_BAD_DER); - rv = SECFailure; - } - } - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - pk->keyType = NSSLOWKEYDSAKey; - lg_prepare_low_dsa_priv_key_for_asn1(pk); - if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, - &pki->privateKey) ) break; - rv = SEC_QuickDERDecodeItem(permarena, pk, - lg_nsslowkey_DSAPrivateKeyTemplate, - &newPrivateKey); - if (rv != SECSuccess) - goto loser; - lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); - if (SECSuccess != SECITEM_CopyItem(permarena, &newAlgParms, - &pki->algorithm.parameters) ) break; - rv = SEC_QuickDERDecodeItem(permarena, &pk->u.dsa.params, - lg_nsslowkey_PQGParamsTemplate, - &newAlgParms); - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - pk->keyType = NSSLOWKEYDHKey; - lg_prepare_low_dh_priv_key_for_asn1(pk); - if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, - &pki->privateKey) ) break; - rv = SEC_QuickDERDecodeItem(permarena, pk, - lg_nsslowkey_DHPrivateKeyTemplate, - &newPrivateKey); - break; + dest); + + rv = SEC_QuickDERDecodeItem(temparena, pki, + lg_nsslowkey_PrivateKeyInfoTemplate, dest); + if (rv == SECSuccess) { + switch (SECOID_GetAlgorithmTag(&pki->algorithm)) { + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + pk->keyType = NSSLOWKEYRSAKey; + lg_prepare_low_rsa_priv_key_for_asn1(pk); + if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, + &pki->privateKey)) + break; + rv = SEC_QuickDERDecodeItem(permarena, pk, + lg_nsslowkey_RSAPrivateKeyTemplate, + &newPrivateKey); + if (rv == SECSuccess) { + break; + } + /* Try decoding with the alternative template, but only allow + * a zero-length modulus for a secret key object. + * See bug 715073. + */ + rv = SEC_QuickDERDecodeItem(permarena, pk, + lg_nsslowkey_RSAPrivateKeyTemplate2, + &newPrivateKey); + /* A publicExponent of 0 is the defining property of a secret + * key disguised as an RSA key. When decoding with the + * alternative template, only accept a secret key with an + * improperly encoded modulus and a publicExponent of 0. + */ + if (rv == SECSuccess) { + if (pk->u.rsa.modulus.len == 2 && + pk->u.rsa.modulus.data[0] == SEC_ASN1_INTEGER && + pk->u.rsa.modulus.data[1] == 0 && + pk->u.rsa.publicExponent.len == 1 && + pk->u.rsa.publicExponent.data[0] == 0) { + /* Fix the zero-length integer by setting it to 0. */ + pk->u.rsa.modulus.data = pk->u.rsa.publicExponent.data; + pk->u.rsa.modulus.len = pk->u.rsa.publicExponent.len; + } else { + PORT_SetError(SEC_ERROR_BAD_DER); + rv = SECFailure; + } + } + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: + pk->keyType = NSSLOWKEYDSAKey; + lg_prepare_low_dsa_priv_key_for_asn1(pk); + if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, + &pki->privateKey)) + break; + rv = SEC_QuickDERDecodeItem(permarena, pk, + lg_nsslowkey_DSAPrivateKeyTemplate, + &newPrivateKey); + if (rv != SECSuccess) + goto loser; + lg_prepare_low_pqg_params_for_asn1(&pk->u.dsa.params); + if (SECSuccess != SECITEM_CopyItem(permarena, &newAlgParms, + &pki->algorithm.parameters)) + break; + rv = SEC_QuickDERDecodeItem(permarena, &pk->u.dsa.params, + lg_nsslowkey_PQGParamsTemplate, + &newAlgParms); + break; + case SEC_OID_X942_DIFFIE_HELMAN_KEY: + pk->keyType = NSSLOWKEYDHKey; + lg_prepare_low_dh_priv_key_for_asn1(pk); + if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, + &pki->privateKey)) + break; + rv = SEC_QuickDERDecodeItem(permarena, pk, + lg_nsslowkey_DHPrivateKeyTemplate, + &newPrivateKey); + break; #ifndef NSS_DISABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - pk->keyType = NSSLOWKEYECKey; - lg_prepare_low_ec_priv_key_for_asn1(pk); + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + pk->keyType = NSSLOWKEYECKey; + lg_prepare_low_ec_priv_key_for_asn1(pk); #ifdef EC_DEBUG - fordebug = &pki->privateKey; - SEC_PRINT("seckey_decrypt_private_key()", "PrivateKey", - pk->keyType, fordebug); + fordebug = &pki->privateKey; + SEC_PRINT("seckey_decrypt_private_key()", "PrivateKey", + pk->keyType, fordebug); #endif - if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, - &pki->privateKey) ) break; - rv = SEC_QuickDERDecodeItem(permarena, pk, - lg_nsslowkey_ECPrivateKeyTemplate, - &newPrivateKey); - if (rv != SECSuccess) - goto loser; + if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey, + &pki->privateKey)) + break; + rv = SEC_QuickDERDecodeItem(permarena, pk, + lg_nsslowkey_ECPrivateKeyTemplate, + &newPrivateKey); + if (rv != SECSuccess) + goto loser; - lg_prepare_low_ecparams_for_asn1(&pk->u.ec.ecParams); + lg_prepare_low_ecparams_for_asn1(&pk->u.ec.ecParams); - rv = SECITEM_CopyItem(permarena, - &pk->u.ec.ecParams.DEREncoding, - &pki->algorithm.parameters); + rv = SECITEM_CopyItem(permarena, + &pk->u.ec.ecParams.DEREncoding, + &pki->algorithm.parameters); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; - /* Fill out the rest of EC params */ - rv = LGEC_FillParams(permarena, &pk->u.ec.ecParams.DEREncoding, - &pk->u.ec.ecParams); + /* Fill out the rest of EC params */ + rv = LGEC_FillParams(permarena, &pk->u.ec.ecParams.DEREncoding, + &pk->u.ec.ecParams); - if (rv != SECSuccess) - goto loser; + if (rv != SECSuccess) + goto loser; - if (pk->u.ec.publicValue.len != 0) { - pk->u.ec.publicValue.len >>= 3; - } + if (pk->u.ec.publicValue.len != 0) { + pk->u.ec.publicValue.len >>= 3; + } - break; + break; #endif /* NSS_DISABLE_ECC */ - default: - rv = SECFailure; - break; - } - } - else if(PORT_GetError() == SEC_ERROR_BAD_DER) - { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - goto loser; - } - } - - /* let success fall through */ + default: + rv = SECFailure; + break; + } + } else if (PORT_GetError() == SEC_ERROR_BAD_DER) { + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + goto loser; + } + } + +/* let success fall through */ loser: - if(temparena != NULL) - PORT_FreeArena(temparena, PR_TRUE); - if(dest != NULL) - SECITEM_ZfreeItem(dest, PR_TRUE); + if (temparena != NULL) + PORT_FreeArena(temparena, PR_TRUE); + if (dest != NULL) + SECITEM_ZfreeItem(dest, PR_TRUE); - if(rv != SECSuccess) - { - if(permarena != NULL) - PORT_FreeArena(permarena, PR_TRUE); - pk = NULL; + if (rv != SECSuccess) { + if (permarena != NULL) + PORT_FreeArena(permarena, PR_TRUE); + pk = NULL; } return pk; @@ -1888,8 +1879,8 @@ loser: static NSSLOWKEYPrivateKey * seckey_decode_encrypted_private_key(NSSLOWKEYDBKey *dbkey, SDB *sdbpw) { - if( ( dbkey == NULL ) || ( sdbpw == NULL ) ) { - return NULL; + if ((dbkey == NULL) || (sdbpw == NULL)) { + return NULL; } return seckey_decrypt_private_key(&(dbkey->derPK), sdbpw); @@ -1897,35 +1888,35 @@ seckey_decode_encrypted_private_key(NSSLOWKEYDBKey *dbkey, SDB *sdbpw) static NSSLOWKEYPrivateKey * seckey_get_private_key(NSSLOWKEYDBHandle *keydb, DBT *index, char **nickname, - SDB *sdbpw) + SDB *sdbpw) { NSSLOWKEYDBKey *dbkey = NULL; NSSLOWKEYPrivateKey *pk = NULL; - if( ( keydb == NULL ) || ( index == NULL ) || ( sdbpw == NULL ) ) { - return NULL; + if ((keydb == NULL) || (index == NULL) || (sdbpw == NULL)) { + return NULL; } dbkey = get_dbkey(keydb, index); - if(dbkey == NULL) { - goto loser; - } - - if ( nickname ) { - if ( dbkey->nickname && ( dbkey->nickname[0] != 0 ) ) { - *nickname = PORT_Strdup(dbkey->nickname); - } else { - *nickname = NULL; - } - } - + if (dbkey == NULL) { + goto loser; + } + + if (nickname) { + if (dbkey->nickname && (dbkey->nickname[0] != 0)) { + *nickname = PORT_Strdup(dbkey->nickname); + } else { + *nickname = NULL; + } + } + pk = seckey_decode_encrypted_private_key(dbkey, sdbpw); - - /* let success fall through */ + +/* let success fall through */ loser: - if ( dbkey != NULL ) { - sec_destroy_dbkey(dbkey); + if (dbkey != NULL) { + sec_destroy_dbkey(dbkey); } return pk; @@ -1940,14 +1931,14 @@ loser: */ NSSLOWKEYPrivateKey * nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, - SDB *sdbpw) + SDB *sdbpw) { DBT namekey; NSSLOWKEYPrivateKey *pk = NULL; if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return NULL; } /* set up db key */ @@ -1955,24 +1946,24 @@ nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, namekey.size = modulus->len; pk = seckey_get_private_key(handle, &namekey, NULL, sdbpw); - + /* no need to free dbkey, since its on the stack, and the data it * points to is owned by the database */ - return(pk); + return (pk); } char * -nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, - SECItem *modulus, SDB *sdbpw) +nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, + SECItem *modulus, SDB *sdbpw) { DBT namekey; NSSLOWKEYPrivateKey *pk = NULL; char *nickname = NULL; if (handle == NULL) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return NULL; + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return NULL; } /* set up db key */ @@ -1981,51 +1972,50 @@ nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, pk = seckey_get_private_key(handle, &namekey, &nickname, sdbpw); if (pk) { - lg_nsslowkey_DestroyPrivateKey(pk); + lg_nsslowkey_DestroyPrivateKey(pk); } - + /* no need to free dbkey, since its on the stack, and the data it * points to is owned by the database */ - return(nickname); + return (nickname); } /* ===== ENCODING ROUTINES ===== */ static SECStatus encodePWCheckEntry(PLArenaPool *arena, SECItem *entry, SECOidTag alg, - SECItem *encCheck) + SECItem *encCheck) { SECOidData *oidData; - + oidData = SECOID_FindOIDByTag(alg); - if ( oidData == NULL ) { - return SECFailure; + if (oidData == NULL) { + return SECFailure; } entry->len = 1 + oidData->oid.len + encCheck->len; - if ( arena ) { - entry->data = (unsigned char *)PORT_ArenaAlloc(arena, entry->len); + if (arena) { + entry->data = (unsigned char *)PORT_ArenaAlloc(arena, entry->len); } else { - entry->data = (unsigned char *)PORT_Alloc(entry->len); + entry->data = (unsigned char *)PORT_Alloc(entry->len); } - - if ( entry->data == NULL ) { - return SECFailure; + + if (entry->data == NULL) { + return SECFailure; } - + /* first length of oid */ entry->data[0] = (unsigned char)oidData->oid.len; /* next oid itself */ PORT_Memcpy(&entry->data[1], oidData->oid.data, oidData->oid.len); /* finally the encrypted check string */ - PORT_Memcpy(&entry->data[1+oidData->oid.len], encCheck->data, - encCheck->len); + PORT_Memcpy(&entry->data[1 + oidData->oid.len], encCheck->data, + encCheck->len); return SECSuccess; } - -#define MAX_DB_SIZE 0xffff +#define MAX_DB_SIZE 0xffff /* * Clear out all the keys in the existing database */ @@ -2035,47 +2025,47 @@ nsslowkey_ResetKeyDB(NSSLOWKEYDBHandle *handle) SECStatus rv; int errors = 0; - if ( handle->db == NULL ) { - return(SECSuccess); + if (handle->db == NULL) { + return (SECSuccess); } if (handle->readOnly) { - /* set an error code */ - return SECFailure; - } + /* set an error code */ + return SECFailure; + } if (handle->appname == NULL && handle->dbname == NULL) { - return SECFailure; + return SECFailure; } keydb_Close(handle); if (handle->appname) { - handle->db= - rdbopen(handle->appname, handle->dbname, "key", NO_CREATE, NULL); + handle->db = + rdbopen(handle->appname, handle->dbname, "key", NO_CREATE, NULL); } else { - handle->db = dbopen( handle->dbname, NO_CREATE, 0600, DB_HASH, 0 ); + handle->db = dbopen(handle->dbname, NO_CREATE, 0600, DB_HASH, 0); } if (handle->db == NULL) { - /* set an error code */ - return SECFailure; + /* set an error code */ + return SECFailure; } - + rv = makeGlobalVersion(handle); - if ( rv != SECSuccess ) { - errors++; - goto done; + if (rv != SECSuccess) { + errors++; + goto done; } if (handle->global_salt) { - rv = StoreKeyDBGlobalSalt(handle, handle->global_salt); + rv = StoreKeyDBGlobalSalt(handle, handle->global_salt); } else { - rv = makeGlobalSalt(handle); - if ( rv == SECSuccess ) { - handle->global_salt = GetKeyDBGlobalSalt(handle); - } + rv = makeGlobalSalt(handle); + if (rv == SECSuccess) { + handle->global_salt = GetKeyDBGlobalSalt(handle); + } } - if ( rv != SECSuccess ) { - errors++; + if (rv != SECSuccess) { + errors++; } done: @@ -2092,15 +2082,15 @@ keydb_Get(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags) int ret; PRLock *kdbLock = kdb->lock; DB *db = kdb->db; - + PORT_Assert(kdbLock != NULL); PZ_Lock(kdbLock); - ret = (* db->get)(db, key, data, flags); + ret = (*db->get)(db, key, data, flags); (void)PZ_Unlock(kdbLock); - return(ret); + return (ret); } static int @@ -2113,11 +2103,11 @@ keydb_Put(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags) PORT_Assert(kdbLock != NULL); PZ_Lock(kdbLock); - ret = (* db->put)(db, key, data, flags); - + ret = (*db->put)(db, key, data, flags); + (void)PZ_Unlock(kdbLock); - return(ret); + return (ret); } static int @@ -2130,11 +2120,11 @@ keydb_Sync(NSSLOWKEYDBHandle *kdb, unsigned int flags) PORT_Assert(kdbLock != NULL); PZ_Lock(kdbLock); - ret = (* db->sync)(db, flags); - + ret = (*db->sync)(db, flags); + (void)PZ_Unlock(kdbLock); - return(ret); + return (ret); } static int @@ -2147,11 +2137,11 @@ keydb_Del(NSSLOWKEYDBHandle *kdb, DBT *key, unsigned int flags) PORT_Assert(kdbLock != NULL); PZ_Lock(kdbLock); - ret = (* db->del)(db, key, flags); - + ret = (*db->del)(db, key, flags); + (void)PZ_Unlock(kdbLock); - return(ret); + return (ret); } static int @@ -2160,15 +2150,15 @@ keydb_Seq(NSSLOWKEYDBHandle *kdb, DBT *key, DBT *data, unsigned int flags) int ret; PRLock *kdbLock = kdb->lock; DB *db = kdb->db; - + PORT_Assert(kdbLock != NULL); PZ_Lock(kdbLock); - - ret = (* db->seq)(db, key, data, flags); + + ret = (*db->seq)(db, key, data, flags); (void)PZ_Unlock(kdbLock); - return(ret); + return (ret); } static void @@ -2180,15 +2170,15 @@ keydb_Close(NSSLOWKEYDBHandle *kdb) PORT_Assert(kdbLock != NULL); SKIP_AFTER_FORK(PZ_Lock(kdbLock)); - (* db->close)(db); - + (*db->close)(db); + SKIP_AFTER_FORK(PZ_Unlock(kdbLock)); return; } /* - * SDB Entry Points for the Key DB + * SDB Entry Points for the Key DB */ CK_RV @@ -2202,9 +2192,9 @@ lg_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2) if (keydb == NULL) { return CKR_TOKEN_WRITE_PROTECTED; } - if (PORT_Strcmp(id,"password") != 0) { - /* shouldn't happen */ - return CKR_GENERAL_ERROR; /* no extra data stored */ + if (PORT_Strcmp(id, "password") != 0) { + /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* no extra data stored */ } rv = nsslowkey_GetPWCheckEntry(keydb, &entry); if (rv != SECSuccess) { @@ -2218,8 +2208,8 @@ lg_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2) } CK_RV -lg_PutMetaData(SDB *sdb, const char *id, - const SECItem *item1, const SECItem *item2) +lg_PutMetaData(SDB *sdb, const char *id, + const SECItem *item1, const SECItem *item2) { NSSLOWKEYDBHandle *keydb; NSSLOWKEYPasswordEntry entry; @@ -2229,9 +2219,9 @@ lg_PutMetaData(SDB *sdb, const char *id, if (keydb == NULL) { return CKR_TOKEN_WRITE_PROTECTED; } - if (PORT_Strcmp(id,"password") != 0) { - /* shouldn't happen */ - return CKR_GENERAL_ERROR; /* no extra data stored */ + if (PORT_Strcmp(id, "password") != 0) { + /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* no extra data stored */ } entry.salt = *item1; entry.value = *item2; @@ -2258,4 +2248,3 @@ lg_Reset(SDB *sdb) } return CKR_OK; } - diff --git a/nss/lib/softoken/legacydb/keydbi.h b/nss/lib/softoken/legacydb/keydbi.h index 924bd71..783c98e 100644 --- a/nss/lib/softoken/legacydb/keydbi.h +++ b/nss/lib/softoken/legacydb/keydbi.h @@ -17,36 +17,35 @@ */ struct NSSLOWKEYDBHandleStr { DB *db; - DB *updatedb; /* used when updating an old version */ - SECItem *global_salt; /* password hashing salt for this db */ - int version; /* version of the database */ - char *appname; /* multiaccess app name */ - char *dbname; /* name of the openned DB */ - PRBool readOnly; /* is the DB read only */ + DB *updatedb; /* used when updating an old version */ + SECItem *global_salt; /* password hashing salt for this db */ + int version; /* version of the database */ + char *appname; /* multiaccess app name */ + char *dbname; /* name of the openned DB */ + PRBool readOnly; /* is the DB read only */ PRLock *lock; - PRInt32 ref; /* reference count */ + PRInt32 ref; /* reference count */ }; /* ** Typedef for callback for traversing key database. ** "key" is the key used to index the data in the database (nickname) ** "data" is the key data -** "pdata" is the user's data +** "pdata" is the user's data */ -typedef SECStatus (* NSSLOWKEYTraverseKeysFunc)(DBT *key, DBT *data, void *pdata); - +typedef SECStatus (*NSSLOWKEYTraverseKeysFunc)(DBT *key, DBT *data, void *pdata); SEC_BEGIN_PROTOS /* -** Traverse the entire key database, and pass the nicknames and keys to a +** Traverse the entire key database, and pass the nicknames and keys to a ** user supplied function. ** "f" is the user function to call for each key ** "udata" is the user's data, which is passed through to "f" */ -extern SECStatus nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, - NSSLOWKEYTraverseKeysFunc f, - void *udata); +extern SECStatus nsslowkey_TraverseKeys(NSSLOWKEYDBHandle *handle, + NSSLOWKEYTraverseKeysFunc f, + void *udata); SEC_END_PROTOS diff --git a/nss/lib/softoken/legacydb/legacydb.gyp b/nss/lib/softoken/legacydb/legacydb.gyp new file mode 100644 index 0000000..6431fb5 --- /dev/null +++ b/nss/lib/softoken/legacydb/legacydb.gyp @@ -0,0 +1,66 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +{ + 'includes': [ + '../../../coreconf/config.gypi' + ], + 'targets': [ + { + 'target_name': 'nssdbm', + 'type': 'static_library', + 'sources': [ + 'dbmshim.c', + 'keydb.c', + 'lgattr.c', + 'lgcreate.c', + 'lgdestroy.c', + 'lgfind.c', + 'lgfips.c', + 'lginit.c', + 'lgutil.c', + 'lowcert.c', + 'lowkey.c', + 'pcertdb.c', + 'pk11db.c' + ], + 'dependencies': [ + '<(DEPTH)/exports.gyp:dbm_exports', + '<(DEPTH)/exports.gyp:nss_exports', + '<(DEPTH)/lib/freebl/freebl.gyp:freebl', + '<(DEPTH)/lib/dbm/src/src.gyp:dbm' + ] + }, + { + 'target_name': 'nssdbm3', + 'type': 'shared_library', + 'dependencies': [ + 'nssdbm' + ], + 'conditions': [ + [ 'moz_fold_libs==0', { + 'dependencies': [ + '<(DEPTH)/lib/util/util.gyp:nssutil3', + ], + }, { + 'libraries': [ + '<(moz_folded_library_name)', + ], + }], + ], + 'variables': { + 'mapfile': 'nssdbm.def' + } + } + ], + 'target_defaults': { + 'defines': [ + 'SHLIB_SUFFIX=\"<(dll_suffix)\"', + 'SHLIB_PREFIX=\"<(dll_prefix)\"', + 'LG_LIB_NAME=\"libnssdbm3.so\"' + ] + }, + 'variables': { + 'module': 'nss' + } +} diff --git a/nss/lib/softoken/legacydb/lgattr.c b/nss/lib/softoken/legacydb/lgattr.c index 429ef87..5c2cbdb 100644 --- a/nss/lib/softoken/legacydb/lgattr.c +++ b/nss/lib/softoken/legacydb/lgattr.c @@ -18,22 +18,22 @@ * Cache the object we are working on during Set's and Get's */ typedef struct LGObjectCacheStr { - CK_OBJECT_CLASS objclass; + CK_OBJECT_CLASS objclass; CK_OBJECT_HANDLE handle; - SDB *sdb; - void *objectInfo; - LGFreeFunc infoFree; - SECItem dbKey; + SDB *sdb; + void *objectInfo; + LGFreeFunc infoFree; + SECItem dbKey; } LGObjectCache; static const CK_OBJECT_HANDLE lg_classArray[] = { 0, CKO_PRIVATE_KEY, CKO_PUBLIC_KEY, CKO_SECRET_KEY, CKO_NSS_TRUST, CKO_NSS_CRL, CKO_NSS_SMIME, - CKO_CERTIFICATE }; + CKO_CERTIFICATE +}; #define handleToClass(handle) \ - lg_classArray[((handle & LG_TOKEN_TYPE_MASK))>>LG_TOKEN_TYPE_SHIFT] - + lg_classArray[((handle & LG_TOKEN_TYPE_MASK)) >> LG_TOKEN_TYPE_SHIFT] static void lg_DestroyObjectCache(LGObjectCache *obj); @@ -45,7 +45,7 @@ lg_NewObjectCache(SDB *sdb, const SECItem *dbKey, CK_OBJECT_HANDLE handle) obj = PORT_New(LGObjectCache); if (obj == NULL) { - return NULL; + return NULL; } obj->objclass = handleToClass(handle); @@ -57,25 +57,22 @@ lg_NewObjectCache(SDB *sdb, const SECItem *dbKey, CK_OBJECT_HANDLE handle) obj->dbKey.len = 0; lg_DBLock(sdb); if (dbKey == NULL) { - dbKey = lg_lookupTokenKeyByHandle(sdb,handle); + dbKey = lg_lookupTokenKeyByHandle(sdb, handle); } if (dbKey == NULL) { - lg_DBUnlock(sdb); - goto loser; + lg_DBUnlock(sdb); + goto loser; } - rv = SECITEM_CopyItem(NULL,&obj->dbKey,dbKey); + rv = SECITEM_CopyItem(NULL, &obj->dbKey, dbKey); lg_DBUnlock(sdb); if (rv != SECSuccess) { - goto loser; + goto loser; } return obj; loser: - if (obj) { - (void) lg_DestroyObjectCache(obj); - } + (void)lg_DestroyObjectCache(obj); return NULL; - } /* @@ -86,13 +83,13 @@ static void lg_DestroyObjectCache(LGObjectCache *obj) { if (obj->dbKey.data) { - PORT_Free(obj->dbKey.data); - obj->dbKey.data = NULL; - } + PORT_Free(obj->dbKey.data); + obj->dbKey.data = NULL; + } if (obj->objectInfo) { - (*obj->infoFree)(obj->objectInfo); - obj->objectInfo = NULL; - obj->infoFree = NULL; + (*obj->infoFree)(obj->objectInfo); + obj->objectInfo = NULL; + obj->infoFree = NULL; } PORT_Free(obj); } @@ -107,55 +104,57 @@ lg_ULongAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE_TYPE type, CK_ULONG value) int i; if (attr->pValue == NULL) { - attr->ulValueLen = 4; - return CKR_OK; + attr->ulValueLen = 4; + return CKR_OK; } if (attr->ulValueLen < 4) { - attr->ulValueLen = (CK_ULONG) -1; - return CKR_BUFFER_TOO_SMALL; + attr->ulValueLen = (CK_ULONG)-1; + return CKR_BUFFER_TOO_SMALL; } data = (unsigned char *)attr->pValue; - for (i=0; i < 4; i++) { - data[i] = (value >> ((3-i)*8)) & 0xff; + for (i = 0; i < 4; i++) { + data[i] = (value >> ((3 - i) * 8)) & 0xff; } attr->ulValueLen = 4; return CKR_OK; } static CK_RV -lg_CopyAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE_TYPE type, - CK_VOID_PTR value, CK_ULONG len) +lg_CopyAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE_TYPE type, + CK_VOID_PTR value, CK_ULONG len) { if (attr->pValue == NULL) { - attr->ulValueLen = len; - return CKR_OK; + attr->ulValueLen = len; + return CKR_OK; } if (attr->ulValueLen < len) { - attr->ulValueLen = (CK_ULONG) -1; - return CKR_BUFFER_TOO_SMALL; + attr->ulValueLen = (CK_ULONG)-1; + return CKR_BUFFER_TOO_SMALL; + } + if (value != NULL) { + PORT_Memcpy(attr->pValue, value, len); } - PORT_Memcpy(attr->pValue,value,len); attr->ulValueLen = len; return CKR_OK; } static CK_RV -lg_CopyAttributeSigned(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, - void *value, CK_ULONG len) +lg_CopyAttributeSigned(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, + void *value, CK_ULONG len) { - unsigned char * dval = (unsigned char *)value; + unsigned char *dval = (unsigned char *)value; if (*dval == 0) { - dval++; - len--; + dval++; + len--; } - return lg_CopyAttribute(attribute,type,dval,len); + return lg_CopyAttribute(attribute, type, dval, len); } static CK_RV -lg_CopyPrivAttribute(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, - void *value, CK_ULONG len, SDB *sdbpw) +lg_CopyPrivAttribute(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, + void *value, CK_ULONG len, SDB *sdbpw) { SECItem plainText, *cipherText = NULL; CK_RV crv = CKR_USER_NOT_LOGGED_IN; @@ -165,86 +164,86 @@ lg_CopyPrivAttribute(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, plainText.len = len; rv = lg_util_encrypt(NULL, sdbpw, &plainText, &cipherText); if (rv != SECSuccess) { - goto loser; + goto loser; } - crv = lg_CopyAttribute(attribute,type,cipherText->data,cipherText->len); + crv = lg_CopyAttribute(attribute, type, cipherText->data, cipherText->len); loser: if (cipherText) { - SECITEM_FreeItem(cipherText,PR_TRUE); + SECITEM_FreeItem(cipherText, PR_TRUE); } return crv; } static CK_RV -lg_CopyPrivAttrSigned(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, - void *value, CK_ULONG len, SDB *sdbpw) +lg_CopyPrivAttrSigned(CK_ATTRIBUTE *attribute, CK_ATTRIBUTE_TYPE type, + void *value, CK_ULONG len, SDB *sdbpw) { - unsigned char * dval = (unsigned char *)value; + unsigned char *dval = (unsigned char *)value; if (*dval == 0) { - dval++; - len--; + dval++; + len--; } - return lg_CopyPrivAttribute(attribute,type,dval,len,sdbpw); + return lg_CopyPrivAttribute(attribute, type, dval, len, sdbpw); } static CK_RV lg_invalidAttribute(CK_ATTRIBUTE *attr) { - attr->ulValueLen = (CK_ULONG) -1; + attr->ulValueLen = (CK_ULONG)-1; return CKR_ATTRIBUTE_TYPE_INVALID; } - -#define LG_DEF_ATTRIBUTE(value,len) \ - { 0, value, len } +#define LG_DEF_ATTRIBUTE(value, len) \ + { \ + 0, value, len \ + } #define LG_CLONE_ATTR(attribute, type, staticAttr) \ lg_CopyAttribute(attribute, type, staticAttr.pValue, staticAttr.ulValueLen) CK_BBOOL lg_staticTrueValue = CK_TRUE; CK_BBOOL lg_staticFalseValue = CK_FALSE; -static const CK_ATTRIBUTE lg_StaticTrueAttr = - LG_DEF_ATTRIBUTE(&lg_staticTrueValue,sizeof(lg_staticTrueValue)); -static const CK_ATTRIBUTE lg_StaticFalseAttr = - LG_DEF_ATTRIBUTE(&lg_staticFalseValue,sizeof(lg_staticFalseValue)); -static const CK_ATTRIBUTE lg_StaticNullAttr = LG_DEF_ATTRIBUTE(NULL,0); +static const CK_ATTRIBUTE lg_StaticTrueAttr = + LG_DEF_ATTRIBUTE(&lg_staticTrueValue, sizeof(lg_staticTrueValue)); +static const CK_ATTRIBUTE lg_StaticFalseAttr = + LG_DEF_ATTRIBUTE(&lg_staticFalseValue, sizeof(lg_staticFalseValue)); +static const CK_ATTRIBUTE lg_StaticNullAttr = LG_DEF_ATTRIBUTE(NULL, 0); char lg_StaticOneValue = 1; /* - * helper functions which get the database and call the underlying + * helper functions which get the database and call the underlying * low level database function. */ static char * lg_FindKeyNicknameByPublicKey(SDB *sdb, SECItem *dbKey) { NSSLOWKEYDBHandle *keyHandle; - char * label; + char *label; keyHandle = lg_getKeyDB(sdb); if (!keyHandle) { - return NULL; + return NULL; } - label = nsslowkey_FindKeyNicknameByPublicKey(keyHandle, dbKey, - sdb); + label = nsslowkey_FindKeyNicknameByPublicKey(keyHandle, dbKey, + sdb); return label; } - NSSLOWKEYPrivateKey * lg_FindKeyByPublicKey(SDB *sdb, SECItem *dbKey) { NSSLOWKEYPrivateKey *privKey; - NSSLOWKEYDBHandle *keyHandle; + NSSLOWKEYDBHandle *keyHandle; keyHandle = lg_getKeyDB(sdb); if (keyHandle == NULL) { - return NULL; + return NULL; } privKey = nsslowkey_FindKeyByPublicKey(keyHandle, dbKey, sdb); if (privKey == NULL) { - return NULL; + return NULL; } return privKey; } @@ -256,19 +255,19 @@ lg_getSMime(LGObjectCache *obj) NSSLOWCERTCertDBHandle *certHandle; if (obj->objclass != CKO_NSS_SMIME) { - return NULL; + return NULL; } if (obj->objectInfo) { - return (certDBEntrySMime *)obj->objectInfo; + return (certDBEntrySMime *)obj->objectInfo; } certHandle = lg_getCertDB(obj->sdb); if (!certHandle) { - return NULL; + return NULL; } entry = nsslowcert_ReadDBSMimeEntry(certHandle, (char *)obj->dbKey.data); obj->objectInfo = (void *)entry; - obj->infoFree = (LGFreeFunc) nsslowcert_DestroyDBEntry; + obj->infoFree = (LGFreeFunc)nsslowcert_DestroyDBEntry; return entry; } @@ -280,21 +279,21 @@ lg_getCrl(LGObjectCache *obj) NSSLOWCERTCertDBHandle *certHandle; if (obj->objclass != CKO_NSS_CRL) { - return NULL; + return NULL; } if (obj->objectInfo) { - return (certDBEntryRevocation *)obj->objectInfo; + return (certDBEntryRevocation *)obj->objectInfo; } - isKrl = (PRBool) (obj->handle == LG_TOKEN_KRL_HANDLE); + isKrl = (PRBool)(obj->handle == LG_TOKEN_KRL_HANDLE); certHandle = lg_getCertDB(obj->sdb); if (!certHandle) { - return NULL; + return NULL; } crl = nsslowcert_FindCrlByKey(certHandle, &obj->dbKey, isKrl); obj->objectInfo = (void *)crl; - obj->infoFree = (LGFreeFunc) nsslowcert_DestroyDBEntry; + obj->infoFree = (LGFreeFunc)nsslowcert_DestroyDBEntry; return crl; } @@ -305,15 +304,15 @@ lg_getCert(LGObjectCache *obj, NSSLOWCERTCertDBHandle *certHandle) CK_OBJECT_CLASS objClass = obj->objclass; if ((objClass != CKO_CERTIFICATE) && (objClass != CKO_NSS_TRUST)) { - return NULL; + return NULL; } if (objClass == CKO_CERTIFICATE && obj->objectInfo) { - return (NSSLOWCERTCertificate *)obj->objectInfo; + return (NSSLOWCERTCertificate *)obj->objectInfo; } cert = nsslowcert_FindCertByKey(certHandle, &obj->dbKey); if (objClass == CKO_CERTIFICATE) { - obj->objectInfo = (void *)cert; - obj->infoFree = (LGFreeFunc) nsslowcert_DestroyCertificate ; + obj->objectInfo = (void *)cert; + obj->infoFree = (LGFreeFunc)nsslowcert_DestroyCertificate; } return cert; } @@ -324,14 +323,14 @@ lg_getTrust(LGObjectCache *obj, NSSLOWCERTCertDBHandle *certHandle) NSSLOWCERTTrust *trust; if (obj->objclass != CKO_NSS_TRUST) { - return NULL; + return NULL; } if (obj->objectInfo) { - return (NSSLOWCERTTrust *)obj->objectInfo; + return (NSSLOWCERTTrust *)obj->objectInfo; } trust = nsslowcert_FindTrustByKey(certHandle, &obj->dbKey); obj->objectInfo = (void *)trust; - obj->infoFree = (LGFreeFunc) nsslowcert_DestroyTrust ; + obj->infoFree = (LGFreeFunc)nsslowcert_DestroyTrust; return trust; } @@ -342,26 +341,26 @@ lg_GetPublicKey(LGObjectCache *obj) NSSLOWKEYPrivateKey *privKey; if (obj->objclass != CKO_PUBLIC_KEY) { - return NULL; + return NULL; } if (obj->objectInfo) { - return (NSSLOWKEYPublicKey *)obj->objectInfo; + return (NSSLOWKEYPublicKey *)obj->objectInfo; } privKey = lg_FindKeyByPublicKey(obj->sdb, &obj->dbKey); if (privKey == NULL) { - return NULL; + return NULL; } pubKey = lg_nsslowkey_ConvertToPublicKey(privKey); lg_nsslowkey_DestroyPrivateKey(privKey); - obj->objectInfo = (void *) pubKey; - obj->infoFree = (LGFreeFunc) lg_nsslowkey_DestroyPublicKey ; + obj->objectInfo = (void *)pubKey; + obj->infoFree = (LGFreeFunc)lg_nsslowkey_DestroyPublicKey; return pubKey; } /* - * we need two versions of lg_GetPrivateKey. One version that takes the + * we need two versions of lg_GetPrivateKey. One version that takes the * DB handle so we can pass the handle we have already acquired in, - * rather than going through the 'getKeyDB' code again, + * rather than going through the 'getKeyDB' code again, * which may fail the second time and another which just aquires * the key handle from the sdb (where we don't already have a key handle. * This version does the former. @@ -371,19 +370,19 @@ lg_GetPrivateKeyWithDB(LGObjectCache *obj, NSSLOWKEYDBHandle *keyHandle) { NSSLOWKEYPrivateKey *privKey; - if ((obj->objclass != CKO_PRIVATE_KEY) && - (obj->objclass != CKO_SECRET_KEY)) { - return NULL; + if ((obj->objclass != CKO_PRIVATE_KEY) && + (obj->objclass != CKO_SECRET_KEY)) { + return NULL; } if (obj->objectInfo) { - return (NSSLOWKEYPrivateKey *)obj->objectInfo; + return (NSSLOWKEYPrivateKey *)obj->objectInfo; } privKey = nsslowkey_FindKeyByPublicKey(keyHandle, &obj->dbKey, obj->sdb); if (privKey == NULL) { - return NULL; + return NULL; } - obj->objectInfo = (void *) privKey; - obj->infoFree = (LGFreeFunc) lg_nsslowkey_DestroyPrivateKey ; + obj->objectInfo = (void *)privKey; + obj->infoFree = (LGFreeFunc)lg_nsslowkey_DestroyPrivateKey; return privKey; } @@ -396,7 +395,7 @@ lg_GetPrivateKey(LGObjectCache *obj) keyHandle = lg_getKeyDB(obj->sdb); if (!keyHandle) { - return NULL; + return NULL; } privKey = lg_GetPrivateKeyWithDB(obj, keyHandle); return privKey; @@ -408,138 +407,139 @@ lg_GetPrivateKey(LGObjectCache *obj) * should include this comment. */ static SECItem * -lg_GetPubItem(NSSLOWKEYPublicKey *pubKey) { +lg_GetPubItem(NSSLOWKEYPublicKey *pubKey) +{ SECItem *pubItem = NULL; /* get value to compare from the cert's public key */ - switch ( pubKey->keyType ) { - case NSSLOWKEYRSAKey: - pubItem = &pubKey->u.rsa.modulus; - break; - case NSSLOWKEYDSAKey: - pubItem = &pubKey->u.dsa.publicValue; - break; - case NSSLOWKEYDHKey: - pubItem = &pubKey->u.dh.publicValue; - break; + switch (pubKey->keyType) { + case NSSLOWKEYRSAKey: + pubItem = &pubKey->u.rsa.modulus; + break; + case NSSLOWKEYDSAKey: + pubItem = &pubKey->u.dsa.publicValue; + break; + case NSSLOWKEYDHKey: + pubItem = &pubKey->u.dh.publicValue; + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - pubItem = &pubKey->u.ec.publicValue; - break; + case NSSLOWKEYECKey: + pubItem = &pubKey->u.ec.publicValue; + break; #endif /* NSS_DISABLE_ECC */ - default: - break; + default: + break; } return pubItem; } static CK_RV lg_FindRSAPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_RSA; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.rsa.modulus.data,key->u.rsa.modulus.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_MODULUS: - return lg_CopyAttributeSigned(attribute,type,key->u.rsa.modulus.data, - key->u.rsa.modulus.len); - case CKA_PUBLIC_EXPONENT: - return lg_CopyAttributeSigned(attribute, type, - key->u.rsa.publicExponent.data, - key->u.rsa.publicExponent.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.rsa.modulus.data, key->u.rsa.modulus.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_ENCRYPT: + case CKA_VERIFY: + case CKA_VERIFY_RECOVER: + case CKA_WRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_MODULUS: + return lg_CopyAttributeSigned(attribute, type, key->u.rsa.modulus.data, + key->u.rsa.modulus.len); + case CKA_PUBLIC_EXPONENT: + return lg_CopyAttributeSigned(attribute, type, + key->u.rsa.publicExponent.data, + key->u.rsa.publicExponent.len); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindDSAPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_DSA; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_VERIFY: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_VALUE: - return lg_CopyAttributeSigned(attribute,type, - key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - case CKA_PRIME: - return lg_CopyAttributeSigned(attribute,type, - key->u.dsa.params.prime.data, - key->u.dsa.params.prime.len); - case CKA_SUBPRIME: - return lg_CopyAttributeSigned(attribute,type, - key->u.dsa.params.subPrime.data, - key->u.dsa.params.subPrime.len); - case CKA_BASE: - return lg_CopyAttributeSigned(attribute,type, - key->u.dsa.params.base.data, - key->u.dsa.params.base.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.dsa.publicValue.data, + key->u.dsa.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + case CKA_ENCRYPT: + case CKA_VERIFY_RECOVER: + case CKA_WRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_VERIFY: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_VALUE: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.publicValue.data, + key->u.dsa.publicValue.len); + case CKA_PRIME: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.prime.data, + key->u.dsa.params.prime.len); + case CKA_SUBPRIME: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.subPrime.data, + key->u.dsa.params.subPrime.len); + case CKA_BASE: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.base.data, + key->u.dsa.params.base.len); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindDHPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_DH; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dh.publicValue.data,key->u.dh.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_VALUE: - return lg_CopyAttributeSigned(attribute,type, - key->u.dh.publicValue.data, - key->u.dh.publicValue.len); - case CKA_PRIME: - return lg_CopyAttributeSigned(attribute,type,key->u.dh.prime.data, - key->u.dh.prime.len); - case CKA_BASE: - return lg_CopyAttributeSigned(attribute,type,key->u.dh.base.data, - key->u.dh.base.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.dh.publicValue.data, key->u.dh.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_ENCRYPT: + case CKA_VERIFY: + case CKA_VERIFY_RECOVER: + case CKA_WRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_VALUE: + return lg_CopyAttributeSigned(attribute, type, + key->u.dh.publicValue.data, + key->u.dh.publicValue.len); + case CKA_PRIME: + return lg_CopyAttributeSigned(attribute, type, key->u.dh.prime.data, + key->u.dh.prime.len); + case CKA_BASE: + return lg_CopyAttributeSigned(attribute, type, key->u.dh.base.data, + key->u.dh.base.len); + default: + break; } return lg_invalidAttribute(attribute); } @@ -547,111 +547,110 @@ lg_FindDHPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type, #ifndef NSS_DISABLE_ECC static CK_RV lg_FindECPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_EC; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash, key->u.ec.publicValue.data, - key->u.ec.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - case CKA_VERIFY: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_ENCRYPT: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_EC_PARAMS: - return lg_CopyAttributeSigned(attribute,type, - key->u.ec.ecParams.DEREncoding.data, - key->u.ec.ecParams.DEREncoding.len); - case CKA_EC_POINT: - if (getenv("NSS_USE_DECODED_CKA_EC_POINT")) { - return lg_CopyAttributeSigned(attribute, type, - key->u.ec.publicValue.data, - key->u.ec.publicValue.len); - } else { - SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL, - &(key->u.ec.publicValue), - SEC_ASN1_GET(SEC_OctetStringTemplate)); - CK_RV crv; - if (!pubValue) { - return CKR_HOST_MEMORY; - } - crv = lg_CopyAttributeSigned(attribute, type, - pubValue->data, - pubValue->len); - SECITEM_FreeItem(pubValue, PR_TRUE); - return crv; - } - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.ec.publicValue.data, + key->u.ec.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + case CKA_VERIFY: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_ENCRYPT: + case CKA_VERIFY_RECOVER: + case CKA_WRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_EC_PARAMS: + return lg_CopyAttributeSigned(attribute, type, + key->u.ec.ecParams.DEREncoding.data, + key->u.ec.ecParams.DEREncoding.len); + case CKA_EC_POINT: + if (PR_GetEnvSecure("NSS_USE_DECODED_CKA_EC_POINT")) { + return lg_CopyAttributeSigned(attribute, type, + key->u.ec.publicValue.data, + key->u.ec.publicValue.len); + } else { + SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL, + &(key->u.ec.publicValue), + SEC_ASN1_GET(SEC_OctetStringTemplate)); + CK_RV crv; + if (!pubValue) { + return CKR_HOST_MEMORY; + } + crv = lg_CopyAttributeSigned(attribute, type, + pubValue->data, + pubValue->len); + SECITEM_FreeItem(pubValue, PR_TRUE); + return crv; + } + default: + break; } return lg_invalidAttribute(attribute); } #endif /* NSS_DISABLE_ECC */ - static CK_RV lg_FindPublicKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { - NSSLOWKEYPublicKey *key; + NSSLOWKEYPublicKey *key; CK_RV crv; char *label; switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_MODIFIABLE: - case CKA_EXTRACTABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_SUBJECT: - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_START_DATE: - case CKA_END_DATE: - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_LABEL: - label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); - if (label == NULL) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - crv = lg_CopyAttribute(attribute,type,label,PORT_Strlen(label)); - PORT_Free(label); - return crv; - default: - break; + case CKA_PRIVATE: + case CKA_SENSITIVE: + case CKA_ALWAYS_SENSITIVE: + case CKA_NEVER_EXTRACTABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_MODIFIABLE: + case CKA_EXTRACTABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_SUBJECT: + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_START_DATE: + case CKA_END_DATE: + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_LABEL: + label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); + if (label == NULL) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + crv = lg_CopyAttribute(attribute, type, label, PORT_Strlen(label)); + PORT_Free(label); + return crv; + default: + break; } key = lg_GetPublicKey(obj); if (key == NULL) { - if (type == CKA_ID) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - return CKR_OBJECT_HANDLE_INVALID; + if (type == CKA_ID) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + return CKR_OBJECT_HANDLE_INVALID; } switch (key->keyType) { - case NSSLOWKEYRSAKey: - return lg_FindRSAPublicKeyAttribute(key,type,attribute); - case NSSLOWKEYDSAKey: - return lg_FindDSAPublicKeyAttribute(key,type,attribute); - case NSSLOWKEYDHKey: - return lg_FindDHPublicKeyAttribute(key,type,attribute); + case NSSLOWKEYRSAKey: + return lg_FindRSAPublicKeyAttribute(key, type, attribute); + case NSSLOWKEYDSAKey: + return lg_FindDSAPublicKeyAttribute(key, type, attribute); + case NSSLOWKEYDHKey: + return lg_FindDHPublicKeyAttribute(key, type, attribute); #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - return lg_FindECPublicKeyAttribute(key,type,attribute); + case NSSLOWKEYECKey: + return lg_FindECPublicKeyAttribute(key, type, attribute); #endif /* NSS_DISABLE_ECC */ - default: - break; + default: + break; } return lg_invalidAttribute(attribute); @@ -659,9 +658,9 @@ lg_FindPublicKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, static CK_RV lg_FindSecretKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { - NSSLOWKEYPrivateKey *key; + NSSLOWKEYPrivateKey *key; char *label; unsigned char *keyString; CK_RV crv; @@ -671,269 +670,267 @@ lg_FindSecretKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, PRUint32 keyTypeStorage; switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_VERIFY: - case CKA_WRAP: - case CKA_UNWRAP: - case CKA_MODIFIABLE: - case CKA_LOCAL: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_NEVER_EXTRACTABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_START_DATE: - case CKA_END_DATE: - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_LABEL: - label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); - if (label == NULL) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - crv = lg_CopyAttribute(attribute,type,label,PORT_Strlen(label)); - PORT_Free(label); - return crv; - case CKA_ID: - return lg_CopyAttribute(attribute,type,obj->dbKey.data, - obj->dbKey.len); - case CKA_KEY_TYPE: - case CKA_VALUE_LEN: - case CKA_VALUE: - break; - default: - return lg_invalidAttribute(attribute); + case CKA_PRIVATE: + case CKA_SENSITIVE: + case CKA_ALWAYS_SENSITIVE: + case CKA_EXTRACTABLE: + case CKA_DERIVE: + case CKA_ENCRYPT: + case CKA_DECRYPT: + case CKA_SIGN: + case CKA_VERIFY: + case CKA_WRAP: + case CKA_UNWRAP: + case CKA_MODIFIABLE: + case CKA_LOCAL: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_NEVER_EXTRACTABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_START_DATE: + case CKA_END_DATE: + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_LABEL: + label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); + if (label == NULL) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + crv = lg_CopyAttribute(attribute, type, label, PORT_Strlen(label)); + PORT_Free(label); + return crv; + case CKA_ID: + return lg_CopyAttribute(attribute, type, obj->dbKey.data, + obj->dbKey.len); + case CKA_KEY_TYPE: + case CKA_VALUE_LEN: + case CKA_VALUE: + break; + default: + return lg_invalidAttribute(attribute); } key = lg_GetPrivateKey(obj); if (key == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (type) { - case CKA_KEY_TYPE: - /* handle legacy databases. In legacy databases key_type was stored - * in host order, with any leading zeros stripped off. Only key types - * under 0x1f (AES) were stored. We assume that any values which are - * either 1 byte long (big endian), or have byte[0] between 0 and - * 0x7f and bytes[1]-bytes[3] equal to '0' (little endian). All other - * values are assumed to be from the new database, which is always 4 - * bytes in network order */ - keyType=0; - keyString = key->u.rsa.coefficient.data; - keyTypeLen = key->u.rsa.coefficient.len; - - - /* - * Because of various endian and word lengths The database may have - * stored the keyType value in one of the following formats: - * (kt) <= 0x1f - * length data - * Big Endian, pre-3.9, all lengths: 1 (kt) - * Little Endian, pre-3.9, 32 bits: 4 (kt) 0 0 0 - * Little Endian, pre-3.9, 64 bits: 8 (kt) 0 0 0 0 0 0 0 - * All platforms, 3.9, 32 bits: 4 0 0 0 (kt) - * Big Endian, 3.9, 64 bits: 8 0 0 0 (kt) 0 0 0 0 - * Little Endian, 3.9, 64 bits: 8 0 0 0 0 0 0 0 (kt) - * All platforms, >= 3.9.1, all lengths: 4 (a) k1 k2 k3 - * where (a) is 0 or >= 0x80. currently (a) can only be 0. - */ - /* - * this key was written on a 64 bit platform with a using NSS 3.9 - * or earlier. Reduce the 64 bit possibilities above. When we are - * through, we will only have: - * - * Big Endian, pre-3.9, all lengths: 1 (kt) - * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 - * All platforms, 3.9, all lengths: 4 0 0 0 (kt) - * All platforms, => 3.9.1, all lengths: 4 (a) k1 k2 k3 - */ - if (keyTypeLen == 8) { - keyTypeStorage = *(PRUint32 *) keyString; - if (keyTypeStorage == 0) { - keyString += sizeof(PRUint32); - } - keyTypeLen = 4; - } - /* - * Now Handle: - * - * All platforms, 3.9, all lengths: 4 0 0 0 (kt) - * All platforms, => 3.9.1, all lengths: 4 (a) k1 k2 k3 - * - * NOTE: if kt == 0 or ak1k2k3 == 0, the test fails and - * we handle it as: - * - * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 - */ - if (keyTypeLen == sizeof(keyTypeStorage) && - (((keyString[0] & 0x80) == 0x80) || - !((keyString[1] == 0) && (keyString[2] == 0) - && (keyString[3] == 0))) ) { - PORT_Memcpy(&keyTypeStorage, keyString, sizeof(keyTypeStorage)); - keyType = (CK_KEY_TYPE) PR_ntohl(keyTypeStorage); - } else { - /* - * Now Handle: - * - * Big Endian, pre-3.9, all lengths: 1 (kt) - * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 - * -- KeyType == 0 all other cases ---: 4 0 0 0 0 - */ - keyType = (CK_KEY_TYPE) keyString[0] ; - } - return lg_ULongAttribute(attribute, type, keyType); - case CKA_VALUE: - return lg_CopyPrivAttribute(attribute,type,key->u.rsa.privateExponent.data, - key->u.rsa.privateExponent.len, obj->sdb); - case CKA_VALUE_LEN: - keyLen=key->u.rsa.privateExponent.len; - return lg_ULongAttribute(attribute,type, keyLen); + case CKA_KEY_TYPE: + /* handle legacy databases. In legacy databases key_type was stored + * in host order, with any leading zeros stripped off. Only key types + * under 0x1f (AES) were stored. We assume that any values which are + * either 1 byte long (big endian), or have byte[0] between 0 and + * 0x7f and bytes[1]-bytes[3] equal to '0' (little endian). All other + * values are assumed to be from the new database, which is always 4 + * bytes in network order */ + keyType = 0; + keyString = key->u.rsa.coefficient.data; + keyTypeLen = key->u.rsa.coefficient.len; + + /* + * Because of various endian and word lengths The database may have + * stored the keyType value in one of the following formats: + * (kt) <= 0x1f + * length data + * Big Endian, pre-3.9, all lengths: 1 (kt) + * Little Endian, pre-3.9, 32 bits: 4 (kt) 0 0 0 + * Little Endian, pre-3.9, 64 bits: 8 (kt) 0 0 0 0 0 0 0 + * All platforms, 3.9, 32 bits: 4 0 0 0 (kt) + * Big Endian, 3.9, 64 bits: 8 0 0 0 (kt) 0 0 0 0 + * Little Endian, 3.9, 64 bits: 8 0 0 0 0 0 0 0 (kt) + * All platforms, >= 3.9.1, all lengths: 4 (a) k1 k2 k3 + * where (a) is 0 or >= 0x80. currently (a) can only be 0. + */ + /* + * this key was written on a 64 bit platform with a using NSS 3.9 + * or earlier. Reduce the 64 bit possibilities above. When we are + * through, we will only have: + * + * Big Endian, pre-3.9, all lengths: 1 (kt) + * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 + * All platforms, 3.9, all lengths: 4 0 0 0 (kt) + * All platforms, => 3.9.1, all lengths: 4 (a) k1 k2 k3 + */ + if (keyTypeLen == 8) { + keyTypeStorage = *(PRUint32 *)keyString; + if (keyTypeStorage == 0) { + keyString += sizeof(PRUint32); + } + keyTypeLen = 4; + } + /* + * Now Handle: + * + * All platforms, 3.9, all lengths: 4 0 0 0 (kt) + * All platforms, => 3.9.1, all lengths: 4 (a) k1 k2 k3 + * + * NOTE: if kt == 0 or ak1k2k3 == 0, the test fails and + * we handle it as: + * + * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 + */ + if (keyTypeLen == sizeof(keyTypeStorage) && + (((keyString[0] & 0x80) == 0x80) || + !((keyString[1] == 0) && (keyString[2] == 0) && (keyString[3] == 0)))) { + PORT_Memcpy(&keyTypeStorage, keyString, sizeof(keyTypeStorage)); + keyType = (CK_KEY_TYPE)PR_ntohl(keyTypeStorage); + } else { + /* + * Now Handle: + * + * Big Endian, pre-3.9, all lengths: 1 (kt) + * Little Endian, pre-3.9, all lengths: 4 (kt) 0 0 0 + * -- KeyType == 0 all other cases ---: 4 0 0 0 0 + */ + keyType = (CK_KEY_TYPE)keyString[0]; + } + return lg_ULongAttribute(attribute, type, keyType); + case CKA_VALUE: + return lg_CopyPrivAttribute(attribute, type, key->u.rsa.privateExponent.data, + key->u.rsa.privateExponent.len, obj->sdb); + case CKA_VALUE_LEN: + keyLen = key->u.rsa.privateExponent.len; + return lg_ULongAttribute(attribute, type, keyLen); } return lg_invalidAttribute(attribute); } static CK_RV lg_FindRSAPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute, SDB *sdbpw) + CK_ATTRIBUTE *attribute, SDB *sdbpw) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_RSA; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.rsa.modulus.data,key->u.rsa.modulus.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return LG_CLONE_ATTR(attribute, type,lg_StaticTrueAttr); - case CKA_MODULUS: - return lg_CopyAttributeSigned(attribute,type,key->u.rsa.modulus.data, - key->u.rsa.modulus.len); - case CKA_PUBLIC_EXPONENT: - return lg_CopyAttributeSigned(attribute, type, - key->u.rsa.publicExponent.data, - key->u.rsa.publicExponent.len); - case CKA_PRIVATE_EXPONENT: - return lg_CopyPrivAttrSigned(attribute,type, - key->u.rsa.privateExponent.data, - key->u.rsa.privateExponent.len, sdbpw); - case CKA_PRIME_1: - return lg_CopyPrivAttrSigned(attribute, type, key->u.rsa.prime1.data, - key->u.rsa.prime1.len, sdbpw); - case CKA_PRIME_2: - return lg_CopyPrivAttrSigned(attribute, type, key->u.rsa.prime2.data, - key->u.rsa.prime2.len, sdbpw); - case CKA_EXPONENT_1: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.rsa.exponent1.data, - key->u.rsa.exponent1.len, sdbpw); - case CKA_EXPONENT_2: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.rsa.exponent2.data, - key->u.rsa.exponent2.len, sdbpw); - case CKA_COEFFICIENT: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.rsa.coefficient.data, - key->u.rsa.coefficient.len, sdbpw); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.rsa.modulus.data, key->u.rsa.modulus.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_DECRYPT: + case CKA_SIGN: + case CKA_SIGN_RECOVER: + case CKA_UNWRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_MODULUS: + return lg_CopyAttributeSigned(attribute, type, key->u.rsa.modulus.data, + key->u.rsa.modulus.len); + case CKA_PUBLIC_EXPONENT: + return lg_CopyAttributeSigned(attribute, type, + key->u.rsa.publicExponent.data, + key->u.rsa.publicExponent.len); + case CKA_PRIVATE_EXPONENT: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.rsa.privateExponent.data, + key->u.rsa.privateExponent.len, sdbpw); + case CKA_PRIME_1: + return lg_CopyPrivAttrSigned(attribute, type, key->u.rsa.prime1.data, + key->u.rsa.prime1.len, sdbpw); + case CKA_PRIME_2: + return lg_CopyPrivAttrSigned(attribute, type, key->u.rsa.prime2.data, + key->u.rsa.prime2.len, sdbpw); + case CKA_EXPONENT_1: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.rsa.exponent1.data, + key->u.rsa.exponent1.len, sdbpw); + case CKA_EXPONENT_2: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.rsa.exponent2.data, + key->u.rsa.exponent2.len, sdbpw); + case CKA_COEFFICIENT: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.rsa.coefficient.data, + key->u.rsa.coefficient.len, sdbpw); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindDSAPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute, SDB *sdbpw) + CK_ATTRIBUTE *attribute, SDB *sdbpw) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_DSA; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - case CKA_DECRYPT: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_SIGN: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_VALUE: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.dsa.privateValue.data, - key->u.dsa.privateValue.len, sdbpw); - case CKA_PRIME: - return lg_CopyAttributeSigned(attribute, type, - key->u.dsa.params.prime.data, - key->u.dsa.params.prime.len); - case CKA_SUBPRIME: - return lg_CopyAttributeSigned(attribute, type, - key->u.dsa.params.subPrime.data, - key->u.dsa.params.subPrime.len); - case CKA_BASE: - return lg_CopyAttributeSigned(attribute, type, - key->u.dsa.params.base.data, - key->u.dsa.params.base.len); - case CKA_NETSCAPE_DB: - return lg_CopyAttributeSigned(attribute, type, - key->u.dsa.publicValue.data, - key->u.dsa.publicValue.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.dsa.publicValue.data, + key->u.dsa.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + case CKA_DECRYPT: + case CKA_SIGN_RECOVER: + case CKA_UNWRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_SIGN: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_VALUE: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.dsa.privateValue.data, + key->u.dsa.privateValue.len, sdbpw); + case CKA_PRIME: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.prime.data, + key->u.dsa.params.prime.len); + case CKA_SUBPRIME: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.subPrime.data, + key->u.dsa.params.subPrime.len); + case CKA_BASE: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.params.base.data, + key->u.dsa.params.base.len); + case CKA_NETSCAPE_DB: + return lg_CopyAttributeSigned(attribute, type, + key->u.dsa.publicValue.data, + key->u.dsa.publicValue.len); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindDHPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute, SDB *sdbpw) + CK_ATTRIBUTE *attribute, SDB *sdbpw) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_DH; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.dh.publicValue.data,key->u.dh.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_VALUE: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.dh.privateValue.data, - key->u.dh.privateValue.len, sdbpw); - case CKA_PRIME: - return lg_CopyAttributeSigned(attribute, type, key->u.dh.prime.data, - key->u.dh.prime.len); - case CKA_BASE: - return lg_CopyAttributeSigned(attribute, type, key->u.dh.base.data, - key->u.dh.base.len); - case CKA_NETSCAPE_DB: - return lg_CopyAttributeSigned(attribute, type, - key->u.dh.publicValue.data, - key->u.dh.publicValue.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.dh.publicValue.data, key->u.dh.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_DECRYPT: + case CKA_SIGN: + case CKA_SIGN_RECOVER: + case CKA_UNWRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_VALUE: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.dh.privateValue.data, + key->u.dh.privateValue.len, sdbpw); + case CKA_PRIME: + return lg_CopyAttributeSigned(attribute, type, key->u.dh.prime.data, + key->u.dh.prime.len); + case CKA_BASE: + return lg_CopyAttributeSigned(attribute, type, key->u.dh.base.data, + key->u.dh.base.len); + case CKA_NETSCAPE_DB: + return lg_CopyAttributeSigned(attribute, type, + key->u.dh.publicValue.data, + key->u.dh.publicValue.len); + default: + break; } return lg_invalidAttribute(attribute); } @@ -941,38 +938,38 @@ lg_FindDHPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, #ifndef NSS_DISABLE_ECC static CK_RV lg_FindECPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute, SDB *sdbpw) + CK_ATTRIBUTE *attribute, SDB *sdbpw) { unsigned char hash[SHA1_LENGTH]; CK_KEY_TYPE keyType = CKK_EC; switch (type) { - case CKA_KEY_TYPE: - return lg_ULongAttribute(attribute, type, keyType); - case CKA_ID: - SHA1_HashBuf(hash,key->u.ec.publicValue.data,key->u.ec.publicValue.len); - return lg_CopyAttribute(attribute,type,hash,SHA1_LENGTH); - case CKA_DERIVE: - case CKA_SIGN: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_DECRYPT: - case CKA_SIGN_RECOVER: - case CKA_UNWRAP: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_VALUE: - return lg_CopyPrivAttrSigned(attribute, type, - key->u.ec.privateValue.data, - key->u.ec.privateValue.len, sdbpw); - case CKA_EC_PARAMS: - return lg_CopyAttributeSigned(attribute, type, - key->u.ec.ecParams.DEREncoding.data, - key->u.ec.ecParams.DEREncoding.len); - case CKA_NETSCAPE_DB: - return lg_CopyAttributeSigned(attribute, type, - key->u.ec.publicValue.data, - key->u.ec.publicValue.len); - default: - break; + case CKA_KEY_TYPE: + return lg_ULongAttribute(attribute, type, keyType); + case CKA_ID: + SHA1_HashBuf(hash, key->u.ec.publicValue.data, key->u.ec.publicValue.len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_DERIVE: + case CKA_SIGN: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_DECRYPT: + case CKA_SIGN_RECOVER: + case CKA_UNWRAP: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_VALUE: + return lg_CopyPrivAttrSigned(attribute, type, + key->u.ec.privateValue.data, + key->u.ec.privateValue.len, sdbpw); + case CKA_EC_PARAMS: + return lg_CopyAttributeSigned(attribute, type, + key->u.ec.ecParams.DEREncoding.data, + key->u.ec.ecParams.DEREncoding.len); + case CKA_NETSCAPE_DB: + return lg_CopyAttributeSigned(attribute, type, + key->u.ec.publicValue.data, + key->u.ec.publicValue.len); + default: + break; } return lg_invalidAttribute(attribute); } @@ -980,55 +977,55 @@ lg_FindECPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type, static CK_RV lg_FindPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { - NSSLOWKEYPrivateKey *key; + NSSLOWKEYPrivateKey *key; char *label; CK_RV crv; switch (type) { - case CKA_PRIVATE: - case CKA_SENSITIVE: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_MODIFIABLE: - case CKA_LOCAL: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_NEVER_EXTRACTABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_SUBJECT: - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_START_DATE: - case CKA_END_DATE: - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_LABEL: - label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); - if (label == NULL) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - crv = lg_CopyAttribute(attribute,type,label,PORT_Strlen(label)); - PORT_Free(label); - return crv; - default: - break; + case CKA_PRIVATE: + case CKA_SENSITIVE: + case CKA_ALWAYS_SENSITIVE: + case CKA_EXTRACTABLE: + case CKA_MODIFIABLE: + case CKA_LOCAL: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_NEVER_EXTRACTABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_SUBJECT: + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_START_DATE: + case CKA_END_DATE: + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_LABEL: + label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); + if (label == NULL) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + crv = lg_CopyAttribute(attribute, type, label, PORT_Strlen(label)); + PORT_Free(label); + return crv; + default: + break; } key = lg_GetPrivateKey(obj); if (key == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (key->keyType) { - case NSSLOWKEYRSAKey: - return lg_FindRSAPrivateKeyAttribute(key,type,attribute,obj->sdb); - case NSSLOWKEYDSAKey: - return lg_FindDSAPrivateKeyAttribute(key,type,attribute,obj->sdb); - case NSSLOWKEYDHKey: - return lg_FindDHPrivateKeyAttribute(key,type,attribute,obj->sdb); + case NSSLOWKEYRSAKey: + return lg_FindRSAPrivateKeyAttribute(key, type, attribute, obj->sdb); + case NSSLOWKEYDSAKey: + return lg_FindDSAPrivateKeyAttribute(key, type, attribute, obj->sdb); + case NSSLOWKEYDHKey: + return lg_FindDHPrivateKeyAttribute(key, type, attribute, obj->sdb); #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - return lg_FindECPrivateKeyAttribute(key,type,attribute,obj->sdb); + case NSSLOWKEYECKey: + return lg_FindECPrivateKeyAttribute(key, type, attribute, obj->sdb); #endif /* NSS_DISABLE_ECC */ - default: - break; + default: + break; } return lg_invalidAttribute(attribute); @@ -1036,46 +1033,46 @@ lg_FindPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, static CK_RV lg_FindSMIMEAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { certDBEntrySMime *entry; switch (type) { - case CKA_PRIVATE: - case CKA_MODIFIABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_NSS_EMAIL: - return lg_CopyAttribute(attribute,type,obj->dbKey.data, - obj->dbKey.len-1); - case CKA_NSS_SMIME_TIMESTAMP: - case CKA_SUBJECT: - case CKA_VALUE: - break; - default: - return lg_invalidAttribute(attribute); + case CKA_PRIVATE: + case CKA_MODIFIABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_NSS_EMAIL: + return lg_CopyAttribute(attribute, type, obj->dbKey.data, + obj->dbKey.len - 1); + case CKA_NSS_SMIME_TIMESTAMP: + case CKA_SUBJECT: + case CKA_VALUE: + break; + default: + return lg_invalidAttribute(attribute); } entry = lg_getSMime(obj); if (entry == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (type) { - case CKA_NSS_SMIME_TIMESTAMP: - return lg_CopyAttribute(attribute,type,entry->optionsDate.data, - entry->optionsDate.len); - case CKA_SUBJECT: - return lg_CopyAttribute(attribute,type,entry->subjectName.data, - entry->subjectName.len); - case CKA_VALUE: - return lg_CopyAttribute(attribute,type,entry->smimeOptions.data, - entry->smimeOptions.len); - default: - break; + case CKA_NSS_SMIME_TIMESTAMP: + return lg_CopyAttribute(attribute, type, entry->optionsDate.data, + entry->optionsDate.len); + case CKA_SUBJECT: + return lg_CopyAttribute(attribute, type, entry->subjectName.data, + entry->subjectName.len); + case CKA_VALUE: + return lg_CopyAttribute(attribute, type, entry->smimeOptions.data, + entry->smimeOptions.len); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindTrustAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { NSSLOWCERTTrust *trust; NSSLOWCERTCertDBHandle *certHandle; @@ -1085,231 +1082,235 @@ lg_FindTrustAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, CK_RV crv; switch (type) { - case CKA_PRIVATE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_MODIFIABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_CERT_SHA1_HASH: - case CKA_CERT_MD5_HASH: - case CKA_TRUST_CLIENT_AUTH: - case CKA_TRUST_SERVER_AUTH: - case CKA_TRUST_EMAIL_PROTECTION: - case CKA_TRUST_CODE_SIGNING: - case CKA_TRUST_STEP_UP_APPROVED: - case CKA_ISSUER: - case CKA_SERIAL_NUMBER: - break; - default: - return lg_invalidAttribute(attribute); + case CKA_PRIVATE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_MODIFIABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_CERT_SHA1_HASH: + case CKA_CERT_MD5_HASH: + case CKA_TRUST_CLIENT_AUTH: + case CKA_TRUST_SERVER_AUTH: + case CKA_TRUST_EMAIL_PROTECTION: + case CKA_TRUST_CODE_SIGNING: + case CKA_TRUST_STEP_UP_APPROVED: + case CKA_ISSUER: + case CKA_SERIAL_NUMBER: + break; + default: + return lg_invalidAttribute(attribute); } certHandle = lg_getCertDB(obj->sdb); if (!certHandle) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } trust = lg_getTrust(obj, certHandle); if (trust == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (type) { - case CKA_CERT_SHA1_HASH: - SHA1_HashBuf(hash,trust->derCert->data,trust->derCert->len); - return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); - case CKA_CERT_MD5_HASH: - MD5_HashBuf(hash,trust->derCert->data,trust->derCert->len); - return lg_CopyAttribute(attribute, type, hash, MD5_LENGTH); - case CKA_TRUST_CLIENT_AUTH: - trustFlags = trust->trust->sslFlags & CERTDB_TRUSTED_CLIENT_CA ? - trust->trust->sslFlags | CERTDB_TRUSTED_CA : 0 ; - goto trust; - case CKA_TRUST_SERVER_AUTH: - trustFlags = trust->trust->sslFlags; - goto trust; - case CKA_TRUST_EMAIL_PROTECTION: - trustFlags = trust->trust->emailFlags; - goto trust; - case CKA_TRUST_CODE_SIGNING: - trustFlags = trust->trust->objectSigningFlags; -trust: - if (trustFlags & CERTDB_TRUSTED_CA ) { - return lg_ULongAttribute(attribute, type, - CKT_NSS_TRUSTED_DELEGATOR); - } - if (trustFlags & CERTDB_TRUSTED) { - return lg_ULongAttribute(attribute, type, CKT_NSS_TRUSTED); - } - if (trustFlags & CERTDB_MUST_VERIFY) { - return lg_ULongAttribute(attribute, type, - CKT_NSS_MUST_VERIFY_TRUST); - } - if (trustFlags & CERTDB_TRUSTED_UNKNOWN) { - return lg_ULongAttribute(attribute, type, CKT_NSS_TRUST_UNKNOWN); - } - if (trustFlags & CERTDB_VALID_CA) { - return lg_ULongAttribute(attribute, type, CKT_NSS_VALID_DELEGATOR); - } - if (trustFlags & CERTDB_TERMINAL_RECORD) { - return lg_ULongAttribute(attribute, type, CKT_NSS_NOT_TRUSTED); - } - return lg_ULongAttribute(attribute, type, CKT_NSS_TRUST_UNKNOWN); - case CKA_TRUST_STEP_UP_APPROVED: - if (trust->trust->sslFlags & CERTDB_GOVT_APPROVED_CA) { - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - } else { - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - } - default: - break; + case CKA_CERT_SHA1_HASH: + SHA1_HashBuf(hash, trust->derCert->data, trust->derCert->len); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_CERT_MD5_HASH: + MD5_HashBuf(hash, trust->derCert->data, trust->derCert->len); + return lg_CopyAttribute(attribute, type, hash, MD5_LENGTH); + case CKA_TRUST_CLIENT_AUTH: + trustFlags = trust->trust->sslFlags & + CERTDB_TRUSTED_CLIENT_CA + ? trust->trust->sslFlags | CERTDB_TRUSTED_CA + : 0; + goto trust; + case CKA_TRUST_SERVER_AUTH: + trustFlags = trust->trust->sslFlags; + goto trust; + case CKA_TRUST_EMAIL_PROTECTION: + trustFlags = trust->trust->emailFlags; + goto trust; + case CKA_TRUST_CODE_SIGNING: + trustFlags = trust->trust->objectSigningFlags; + trust: + if (trustFlags & CERTDB_TRUSTED_CA) { + return lg_ULongAttribute(attribute, type, + CKT_NSS_TRUSTED_DELEGATOR); + } + if (trustFlags & CERTDB_TRUSTED) { + return lg_ULongAttribute(attribute, type, CKT_NSS_TRUSTED); + } + if (trustFlags & CERTDB_MUST_VERIFY) { + return lg_ULongAttribute(attribute, type, + CKT_NSS_MUST_VERIFY_TRUST); + } + if (trustFlags & CERTDB_TRUSTED_UNKNOWN) { + return lg_ULongAttribute(attribute, type, CKT_NSS_TRUST_UNKNOWN); + } + if (trustFlags & CERTDB_VALID_CA) { + return lg_ULongAttribute(attribute, type, CKT_NSS_VALID_DELEGATOR); + } + if (trustFlags & CERTDB_TERMINAL_RECORD) { + return lg_ULongAttribute(attribute, type, CKT_NSS_NOT_TRUSTED); + } + return lg_ULongAttribute(attribute, type, CKT_NSS_TRUST_UNKNOWN); + case CKA_TRUST_STEP_UP_APPROVED: + if (trust->trust->sslFlags & CERTDB_GOVT_APPROVED_CA) { + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + } else { + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + } + default: + break; } - switch (type) { - case CKA_ISSUER: - cert = lg_getCert(obj, certHandle); - if (cert == NULL) break; - crv = lg_CopyAttribute(attribute,type,cert->derIssuer.data, - cert->derIssuer.len); - break; - case CKA_SERIAL_NUMBER: - cert = lg_getCert(obj, certHandle); - if (cert == NULL) break; - crv = lg_CopyAttribute(attribute,type,cert->derSN.data, - cert->derSN.len); - break; - default: - cert = NULL; - break; + case CKA_ISSUER: + cert = lg_getCert(obj, certHandle); + if (cert == NULL) + break; + crv = lg_CopyAttribute(attribute, type, cert->derIssuer.data, + cert->derIssuer.len); + break; + case CKA_SERIAL_NUMBER: + cert = lg_getCert(obj, certHandle); + if (cert == NULL) + break; + crv = lg_CopyAttribute(attribute, type, cert->derSN.data, + cert->derSN.len); + break; + default: + cert = NULL; + break; } if (cert) { - nsslowcert_DestroyCertificate(cert); - return crv; + nsslowcert_DestroyCertificate(cert); + return crv; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindCrlAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { certDBEntryRevocation *crl; switch (type) { - case CKA_PRIVATE: - case CKA_MODIFIABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_NSS_KRL: - return ((obj->handle == LG_TOKEN_KRL_HANDLE) - ? LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr) - : LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr)); - case CKA_SUBJECT: - return lg_CopyAttribute(attribute,type,obj->dbKey.data, - obj->dbKey.len); - case CKA_NSS_URL: - case CKA_VALUE: - break; - default: - return lg_invalidAttribute(attribute); - } - crl = lg_getCrl(obj); + case CKA_PRIVATE: + case CKA_MODIFIABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_NSS_KRL: + return ((obj->handle == LG_TOKEN_KRL_HANDLE) + ? LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr) + : LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr)); + case CKA_SUBJECT: + return lg_CopyAttribute(attribute, type, obj->dbKey.data, + obj->dbKey.len); + case CKA_NSS_URL: + case CKA_VALUE: + break; + default: + return lg_invalidAttribute(attribute); + } + crl = lg_getCrl(obj); if (!crl) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (type) { - case CKA_NSS_URL: - if (crl->url == NULL) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - return lg_CopyAttribute(attribute, type, crl->url, - PORT_Strlen(crl->url)+1); - case CKA_VALUE: - return lg_CopyAttribute(attribute, type, crl->derCrl.data, - crl->derCrl.len); - default: - break; + case CKA_NSS_URL: + if (crl->url == NULL) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + return lg_CopyAttribute(attribute, type, crl->url, + PORT_Strlen(crl->url) + 1); + case CKA_VALUE: + return lg_CopyAttribute(attribute, type, crl->derCrl.data, + crl->derCrl.len); + default: + break; } return lg_invalidAttribute(attribute); } static CK_RV lg_FindCertAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *attribute) + CK_ATTRIBUTE *attribute) { - NSSLOWCERTCertificate *cert; + NSSLOWCERTCertificate *cert; NSSLOWCERTCertDBHandle *certHandle; - NSSLOWKEYPublicKey *pubKey; + NSSLOWKEYPublicKey *pubKey; unsigned char hash[SHA1_LENGTH]; SECItem *item; switch (type) { - case CKA_PRIVATE: - return LG_CLONE_ATTR(attribute,type,lg_StaticFalseAttr); - case CKA_MODIFIABLE: - return LG_CLONE_ATTR(attribute,type,lg_StaticTrueAttr); - case CKA_CERTIFICATE_TYPE: - /* hardcoding X.509 into here */ - return lg_ULongAttribute(attribute, type, CKC_X_509); - case CKA_VALUE: - case CKA_ID: - case CKA_LABEL: - case CKA_SUBJECT: - case CKA_ISSUER: - case CKA_SERIAL_NUMBER: - case CKA_NSS_EMAIL: - break; - default: - return lg_invalidAttribute(attribute); + case CKA_PRIVATE: + return LG_CLONE_ATTR(attribute, type, lg_StaticFalseAttr); + case CKA_MODIFIABLE: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_CERTIFICATE_TYPE: + /* hardcoding X.509 into here */ + return lg_ULongAttribute(attribute, type, CKC_X_509); + case CKA_VALUE: + case CKA_ID: + case CKA_LABEL: + case CKA_SUBJECT: + case CKA_ISSUER: + case CKA_SERIAL_NUMBER: + case CKA_NSS_EMAIL: + break; + default: + return lg_invalidAttribute(attribute); } certHandle = lg_getCertDB(obj->sdb); if (certHandle == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } cert = lg_getCert(obj, certHandle); if (cert == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } switch (type) { - case CKA_VALUE: - return lg_CopyAttribute(attribute,type,cert->derCert.data, - cert->derCert.len); - case CKA_ID: - if (((cert->trust->sslFlags & CERTDB_USER) == 0) && - ((cert->trust->emailFlags & CERTDB_USER) == 0) && - ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - } - pubKey = nsslowcert_ExtractPublicKey(cert); - if (pubKey == NULL) break; - item = lg_GetPubItem(pubKey); - if (item == NULL) { - lg_nsslowkey_DestroyPublicKey(pubKey); - break; - } - SHA1_HashBuf(hash,item->data,item->len); - /* item is imbedded in pubKey, just free the key */ - lg_nsslowkey_DestroyPublicKey(pubKey); - return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); - case CKA_LABEL: - return cert->nickname - ? lg_CopyAttribute(attribute, type, cert->nickname, - PORT_Strlen(cert->nickname)) - : LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - case CKA_SUBJECT: - return lg_CopyAttribute(attribute,type,cert->derSubject.data, - cert->derSubject.len); - case CKA_ISSUER: - return lg_CopyAttribute(attribute,type,cert->derIssuer.data, - cert->derIssuer.len); - case CKA_SERIAL_NUMBER: - return lg_CopyAttribute(attribute,type,cert->derSN.data, - cert->derSN.len); - case CKA_NSS_EMAIL: - return (cert->emailAddr && cert->emailAddr[0]) - ? lg_CopyAttribute(attribute, type, cert->emailAddr, - PORT_Strlen(cert->emailAddr)) - : LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - default: - break; + case CKA_VALUE: + return lg_CopyAttribute(attribute, type, cert->derCert.data, + cert->derCert.len); + case CKA_ID: + if (((cert->trust->sslFlags & CERTDB_USER) == 0) && + ((cert->trust->emailFlags & CERTDB_USER) == 0) && + ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + } + pubKey = nsslowcert_ExtractPublicKey(cert); + if (pubKey == NULL) + break; + item = lg_GetPubItem(pubKey); + if (item == NULL) { + lg_nsslowkey_DestroyPublicKey(pubKey); + break; + } + SHA1_HashBuf(hash, item->data, item->len); + /* item is imbedded in pubKey, just free the key */ + lg_nsslowkey_DestroyPublicKey(pubKey); + return lg_CopyAttribute(attribute, type, hash, SHA1_LENGTH); + case CKA_LABEL: + return cert->nickname + ? lg_CopyAttribute(attribute, type, cert->nickname, + PORT_Strlen(cert->nickname)) + : LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + case CKA_SUBJECT: + return lg_CopyAttribute(attribute, type, cert->derSubject.data, + cert->derSubject.len); + case CKA_ISSUER: + return lg_CopyAttribute(attribute, type, cert->derIssuer.data, + cert->derIssuer.len); + case CKA_SERIAL_NUMBER: + return lg_CopyAttribute(attribute, type, cert->derSN.data, + cert->derSN.len); + case CKA_NSS_EMAIL: + return (cert->emailAddr && cert->emailAddr[0]) + ? lg_CopyAttribute(attribute, type, cert->emailAddr, + PORT_Strlen(cert->emailAddr)) + : LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + default: + break; } return lg_invalidAttribute(attribute); } @@ -1320,60 +1321,61 @@ lg_GetSingleAttribute(LGObjectCache *obj, CK_ATTRIBUTE *attribute) /* handle the common ones */ CK_ATTRIBUTE_TYPE type = attribute->type; switch (type) { - case CKA_CLASS: - return lg_ULongAttribute(attribute,type,obj->objclass); - case CKA_TOKEN: - return LG_CLONE_ATTR(attribute, type,lg_StaticTrueAttr); - case CKA_LABEL: - if ( (obj->objclass == CKO_CERTIFICATE) - || (obj->objclass == CKO_PRIVATE_KEY) - || (obj->objclass == CKO_PUBLIC_KEY) - || (obj->objclass == CKO_SECRET_KEY)) { - break; - } - return LG_CLONE_ATTR(attribute,type,lg_StaticNullAttr); - default: - break; + case CKA_CLASS: + return lg_ULongAttribute(attribute, type, obj->objclass); + case CKA_TOKEN: + return LG_CLONE_ATTR(attribute, type, lg_StaticTrueAttr); + case CKA_LABEL: + if ((obj->objclass == CKO_CERTIFICATE) || + (obj->objclass == CKO_PRIVATE_KEY) || + (obj->objclass == CKO_PUBLIC_KEY) || + (obj->objclass == CKO_SECRET_KEY)) { + break; + } + return LG_CLONE_ATTR(attribute, type, lg_StaticNullAttr); + default: + break; } switch (obj->objclass) { - case CKO_CERTIFICATE: - return lg_FindCertAttribute(obj,type,attribute); - case CKO_NSS_CRL: - return lg_FindCrlAttribute(obj,type,attribute); - case CKO_NSS_TRUST: - return lg_FindTrustAttribute(obj,type,attribute); - case CKO_NSS_SMIME: - return lg_FindSMIMEAttribute(obj,type,attribute); - case CKO_PUBLIC_KEY: - return lg_FindPublicKeyAttribute(obj,type,attribute); - case CKO_PRIVATE_KEY: - return lg_FindPrivateKeyAttribute(obj,type,attribute); - case CKO_SECRET_KEY: - return lg_FindSecretKeyAttribute(obj,type,attribute); - default: - break; + case CKO_CERTIFICATE: + return lg_FindCertAttribute(obj, type, attribute); + case CKO_NSS_CRL: + return lg_FindCrlAttribute(obj, type, attribute); + case CKO_NSS_TRUST: + return lg_FindTrustAttribute(obj, type, attribute); + case CKO_NSS_SMIME: + return lg_FindSMIMEAttribute(obj, type, attribute); + case CKO_PUBLIC_KEY: + return lg_FindPublicKeyAttribute(obj, type, attribute); + case CKO_PRIVATE_KEY: + return lg_FindPrivateKeyAttribute(obj, type, attribute); + case CKO_SECRET_KEY: + return lg_FindSecretKeyAttribute(obj, type, attribute); + default: + break; } return lg_invalidAttribute(attribute); -} +} /* * Fill in the attribute template based on the data in the database. - */ + */ CK_RV -lg_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE handle, CK_ATTRIBUTE *templ, - CK_ULONG count) +lg_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE handle, CK_ATTRIBUTE *templ, + CK_ULONG count) { LGObjectCache *obj = lg_NewObjectCache(sdb, NULL, handle & ~LG_TOKEN_MASK); CK_RV crv, crvCollect = CKR_OK; unsigned int i; if (obj == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } - for (i=0; i < count; i++) { - crv = lg_GetSingleAttribute(obj, &templ[i]); - if (crvCollect == CKR_OK) crvCollect = crv; + for (i = 0; i < count; i++) { + crv = lg_GetSingleAttribute(obj, &templ[i]); + if (crvCollect == CKR_OK) + crvCollect = crv; } lg_DestroyObjectCache(obj); @@ -1399,45 +1401,47 @@ lg_cmpAttribute(LGObjectCache *obj, const CK_ATTRIBUTE *attribute) /* if we don't have enough space, malloc it */ if (attribute->ulValueLen > LG_BUF_SPACE) { - tempBuf = PORT_Alloc(attribute->ulValueLen); - if (!tempBuf) { - return PR_FALSE; - } - testAttr.pValue = tempBuf; + tempBuf = PORT_Alloc(attribute->ulValueLen); + if (!tempBuf) { + return PR_FALSE; + } + testAttr.pValue = tempBuf; } /* get the attribute */ crv = lg_GetSingleAttribute(obj, &testAttr); /* if the attribute was read OK, compare it */ - if ((crv != CKR_OK) || (attribute->ulValueLen != testAttr.ulValueLen) || - (PORT_Memcmp(attribute->pValue,testAttr.pValue,testAttr.ulValueLen)!= 0)){ - /* something didn't match, this isn't the object we are looking for */ - match = PR_FALSE; + if ((crv != CKR_OK) || + (attribute->pValue == NULL) || + (attribute->ulValueLen != testAttr.ulValueLen) || + (PORT_Memcmp(attribute->pValue, testAttr.pValue, testAttr.ulValueLen) != 0)) { + /* something didn't match, this isn't the object we are looking for */ + match = PR_FALSE; } /* free the buffer we may have allocated */ if (tempBuf) { - PORT_Free(tempBuf); + PORT_Free(tempBuf); } return match; } PRBool lg_tokenMatch(SDB *sdb, const SECItem *dbKey, CK_OBJECT_HANDLE class, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { PRBool match = PR_TRUE; LGObjectCache *obj = lg_NewObjectCache(sdb, dbKey, class); unsigned int i; if (obj == NULL) { - return PR_FALSE; + return PR_FALSE; } - for (i=0; i < count; i++) { - match = lg_cmpAttribute(obj, &templ[i]); - if (!match) { - break; - } + for (i = 0; i < count; i++) { + match = lg_cmpAttribute(obj, &templ[i]); + if (!match) { + break; + } } /* done looking, free up our cache */ @@ -1449,10 +1453,10 @@ lg_tokenMatch(SDB *sdb, const SECItem *dbKey, CK_OBJECT_HANDLE class, } static CK_RV -lg_SetCertAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len) +lg_SetCertAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len) { - NSSLOWCERTCertificate *cert; + NSSLOWCERTCertificate *cert; NSSLOWCERTCertDBHandle *certHandle; char *nickname = NULL; SECStatus rv; @@ -1461,77 +1465,77 @@ lg_SetCertAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, /* we can't change the EMAIL values, but let the * upper layers feel better about the fact we tried to set these */ if (type == CKA_NSS_EMAIL) { - return CKR_OK; + return CKR_OK; } certHandle = lg_getCertDB(obj->sdb); if (certHandle == NULL) { - crv = CKR_TOKEN_WRITE_PROTECTED; - goto done; + crv = CKR_TOKEN_WRITE_PROTECTED; + goto done; } - if ((type != CKA_LABEL) && (type != CKA_ID)) { - crv = CKR_ATTRIBUTE_READ_ONLY; - goto done; + if ((type != CKA_LABEL) && (type != CKA_ID)) { + crv = CKR_ATTRIBUTE_READ_ONLY; + goto done; } cert = lg_getCert(obj, certHandle); if (cert == NULL) { - crv = CKR_OBJECT_HANDLE_INVALID; - goto done; + crv = CKR_OBJECT_HANDLE_INVALID; + goto done; } /* if the app is trying to set CKA_ID, it's probably because it just * imported the key. Look to see if we need to set the CERTDB_USER bits. */ if (type == CKA_ID) { - if (((cert->trust->sslFlags & CERTDB_USER) == 0) && - ((cert->trust->emailFlags & CERTDB_USER) == 0) && - ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { - NSSLOWKEYDBHandle *keyHandle; - - keyHandle = lg_getKeyDB(obj->sdb); - if (keyHandle) { - if (nsslowkey_KeyForCertExists(keyHandle, cert)) { - NSSLOWCERTCertTrust trust = *cert->trust; - trust.sslFlags |= CERTDB_USER; - trust.emailFlags |= CERTDB_USER; - trust.objectSigningFlags |= CERTDB_USER; - nsslowcert_ChangeCertTrust(certHandle,cert,&trust); - } - } - } - crv = CKR_OK; - goto done; + if (((cert->trust->sslFlags & CERTDB_USER) == 0) && + ((cert->trust->emailFlags & CERTDB_USER) == 0) && + ((cert->trust->objectSigningFlags & CERTDB_USER) == 0)) { + NSSLOWKEYDBHandle *keyHandle; + + keyHandle = lg_getKeyDB(obj->sdb); + if (keyHandle) { + if (nsslowkey_KeyForCertExists(keyHandle, cert)) { + NSSLOWCERTCertTrust trust = *cert->trust; + trust.sslFlags |= CERTDB_USER; + trust.emailFlags |= CERTDB_USER; + trust.objectSigningFlags |= CERTDB_USER; + nsslowcert_ChangeCertTrust(certHandle, cert, &trust); + } + } + } + crv = CKR_OK; + goto done; } /* must be CKA_LABEL */ if (value != NULL) { - nickname = PORT_ZAlloc(len+1); - if (nickname == NULL) { - crv = CKR_HOST_MEMORY; - goto done; - } - PORT_Memcpy(nickname,value,len); - nickname[len] = 0; + nickname = PORT_ZAlloc(len + 1); + if (nickname == NULL) { + crv = CKR_HOST_MEMORY; + goto done; + } + PORT_Memcpy(nickname, value, len); + nickname[len] = 0; } rv = nsslowcert_AddPermNickname(certHandle, cert, nickname); crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; done: if (nickname) { - PORT_Free(nickname); + PORT_Free(nickname); } return crv; } static CK_RV -lg_SetPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len, - PRBool *writePrivate) +lg_SetPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len, + PRBool *writePrivate) { NSSLOWKEYPrivateKey *privKey; - NSSLOWKEYDBHandle *keyHandle; + NSSLOWKEYDBHandle *keyHandle; char *nickname = NULL; SECStatus rv; CK_RV crv; @@ -1539,162 +1543,165 @@ lg_SetPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, /* we can't change the ID and we don't store the subject, but let the * upper layers feel better about the fact we tried to set these */ if ((type == CKA_ID) || (type == CKA_SUBJECT) || - (type == CKA_LOCAL) || (type == CKA_NEVER_EXTRACTABLE) || - (type == CKA_ALWAYS_SENSITIVE)) { - return CKR_OK; + (type == CKA_LOCAL) || (type == CKA_NEVER_EXTRACTABLE) || + (type == CKA_ALWAYS_SENSITIVE)) { + return CKR_OK; } keyHandle = lg_getKeyDB(obj->sdb); if (keyHandle == NULL) { - crv = CKR_TOKEN_WRITE_PROTECTED; - goto done; + crv = CKR_TOKEN_WRITE_PROTECTED; + goto done; } privKey = lg_GetPrivateKeyWithDB(obj, keyHandle); if (privKey == NULL) { - crv = CKR_OBJECT_HANDLE_INVALID; - goto done; + crv = CKR_OBJECT_HANDLE_INVALID; + goto done; } crv = CKR_ATTRIBUTE_READ_ONLY; - switch(type) { - case CKA_LABEL: - if (value != NULL) { - nickname = PORT_ZAlloc(len+1); - if (nickname == NULL) { - crv = CKR_HOST_MEMORY; - goto done; - } - PORT_Memcpy(nickname,value,len); - nickname[len] = 0; - } - rv = nsslowkey_UpdateNickname(keyHandle, privKey, &obj->dbKey, - nickname, obj->sdb); - crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; - break; - case CKA_UNWRAP: - case CKA_SIGN: - case CKA_DERIVE: - case CKA_SIGN_RECOVER: - case CKA_DECRYPT: - /* ignore attempts to change restrict these. - * legacyDB ignore these flags and always presents all of them - * that are valid as true. - * NOTE: We only get here if the current value and the new value do - * not match. */ - if (*(char *)value == 0) { - crv = CKR_OK; - } - break; - case CKA_VALUE: - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - /* We aren't really changing these values, we are just triggering - * the database to update it's entry */ - *writePrivate = PR_TRUE; - crv = CKR_OK; - break; - default: - crv = CKR_ATTRIBUTE_READ_ONLY; - break; + switch (type) { + case CKA_LABEL: + if (value != NULL) { + nickname = PORT_ZAlloc(len + 1); + if (nickname == NULL) { + crv = CKR_HOST_MEMORY; + goto done; + } + PORT_Memcpy(nickname, value, len); + nickname[len] = 0; + } + rv = nsslowkey_UpdateNickname(keyHandle, privKey, &obj->dbKey, + nickname, obj->sdb); + crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; + break; + case CKA_UNWRAP: + case CKA_SIGN: + case CKA_DERIVE: + case CKA_SIGN_RECOVER: + case CKA_DECRYPT: + /* ignore attempts to change restrict these. + * legacyDB ignore these flags and always presents all of them + * that are valid as true. + * NOTE: We only get here if the current value and the new value do + * not match. */ + if (*(char *)value == 0) { + crv = CKR_OK; + } + break; + case CKA_VALUE: + case CKA_PRIVATE_EXPONENT: + case CKA_PRIME_1: + case CKA_PRIME_2: + case CKA_EXPONENT_1: + case CKA_EXPONENT_2: + case CKA_COEFFICIENT: + /* We aren't really changing these values, we are just triggering + * the database to update it's entry */ + *writePrivate = PR_TRUE; + crv = CKR_OK; + break; + default: + crv = CKR_ATTRIBUTE_READ_ONLY; + break; } done: if (nickname) { - PORT_Free(nickname); + PORT_Free(nickname); } return crv; } static CK_RV -lg_SetPublicKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len, - PRBool *writePrivate) +lg_SetPublicKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len, + PRBool *writePrivate) { /* we can't change the ID and we don't store the subject, but let the * upper layers feel better about the fact we tried to set these */ if ((type == CKA_ID) || (type == CKA_SUBJECT) || (type == CKA_LABEL)) { - return CKR_OK; + return CKR_OK; } - return CKR_ATTRIBUTE_READ_ONLY; + return CKR_ATTRIBUTE_READ_ONLY; } static CK_RV lg_SetTrustAttribute(LGObjectCache *obj, const CK_ATTRIBUTE *attr) { unsigned int flags; - CK_TRUST trust; - NSSLOWCERTCertificate *cert; + CK_TRUST trust; + NSSLOWCERTCertificate *cert = NULL; NSSLOWCERTCertDBHandle *certHandle; - NSSLOWCERTCertTrust dbTrust; + NSSLOWCERTCertTrust dbTrust; SECStatus rv; CK_RV crv; if (attr->type == CKA_LABEL) { - return CKR_OK; + return CKR_OK; } crv = lg_GetULongAttribute(attr->type, attr, 1, &trust); if (crv != CKR_OK) { - return crv; + return crv; } - flags = lg_MapTrust(trust, (PRBool) (attr->type == CKA_TRUST_CLIENT_AUTH)); + flags = lg_MapTrust(trust, (PRBool)(attr->type == CKA_TRUST_CLIENT_AUTH)); certHandle = lg_getCertDB(obj->sdb); if (certHandle == NULL) { - crv = CKR_TOKEN_WRITE_PROTECTED; - goto done; + crv = CKR_TOKEN_WRITE_PROTECTED; + goto done; } cert = lg_getCert(obj, certHandle); if (cert == NULL) { - crv = CKR_OBJECT_HANDLE_INVALID; - goto done; + crv = CKR_OBJECT_HANDLE_INVALID; + goto done; } dbTrust = *cert->trust; switch (attr->type) { - case CKA_TRUST_EMAIL_PROTECTION: - dbTrust.emailFlags = flags | - (cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS); - break; - case CKA_TRUST_CODE_SIGNING: - dbTrust.objectSigningFlags = flags | - (cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS); - break; - case CKA_TRUST_CLIENT_AUTH: - dbTrust.sslFlags = flags | (cert->trust->sslFlags & - (CERTDB_PRESERVE_TRUST_BITS|CERTDB_TRUSTED_CA)); - break; - case CKA_TRUST_SERVER_AUTH: - dbTrust.sslFlags = flags | (cert->trust->sslFlags & - (CERTDB_PRESERVE_TRUST_BITS|CERTDB_TRUSTED_CLIENT_CA)); - break; - default: - crv = CKR_ATTRIBUTE_READ_ONLY; - goto done; + case CKA_TRUST_EMAIL_PROTECTION: + dbTrust.emailFlags = flags | + (cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS); + break; + case CKA_TRUST_CODE_SIGNING: + dbTrust.objectSigningFlags = flags | + (cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS); + break; + case CKA_TRUST_CLIENT_AUTH: + dbTrust.sslFlags = flags | (cert->trust->sslFlags & + (CERTDB_PRESERVE_TRUST_BITS | CERTDB_TRUSTED_CA)); + break; + case CKA_TRUST_SERVER_AUTH: + dbTrust.sslFlags = flags | (cert->trust->sslFlags & + (CERTDB_PRESERVE_TRUST_BITS | CERTDB_TRUSTED_CLIENT_CA)); + break; + default: + crv = CKR_ATTRIBUTE_READ_ONLY; + goto done; } rv = nsslowcert_ChangeCertTrust(certHandle, cert, &dbTrust); crv = (rv == SECSuccess) ? CKR_OK : CKR_DEVICE_ERROR; done: + if (cert) { + nsslowcert_DestroyCertificate(cert); + } return crv; } static CK_RV -lg_SetSingleAttribute(LGObjectCache *obj, const CK_ATTRIBUTE *attr, - PRBool *writePrivate) +lg_SetSingleAttribute(LGObjectCache *obj, const CK_ATTRIBUTE *attr, + PRBool *writePrivate) { CK_ATTRIBUTE attribLocal; CK_RV crv; if ((attr->type == CKA_NETSCAPE_DB) && (obj->objclass == CKO_PRIVATE_KEY)) { - *writePrivate = PR_TRUE; - return CKR_OK; + *writePrivate = PR_TRUE; + return CKR_OK; } /* Make sure the attribute exists first */ @@ -1703,50 +1710,50 @@ lg_SetSingleAttribute(LGObjectCache *obj, const CK_ATTRIBUTE *attr, attribLocal.ulValueLen = 0; crv = lg_GetSingleAttribute(obj, &attribLocal); if (crv != CKR_OK) { - return crv; + return crv; } /* if we are just setting it to the value we already have, * allow it to happen. Let label setting go through so * we have the opportunity to repair any database corruption. */ if (attr->type != CKA_LABEL) { - if (lg_cmpAttribute(obj,attr)) { - return CKR_OK; - } + if (lg_cmpAttribute(obj, attr)) { + return CKR_OK; + } } crv = CKR_ATTRIBUTE_READ_ONLY; switch (obj->objclass) { - case CKO_CERTIFICATE: - /* change NICKNAME, EMAIL, */ - crv = lg_SetCertAttribute(obj,attr->type, - attr->pValue,attr->ulValueLen); - break; - case CKO_NSS_CRL: - /* change URL */ - break; - case CKO_NSS_TRUST: - crv = lg_SetTrustAttribute(obj,attr); - break; - case CKO_PRIVATE_KEY: - case CKO_SECRET_KEY: - crv = lg_SetPrivateKeyAttribute(obj,attr->type, - attr->pValue,attr->ulValueLen, writePrivate); - break; - case CKO_PUBLIC_KEY: - crv = lg_SetPublicKeyAttribute(obj,attr->type, - attr->pValue,attr->ulValueLen, writePrivate); - break; + case CKO_CERTIFICATE: + /* change NICKNAME, EMAIL, */ + crv = lg_SetCertAttribute(obj, attr->type, + attr->pValue, attr->ulValueLen); + break; + case CKO_NSS_CRL: + /* change URL */ + break; + case CKO_NSS_TRUST: + crv = lg_SetTrustAttribute(obj, attr); + break; + case CKO_PRIVATE_KEY: + case CKO_SECRET_KEY: + crv = lg_SetPrivateKeyAttribute(obj, attr->type, + attr->pValue, attr->ulValueLen, writePrivate); + break; + case CKO_PUBLIC_KEY: + crv = lg_SetPublicKeyAttribute(obj, attr->type, + attr->pValue, attr->ulValueLen, writePrivate); + break; } return crv; } /* * Fill in the attribute template based on the data in the database. - */ + */ CK_RV -lg_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) +lg_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE handle, + const CK_ATTRIBUTE *templ, CK_ULONG count) { LGObjectCache *obj = lg_NewObjectCache(sdb, NULL, handle & ~LG_TOKEN_MASK); CK_RV crv, crvCollect = CKR_OK; @@ -1754,29 +1761,30 @@ lg_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE handle, unsigned int i; if (obj == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } - for (i=0; i < count; i++) { - crv = lg_SetSingleAttribute(obj, &templ[i], &writePrivate); - if (crvCollect == CKR_OK) crvCollect = crv; + for (i = 0; i < count; i++) { + crv = lg_SetSingleAttribute(obj, &templ[i], &writePrivate); + if (crvCollect == CKR_OK) + crvCollect = crv; } /* Write any collected changes out for private and secret keys. * don't do the write for just the label */ if (writePrivate) { - NSSLOWKEYPrivateKey *privKey = lg_GetPrivateKey(obj); - SECStatus rv = SECFailure; - char * label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); - - if (privKey) { - rv = nsslowkey_StoreKeyByPublicKeyAlg(lg_getKeyDB(sdb), privKey, - &obj->dbKey, label, sdb, PR_TRUE ); - } - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - } - PORT_Free(label); + NSSLOWKEYPrivateKey *privKey = lg_GetPrivateKey(obj); + SECStatus rv = SECFailure; + char *label = lg_FindKeyNicknameByPublicKey(obj->sdb, &obj->dbKey); + + if (privKey) { + rv = nsslowkey_StoreKeyByPublicKeyAlg(lg_getKeyDB(sdb), privKey, + &obj->dbKey, label, sdb, PR_TRUE); + } + if (rv != SECSuccess) { + crv = CKR_DEVICE_ERROR; + } + PORT_Free(label); } lg_DestroyObjectCache(obj); diff --git a/nss/lib/softoken/legacydb/lgcreate.c b/nss/lib/softoken/legacydb/lgcreate.c index c5ce99e..a0d2b2e 100644 --- a/nss/lib/softoken/legacydb/lgcreate.c +++ b/nss/lib/softoken/legacydb/lgcreate.c @@ -3,34 +3,34 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "secitem.h" #include "pkcs11.h" -#include "lgdb.h" +#include "lgdb.h" #include "pcert.h" #include "lowkeyi.h" #include "blapi.h" #include "secder.h" #include "secasn1.h" -#include "keydbi.h" +#include "keydbi.h" /* * ******************** Object Creation Utilities *************************** */ /* - * check the consistancy and initialize a Certificate Object + * check the consistancy and initialize a Certificate Object */ static CK_RV lg_createCertObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { SECItem derCert; NSSLOWCERTCertificate *cert; NSSLOWCERTCertTrust *trust = NULL; - NSSLOWCERTCertTrust userTrust = - { CERTDB_USER, CERTDB_USER, CERTDB_USER }; - NSSLOWCERTCertTrust defTrust = - { CERTDB_TRUSTED_UNKNOWN, - CERTDB_TRUSTED_UNKNOWN, CERTDB_TRUSTED_UNKNOWN }; + NSSLOWCERTCertTrust userTrust = + { CERTDB_USER, CERTDB_USER, CERTDB_USER }; + NSSLOWCERTCertTrust defTrust = + { CERTDB_TRUSTED_UNKNOWN, + CERTDB_TRUSTED_UNKNOWN, CERTDB_TRUSTED_UNKNOWN }; char *label = NULL; char *email = NULL; SECStatus rv; @@ -43,68 +43,69 @@ lg_createCertObject(SDB *sdb, CK_OBJECT_HANDLE *handle, /* we can't store any certs private */ if (lg_isTrue(CKA_PRIVATE, templ, count)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } - + /* We only support X.509 Certs for now */ crv = lg_GetULongAttribute(CKA_CERTIFICATE_TYPE, templ, count, &type); if (crv != CKR_OK) { - return crv; + return crv; } if (type != CKC_X_509) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } /* X.509 Certificate */ - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - /* get the der cert */ + /* get the der cert */ attribute = lg_FindAttribute(CKA_VALUE, templ, count); if (!attribute) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } derCert.type = 0; derCert.data = (unsigned char *)attribute->pValue; - derCert.len = attribute->ulValueLen ; + derCert.len = attribute->ulValueLen; label = lg_getString(CKA_LABEL, templ, count); - cert = nsslowcert_FindCertByDERCert(certHandle, &derCert); + cert = nsslowcert_FindCertByDERCert(certHandle, &derCert); if (cert == NULL) { - cert = nsslowcert_DecodeDERCertificate(&derCert, label); - inDB = PR_FALSE; + cert = nsslowcert_DecodeDERCertificate(&derCert, label); + inDB = PR_FALSE; } if (cert == NULL) { - if (label) PORT_Free(label); - return CKR_ATTRIBUTE_VALUE_INVALID; + if (label) + PORT_Free(label); + return CKR_ATTRIBUTE_VALUE_INVALID; } keyHandle = lg_getKeyDB(sdb); if (keyHandle) { - if (nsslowkey_KeyForCertExists(keyHandle,cert)) { - trust = &userTrust; - } + if (nsslowkey_KeyForCertExists(keyHandle, cert)) { + trust = &userTrust; + } } if (!inDB) { - if (!trust) trust = &defTrust; - rv = nsslowcert_AddPermCert(certHandle, cert, label, trust); + if (!trust) + trust = &defTrust; + rv = nsslowcert_AddPermCert(certHandle, cert, label, trust); } else { - rv = trust ? nsslowcert_ChangeCertTrust(certHandle,cert,trust) : - SECSuccess; + rv = trust ? nsslowcert_ChangeCertTrust(certHandle, cert, trust) : SECSuccess; } - if (label) PORT_Free(label); + if (label) + PORT_Free(label); if (rv != SECSuccess) { - nsslowcert_DestroyCertificate(cert); - return CKR_DEVICE_ERROR; + nsslowcert_DestroyCertificate(cert); + return CKR_DEVICE_ERROR; } /* @@ -112,18 +113,18 @@ lg_createCertObject(SDB *sdb, CK_OBJECT_HANDLE *handle, */ email = lg_getString(CKA_NSS_EMAIL, templ, count); if (email) { - certDBEntrySMime *entry; - - entry = nsslowcert_ReadDBSMimeEntry(certHandle,email); - if (!entry) { - nsslowcert_SaveSMimeProfile(certHandle, email, - &cert->derSubject, NULL, NULL); - } else { - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(email); - } - *handle=lg_mkHandle(sdb,&cert->certKey,LG_TOKEN_TYPE_CERT); + certDBEntrySMime *entry; + + entry = nsslowcert_ReadDBSMimeEntry(certHandle, email); + if (!entry) { + nsslowcert_SaveSMimeProfile(certHandle, email, + &cert->derSubject, NULL, NULL); + } else { + nsslowcert_DestroyDBEntry((certDBEntry *)entry); + } + PORT_Free(email); + } + *handle = lg_mkHandle(sdb, &cert->certKey, LG_TOKEN_TYPE_CERT); nsslowcert_DestroyCertificate(cert); return CKR_OK; @@ -132,32 +133,30 @@ lg_createCertObject(SDB *sdb, CK_OBJECT_HANDLE *handle, unsigned int lg_MapTrust(CK_TRUST trust, PRBool clientAuth) { - unsigned int trustCA = clientAuth ? CERTDB_TRUSTED_CLIENT_CA : - CERTDB_TRUSTED_CA; + unsigned int trustCA = clientAuth ? CERTDB_TRUSTED_CLIENT_CA : CERTDB_TRUSTED_CA; switch (trust) { - case CKT_NSS_TRUSTED: - return CERTDB_TERMINAL_RECORD|CERTDB_TRUSTED; - case CKT_NSS_TRUSTED_DELEGATOR: - return CERTDB_VALID_CA|trustCA; - case CKT_NSS_MUST_VERIFY_TRUST: - return CERTDB_MUST_VERIFY; - case CKT_NSS_NOT_TRUSTED: - return CERTDB_TERMINAL_RECORD; - case CKT_NSS_VALID_DELEGATOR: /* implies must verify */ - return CERTDB_VALID_CA; - default: - break; + case CKT_NSS_TRUSTED: + return CERTDB_TERMINAL_RECORD | CERTDB_TRUSTED; + case CKT_NSS_TRUSTED_DELEGATOR: + return CERTDB_VALID_CA | trustCA; + case CKT_NSS_MUST_VERIFY_TRUST: + return CERTDB_MUST_VERIFY; + case CKT_NSS_NOT_TRUSTED: + return CERTDB_TERMINAL_RECORD; + case CKT_NSS_VALID_DELEGATOR: /* implies must verify */ + return CERTDB_VALID_CA; + default: + break; } return CERTDB_TRUSTED_UNKNOWN; } - - + /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV lg_createTrustObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { const CK_ATTRIBUTE *issuer = NULL; const CK_ATTRIBUTE *serial = NULL; @@ -175,30 +174,30 @@ lg_createTrustObject(SDB *sdb, CK_OBJECT_HANDLE *handle, /* we can't store any certs private */ if (lg_isTrue(CKA_PRIVATE, templ, count)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } issuer = lg_FindAttribute(CKA_ISSUER, templ, count); serial = lg_FindAttribute(CKA_SERIAL_NUMBER, templ, count); if (issuer && serial) { - issuerSN.derIssuer.data = (unsigned char *)issuer->pValue; - issuerSN.derIssuer.len = issuer->ulValueLen ; + issuerSN.derIssuer.data = (unsigned char *)issuer->pValue; + issuerSN.derIssuer.len = issuer->ulValueLen; - issuerSN.serialNumber.data = (unsigned char *)serial->pValue; - issuerSN.serialNumber.len = serial->ulValueLen ; + issuerSN.serialNumber.data = (unsigned char *)serial->pValue; + issuerSN.serialNumber.len = serial->ulValueLen; - cert = nsslowcert_FindCertByIssuerAndSN(certHandle,&issuerSN); + cert = nsslowcert_FindCertByIssuerAndSN(certHandle, &issuerSN); } if (cert == NULL) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } - + lg_GetULongAttribute(CKA_TRUST_SERVER_AUTH, templ, count, &sslTrust); lg_GetULongAttribute(CKA_TRUST_CLIENT_AUTH, templ, count, &clientTrust); lg_GetULongAttribute(CKA_TRUST_EMAIL_PROTECTION, templ, count, &emailTrust); @@ -206,284 +205,283 @@ lg_createTrustObject(SDB *sdb, CK_OBJECT_HANDLE *handle, stepUp = CK_FALSE; trust = lg_FindAttribute(CKA_TRUST_STEP_UP_APPROVED, templ, count); if (trust) { - if (trust->ulValueLen == sizeof(CK_BBOOL)) { - stepUp = *(CK_BBOOL*)trust->pValue; - } + if (trust->ulValueLen == sizeof(CK_BBOOL)) { + stepUp = *(CK_BBOOL *)trust->pValue; + } } /* preserve certain old fields */ if (cert->trust) { - dbTrust.sslFlags = cert->trust->sslFlags & CERTDB_PRESERVE_TRUST_BITS; - dbTrust.emailFlags= - cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS; - dbTrust.objectSigningFlags = - cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS; + dbTrust.sslFlags = cert->trust->sslFlags & CERTDB_PRESERVE_TRUST_BITS; + dbTrust.emailFlags = + cert->trust->emailFlags & CERTDB_PRESERVE_TRUST_BITS; + dbTrust.objectSigningFlags = + cert->trust->objectSigningFlags & CERTDB_PRESERVE_TRUST_BITS; } - dbTrust.sslFlags |= lg_MapTrust(sslTrust,PR_FALSE); - dbTrust.sslFlags |= lg_MapTrust(clientTrust,PR_TRUE); - dbTrust.emailFlags |= lg_MapTrust(emailTrust,PR_FALSE); - dbTrust.objectSigningFlags |= lg_MapTrust(signTrust,PR_FALSE); + dbTrust.sslFlags |= lg_MapTrust(sslTrust, PR_FALSE); + dbTrust.sslFlags |= lg_MapTrust(clientTrust, PR_TRUE); + dbTrust.emailFlags |= lg_MapTrust(emailTrust, PR_FALSE); + dbTrust.objectSigningFlags |= lg_MapTrust(signTrust, PR_FALSE); if (stepUp) { - dbTrust.sslFlags |= CERTDB_GOVT_APPROVED_CA; + dbTrust.sslFlags |= CERTDB_GOVT_APPROVED_CA; } - rv = nsslowcert_ChangeCertTrust(certHandle,cert,&dbTrust); - *handle=lg_mkHandle(sdb,&cert->certKey,LG_TOKEN_TYPE_TRUST); + rv = nsslowcert_ChangeCertTrust(certHandle, cert, &dbTrust); + *handle = lg_mkHandle(sdb, &cert->certKey, LG_TOKEN_TYPE_TRUST); nsslowcert_DestroyCertificate(cert); if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; + return CKR_DEVICE_ERROR; } return CKR_OK; } /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV lg_createSMimeObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { - SECItem derSubj,rawProfile,rawTime,emailKey; + SECItem derSubj, rawProfile, rawTime, emailKey; SECItem *pRawProfile = NULL; SECItem *pRawTime = NULL; char *email = NULL; const CK_ATTRIBUTE *subject = NULL, - *profile = NULL, - *time = NULL; + *profile = NULL, + *time = NULL; SECStatus rv; NSSLOWCERTCertDBHandle *certHandle; CK_RV ck_rv = CKR_OK; /* we can't store any certs private */ - if (lg_isTrue(CKA_PRIVATE,templ,count)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (lg_isTrue(CKA_PRIVATE, templ, count)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } certHandle = lg_getCertDB(sdb); if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } /* lookup SUBJECT */ - subject = lg_FindAttribute(CKA_SUBJECT,templ,count); + subject = lg_FindAttribute(CKA_SUBJECT, templ, count); PORT_Assert(subject); if (!subject) { - ck_rv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; + ck_rv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } derSubj.data = (unsigned char *)subject->pValue; - derSubj.len = subject->ulValueLen ; + derSubj.len = subject->ulValueLen; derSubj.type = 0; /* lookup VALUE */ - profile = lg_FindAttribute(CKA_VALUE,templ,count); + profile = lg_FindAttribute(CKA_VALUE, templ, count); if (profile) { - rawProfile.data = (unsigned char *)profile->pValue; - rawProfile.len = profile->ulValueLen ; - rawProfile.type = siBuffer; - pRawProfile = &rawProfile; + rawProfile.data = (unsigned char *)profile->pValue; + rawProfile.len = profile->ulValueLen; + rawProfile.type = siBuffer; + pRawProfile = &rawProfile; } /* lookup Time */ - time = lg_FindAttribute(CKA_NSS_SMIME_TIMESTAMP,templ,count); + time = lg_FindAttribute(CKA_NSS_SMIME_TIMESTAMP, templ, count); if (time) { - rawTime.data = (unsigned char *)time->pValue; - rawTime.len = time->ulValueLen ; - rawTime.type = siBuffer; - pRawTime = &rawTime; + rawTime.data = (unsigned char *)time->pValue; + rawTime.len = time->ulValueLen; + rawTime.type = siBuffer; + pRawTime = &rawTime; } - - email = lg_getString(CKA_NSS_EMAIL,templ,count); + email = lg_getString(CKA_NSS_EMAIL, templ, count); if (!email) { - ck_rv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; + ck_rv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } /* Store S/MIME Profile by SUBJECT */ - rv = nsslowcert_SaveSMimeProfile(certHandle, email, &derSubj, - pRawProfile,pRawTime); + rv = nsslowcert_SaveSMimeProfile(certHandle, email, &derSubj, + pRawProfile, pRawTime); if (rv != SECSuccess) { - ck_rv = CKR_DEVICE_ERROR; - goto loser; + ck_rv = CKR_DEVICE_ERROR; + goto loser; } emailKey.data = (unsigned char *)email; - emailKey.len = PORT_Strlen(email)+1; + emailKey.len = PORT_Strlen(email) + 1; *handle = lg_mkHandle(sdb, &emailKey, LG_TOKEN_TYPE_SMIME); loser: - if (email) PORT_Free(email); + if (email) + PORT_Free(email); return ck_rv; } /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV lg_createCrlObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { PRBool isKRL = PR_FALSE; - SECItem derSubj,derCrl; + SECItem derSubj, derCrl; char *url = NULL; - const CK_ATTRIBUTE *subject,*crl; + const CK_ATTRIBUTE *subject, *crl; SECStatus rv; NSSLOWCERTCertDBHandle *certHandle; certHandle = lg_getCertDB(sdb); /* we can't store any private crls */ - if (lg_isTrue(CKA_PRIVATE,templ,count)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (lg_isTrue(CKA_PRIVATE, templ, count)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } /* lookup SUBJECT */ - subject = lg_FindAttribute(CKA_SUBJECT,templ,count); + subject = lg_FindAttribute(CKA_SUBJECT, templ, count); if (!subject) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } derSubj.data = (unsigned char *)subject->pValue; - derSubj.len = subject->ulValueLen ; + derSubj.len = subject->ulValueLen; /* lookup VALUE */ - crl = lg_FindAttribute(CKA_VALUE,templ,count); + crl = lg_FindAttribute(CKA_VALUE, templ, count); PORT_Assert(crl); if (!crl) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } derCrl.data = (unsigned char *)crl->pValue; - derCrl.len = crl->ulValueLen ; + derCrl.len = crl->ulValueLen; - url = lg_getString(CKA_NSS_URL,templ,count); - isKRL = lg_isTrue(CKA_NSS_KRL,templ,count); + url = lg_getString(CKA_NSS_URL, templ, count); + isKRL = lg_isTrue(CKA_NSS_KRL, templ, count); /* Store CRL by SUBJECT */ rv = nsslowcert_AddCrl(certHandle, &derCrl, &derSubj, url, isKRL); if (url) { - PORT_Free(url); + PORT_Free(url); } if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; + return CKR_DEVICE_ERROR; } /* if we overwrote the existing CRL, poison the handle entry so we get * a new object handle */ - (void) lg_poisonHandle(sdb, &derSubj, - isKRL ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL); + (void)lg_poisonHandle(sdb, &derSubj, + isKRL ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL); *handle = lg_mkHandle(sdb, &derSubj, - isKRL ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL); + isKRL ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL); return CKR_OK; } /* - * check the consistancy and initialize a Public Key Object + * check the consistancy and initialize a Public Key Object */ static CK_RV lg_createPublicKeyObject(SDB *sdb, CK_KEY_TYPE key_type, - CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) + CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) { CK_ATTRIBUTE_TYPE pubKeyAttr = CKA_VALUE; CK_RV crv = CKR_OK; NSSLOWKEYPrivateKey *priv; - SECItem pubKeySpace = {siBuffer, NULL, 0}; + SECItem pubKeySpace = { siBuffer, NULL, 0 }; SECItem *pubKey; #ifndef NSS_DISABLE_ECC - SECItem pubKey2Space = {siBuffer, NULL, 0}; + SECItem pubKey2Space = { siBuffer, NULL, 0 }; PLArenaPool *arena = NULL; #endif /* NSS_DISABLE_ECC */ NSSLOWKEYDBHandle *keyHandle = NULL; - switch (key_type) { - case CKK_RSA: - pubKeyAttr = CKA_MODULUS; - break; + case CKK_RSA: + pubKeyAttr = CKA_MODULUS; + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - pubKeyAttr = CKA_EC_POINT; - break; + case CKK_EC: + pubKeyAttr = CKA_EC_POINT; + break; #endif /* NSS_DISABLE_ECC */ - case CKK_DSA: - case CKK_DH: - break; - default: - return CKR_ATTRIBUTE_VALUE_INVALID; + case CKK_DSA: + case CKK_DH: + break; + default: + return CKR_ATTRIBUTE_VALUE_INVALID; } - pubKey = &pubKeySpace; - crv = lg_Attribute2SSecItem(NULL,pubKeyAttr,templ,count,pubKey); - if (crv != CKR_OK) return crv; + crv = lg_Attribute2SSecItem(NULL, pubKeyAttr, templ, count, pubKey); + if (crv != CKR_OK) + return crv; #ifndef NSS_DISABLE_ECC if (key_type == CKK_EC) { - SECStatus rv; - /* - * for ECC, use the decoded key first. - */ - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - crv = CKR_HOST_MEMORY; - goto done; - } - rv= SEC_QuickDERDecodeItem(arena, &pubKey2Space, - SEC_ASN1_GET(SEC_OctetStringTemplate), - pubKey); - if (rv != SECSuccess) { - /* decode didn't work, just try the pubKey */ - PORT_FreeArena(arena, PR_FALSE); - arena = NULL; - } else { - /* try the decoded pub key first */ - pubKey = &pubKey2Space; - } + SECStatus rv; + /* + * for ECC, use the decoded key first. + */ + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + crv = CKR_HOST_MEMORY; + goto done; + } + rv = SEC_QuickDERDecodeItem(arena, &pubKey2Space, + SEC_ASN1_GET(SEC_OctetStringTemplate), + pubKey); + if (rv != SECSuccess) { + /* decode didn't work, just try the pubKey */ + PORT_FreeArena(arena, PR_FALSE); + arena = NULL; + } else { + /* try the decoded pub key first */ + pubKey = &pubKey2Space; + } } #endif /* NSS_DISABLE_ECC */ PORT_Assert(pubKey->data); if (pubKey->data == NULL) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto done; + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto done; } keyHandle = lg_getKeyDB(sdb); if (keyHandle == NULL) { - crv = CKR_TOKEN_WRITE_PROTECTED; - goto done; + crv = CKR_TOKEN_WRITE_PROTECTED; + goto done; } if (keyHandle->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,pubKey->data,pubKey->len); - PORT_Memcpy(pubKey->data,buf,sizeof(buf)); - pubKey->len = sizeof(buf); + unsigned char buf[SHA1_LENGTH]; + SHA1_HashBuf(buf, pubKey->data, pubKey->len); + PORT_Memcpy(pubKey->data, buf, sizeof(buf)); + pubKey->len = sizeof(buf); } /* make sure the associated private key already exists */ /* only works if we are logged in */ priv = nsslowkey_FindKeyByPublicKey(keyHandle, pubKey, sdb /*password*/); #ifndef NSS_DISABLE_ECC if (priv == NULL && pubKey == &pubKey2Space) { - /* no match on the decoded key, match the original pubkey */ - pubKey = &pubKeySpace; - priv = nsslowkey_FindKeyByPublicKey(keyHandle, pubKey, - sdb /*password*/); + /* no match on the decoded key, match the original pubkey */ + pubKey = &pubKeySpace; + priv = nsslowkey_FindKeyByPublicKey(keyHandle, pubKey, + sdb /*password*/); } #endif if (priv == NULL) { - /* the legacy database can only 'store' public keys which already - * have their corresponding private keys in the database */ - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto done; + /* the legacy database can only 'store' public keys which already + * have their corresponding private keys in the database */ + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto done; } lg_nsslowkey_DestroyPrivateKey(priv); crv = CKR_OK; @@ -493,8 +491,8 @@ lg_createPublicKeyObject(SDB *sdb, CK_KEY_TYPE key_type, done: PORT_Free(pubKeySpace.data); #ifndef NSS_DISABLE_ECC - if (arena) - PORT_FreeArena(arena, PR_FALSE); + if (arena) + PORT_FreeArena(arena, PR_FALSE); #endif return crv; @@ -503,7 +501,7 @@ done: /* make a private key from a verified object */ static NSSLOWKEYPrivateKey * lg_mkPrivKey(SDB *sdb, const CK_ATTRIBUTE *templ, CK_ULONG count, - CK_KEY_TYPE key_type, CK_RV *crvp) + CK_KEY_TYPE key_type, CK_RV *crvp) { NSSLOWKEYPrivateKey *privKey; PLArenaPool *arena; @@ -512,142 +510,162 @@ lg_mkPrivKey(SDB *sdb, const CK_ATTRIBUTE *templ, CK_ULONG count, arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - *crvp = CKR_HOST_MEMORY; - return NULL; + *crvp = CKR_HOST_MEMORY; + return NULL; } privKey = (NSSLOWKEYPrivateKey *) - PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey)); - if (privKey == NULL) { - PORT_FreeArena(arena,PR_FALSE); - *crvp = CKR_HOST_MEMORY; - return NULL; + PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPrivateKey)); + if (privKey == NULL) { + PORT_FreeArena(arena, PR_FALSE); + *crvp = CKR_HOST_MEMORY; + return NULL; } /* in future this would be a switch on key_type */ privKey->arena = arena; switch (key_type) { - case CKK_RSA: - privKey->keyType = NSSLOWKEYRSAKey; - crv=lg_Attribute2SSecItem(arena,CKA_MODULUS,templ,count, - &privKey->u.rsa.modulus); - if (crv != CKR_OK) break; - crv=lg_Attribute2SSecItem(arena,CKA_PUBLIC_EXPONENT,templ,count, - &privKey->u.rsa.publicExponent); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_PRIVATE_EXPONENT,templ,count, - &privKey->u.rsa.privateExponent, sdb); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_PRIME_1,templ,count, - &privKey->u.rsa.prime1, sdb); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_PRIME_2,templ,count, - &privKey->u.rsa.prime2, sdb); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_EXPONENT_1,templ,count, - &privKey->u.rsa.exponent1, sdb); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_EXPONENT_2,templ,count, - &privKey->u.rsa.exponent2, sdb); - if (crv != CKR_OK) break; - crv=lg_PrivAttr2SSecItem(arena,CKA_COEFFICIENT,templ,count, - &privKey->u.rsa.coefficient, sdb); - if (crv != CKR_OK) break; - rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version, - NSSLOWKEY_VERSION); - if (rv != SECSuccess) crv = CKR_HOST_MEMORY; - break; - - case CKK_DSA: - privKey->keyType = NSSLOWKEYDSAKey; - crv = lg_Attribute2SSecItem(arena,CKA_PRIME,templ,count, - &privKey->u.dsa.params.prime); - if (crv != CKR_OK) break; - crv = lg_Attribute2SSecItem(arena,CKA_SUBPRIME,templ,count, - &privKey->u.dsa.params.subPrime); - if (crv != CKR_OK) break; - crv = lg_Attribute2SSecItem(arena,CKA_BASE,templ,count, - &privKey->u.dsa.params.base); - if (crv != CKR_OK) break; - crv = lg_PrivAttr2SSecItem(arena,CKA_VALUE,templ,count, - &privKey->u.dsa.privateValue, sdb); - if (crv != CKR_OK) break; - if (lg_hasAttribute(CKA_NETSCAPE_DB, templ,count)) { - crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB,templ,count, - &privKey->u.dsa.publicValue); - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - } - break; - - case CKK_DH: - privKey->keyType = NSSLOWKEYDHKey; - crv = lg_Attribute2SSecItem(arena,CKA_PRIME,templ,count, - &privKey->u.dh.prime); - if (crv != CKR_OK) break; - crv = lg_Attribute2SSecItem(arena,CKA_BASE,templ,count, - &privKey->u.dh.base); - if (crv != CKR_OK) break; - crv = lg_PrivAttr2SSecItem(arena,CKA_VALUE,templ,count, - &privKey->u.dh.privateValue, sdb); - if (crv != CKR_OK) break; - if (lg_hasAttribute(CKA_NETSCAPE_DB, templ, count)) { - crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB,templ,count, - &privKey->u.dh.publicValue); - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - } - break; + case CKK_RSA: + privKey->keyType = NSSLOWKEYRSAKey; + crv = lg_Attribute2SSecItem(arena, CKA_MODULUS, templ, count, + &privKey->u.rsa.modulus); + if (crv != CKR_OK) + break; + crv = lg_Attribute2SSecItem(arena, CKA_PUBLIC_EXPONENT, templ, count, + &privKey->u.rsa.publicExponent); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_PRIVATE_EXPONENT, templ, count, + &privKey->u.rsa.privateExponent, sdb); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_PRIME_1, templ, count, + &privKey->u.rsa.prime1, sdb); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_PRIME_2, templ, count, + &privKey->u.rsa.prime2, sdb); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_EXPONENT_1, templ, count, + &privKey->u.rsa.exponent1, sdb); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_EXPONENT_2, templ, count, + &privKey->u.rsa.exponent2, sdb); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_COEFFICIENT, templ, count, + &privKey->u.rsa.coefficient, sdb); + if (crv != CKR_OK) + break; + rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version, + NSSLOWKEY_VERSION); + if (rv != SECSuccess) + crv = CKR_HOST_MEMORY; + break; + + case CKK_DSA: + privKey->keyType = NSSLOWKEYDSAKey; + crv = lg_Attribute2SSecItem(arena, CKA_PRIME, templ, count, + &privKey->u.dsa.params.prime); + if (crv != CKR_OK) + break; + crv = lg_Attribute2SSecItem(arena, CKA_SUBPRIME, templ, count, + &privKey->u.dsa.params.subPrime); + if (crv != CKR_OK) + break; + crv = lg_Attribute2SSecItem(arena, CKA_BASE, templ, count, + &privKey->u.dsa.params.base); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_VALUE, templ, count, + &privKey->u.dsa.privateValue, sdb); + if (crv != CKR_OK) + break; + if (lg_hasAttribute(CKA_NETSCAPE_DB, templ, count)) { + crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB, templ, count, + &privKey->u.dsa.publicValue); + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + } + break; + + case CKK_DH: + privKey->keyType = NSSLOWKEYDHKey; + crv = lg_Attribute2SSecItem(arena, CKA_PRIME, templ, count, + &privKey->u.dh.prime); + if (crv != CKR_OK) + break; + crv = lg_Attribute2SSecItem(arena, CKA_BASE, templ, count, + &privKey->u.dh.base); + if (crv != CKR_OK) + break; + crv = lg_PrivAttr2SSecItem(arena, CKA_VALUE, templ, count, + &privKey->u.dh.privateValue, sdb); + if (crv != CKR_OK) + break; + if (lg_hasAttribute(CKA_NETSCAPE_DB, templ, count)) { + crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB, templ, count, + &privKey->u.dh.publicValue); + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + } + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - privKey->keyType = NSSLOWKEYECKey; - crv = lg_Attribute2SSecItem(arena, CKA_EC_PARAMS,templ,count, - &privKey->u.ec.ecParams.DEREncoding); - if (crv != CKR_OK) break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (LGEC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding, - &privKey->u.ec.ecParams) != SECSuccess) { - crv = CKR_DOMAIN_PARAMS_INVALID; - break; - } - crv = lg_PrivAttr2SSecItem(arena,CKA_VALUE,templ,count, - &privKey->u.ec.privateValue, sdb); - if (crv != CKR_OK) break; - if (lg_hasAttribute(CKA_NETSCAPE_DB,templ,count)) { - crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB,templ,count, - &privKey->u.ec.publicValue); - if (crv != CKR_OK) break; - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - } - rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version, - NSSLOWKEY_EC_PRIVATE_KEY_VERSION); - if (rv != SECSuccess) crv = CKR_HOST_MEMORY; - break; + case CKK_EC: + privKey->keyType = NSSLOWKEYECKey; + crv = lg_Attribute2SSecItem(arena, CKA_EC_PARAMS, templ, count, + &privKey->u.ec.ecParams.DEREncoding); + if (crv != CKR_OK) + break; + + /* Fill out the rest of the ecParams structure + * based on the encoded params + */ + if (LGEC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding, + &privKey->u.ec.ecParams) != SECSuccess) { + crv = CKR_DOMAIN_PARAMS_INVALID; + break; + } + crv = lg_PrivAttr2SSecItem(arena, CKA_VALUE, templ, count, + &privKey->u.ec.privateValue, sdb); + if (crv != CKR_OK) + break; + if (lg_hasAttribute(CKA_NETSCAPE_DB, templ, count)) { + crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB, templ, count, + &privKey->u.ec.publicValue); + if (crv != CKR_OK) + break; + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + } + rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version, + NSSLOWKEY_EC_PRIVATE_KEY_VERSION); + if (rv != SECSuccess) + crv = CKR_HOST_MEMORY; + break; #endif /* NSS_DISABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; + default: + crv = CKR_KEY_TYPE_INCONSISTENT; + break; } *crvp = crv; if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } return privKey; } /* - * check the consistancy and initialize a Private Key Object + * check the consistancy and initialize a Private Key Object */ static CK_RV lg_createPrivateKeyObject(SDB *sdb, CK_KEY_TYPE key_type, - CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) + CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) { NSSLOWKEYPrivateKey *privKey; char *label; @@ -657,53 +675,56 @@ lg_createPrivateKeyObject(SDB *sdb, CK_KEY_TYPE key_type, NSSLOWKEYDBHandle *keyHandle = lg_getKeyDB(sdb); if (keyHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - privKey=lg_mkPrivKey(sdb, templ,count,key_type,&crv); - if (privKey == NULL) return crv; - label = lg_getString(CKA_LABEL,templ,count); + privKey = lg_mkPrivKey(sdb, templ, count, key_type, &crv); + if (privKey == NULL) + return crv; + label = lg_getString(CKA_LABEL, templ, count); - crv = lg_Attribute2SSecItem(NULL,CKA_NETSCAPE_DB,templ,count,&pubKey); + crv = lg_Attribute2SSecItem(NULL, CKA_NETSCAPE_DB, templ, count, &pubKey); if (crv != CKR_OK) { - crv = CKR_TEMPLATE_INCOMPLETE; - rv = SECFailure; - goto fail; + crv = CKR_TEMPLATE_INCOMPLETE; + rv = SECFailure; + goto fail; } #ifdef notdef if (keyHandle->version != 3) { - unsigned char buf[SHA1_LENGTH]; - SHA1_HashBuf(buf,pubKey.data,pubKey.len); - PORT_Memcpy(pubKey.data,buf,sizeof(buf)); - pubKey.len = sizeof(buf); + unsigned char buf[SHA1_LENGTH]; + SHA1_HashBuf(buf, pubKey.data, pubKey.len); + PORT_Memcpy(pubKey.data, buf, sizeof(buf)); + pubKey.len = sizeof(buf); } #endif /* get the key type */ if (key_type == CKK_RSA) { - rv = RSA_PrivateKeyCheck(&privKey->u.rsa); - if (rv == SECFailure) { - goto fail; - } + rv = RSA_PrivateKeyCheck(&privKey->u.rsa); + if (rv == SECFailure) { + goto fail; + } } - rv = nsslowkey_StoreKeyByPublicKey(keyHandle, privKey, &pubKey, - label, sdb /*->password*/); + rv = nsslowkey_StoreKeyByPublicKey(keyHandle, privKey, &pubKey, + label, sdb /*->password*/); fail: - if (label) PORT_Free(label); - *handle = lg_mkHandle(sdb,&pubKey,LG_TOKEN_TYPE_PRIV); - if (pubKey.data) PORT_Free(pubKey.data); + if (label) + PORT_Free(label); + *handle = lg_mkHandle(sdb, &pubKey, LG_TOKEN_TYPE_PRIV); + if (pubKey.data) + PORT_Free(pubKey.data); lg_nsslowkey_DestroyPrivateKey(privKey); - if (rv != SECSuccess) return crv; + if (rv != SECSuccess) + return crv; return CKR_OK; } - #define LG_KEY_MAX_RETRIES 10 /* don't hang if we are having problems with the rng */ -#define LG_KEY_ID_SIZE 18 /* don't use either SHA1 or MD5 sizes */ +#define LG_KEY_ID_SIZE 18 /* don't use either SHA1 or MD5 sizes */ /* * Secret keys must have a CKA_ID value to be stored in the database. This code - * will generate one if there wasn't one already. + * will generate one if there wasn't one already. */ static CK_RV lg_GenerateSecretCKA_ID(NSSLOWKEYDBHandle *handle, SECItem *id, char *label) @@ -714,43 +735,43 @@ lg_GenerateSecretCKA_ID(NSSLOWKEYDBHandle *handle, SECItem *id, char *label) id->data = NULL; if (label) { - id->data = (unsigned char *)PORT_Strdup(label); - if (id->data == NULL) { - return CKR_HOST_MEMORY; - } - id->len = PORT_Strlen(label)+1; - if (!nsslowkey_KeyForIDExists(handle,id)) { - return CKR_OK; - } - PORT_Free(id->data); - id->data = NULL; - id->len = 0; + id->data = (unsigned char *)PORT_Strdup(label); + if (id->data == NULL) { + return CKR_HOST_MEMORY; + } + id->len = PORT_Strlen(label) + 1; + if (!nsslowkey_KeyForIDExists(handle, id)) { + return CKR_OK; + } + PORT_Free(id->data); + id->data = NULL; + id->len = 0; } id->data = (unsigned char *)PORT_Alloc(LG_KEY_ID_SIZE); if (id->data == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } id->len = LG_KEY_ID_SIZE; retries = 0; do { - rv = RNG_GenerateGlobalRandomBytes(id->data,id->len); - } while (rv == SECSuccess && nsslowkey_KeyForIDExists(handle,id) && - (++retries <= LG_KEY_MAX_RETRIES)); + rv = RNG_GenerateGlobalRandomBytes(id->data, id->len); + } while (rv == SECSuccess && nsslowkey_KeyForIDExists(handle, id) && + (++retries <= LG_KEY_MAX_RETRIES)); if ((rv != SECSuccess) || (retries > LG_KEY_MAX_RETRIES)) { - crv = CKR_DEVICE_ERROR; /* random number generator is bad */ - PORT_Free(id->data); - id->data = NULL; - id->len = 0; + crv = CKR_DEVICE_ERROR; /* random number generator is bad */ + PORT_Free(id->data); + id->data = NULL; + id->len = 0; } return crv; } - -static NSSLOWKEYPrivateKey *lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, - CK_ULONG count, CK_KEY_TYPE key_type, - SECItem *pubkey, SDB *sdbpw) +static NSSLOWKEYPrivateKey * +lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, + CK_ULONG count, CK_KEY_TYPE key_type, + SECItem *pubkey, SDB *sdbpw) { NSSLOWKEYPrivateKey *privKey = 0; PLArenaPool *arena = 0; @@ -762,17 +783,23 @@ static NSSLOWKEYPrivateKey *lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, static unsigned char derZero[1] = { 0 }; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { crv = CKR_HOST_MEMORY; goto loser; } + if (arena == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } privKey = (NSSLOWKEYPrivateKey *) - PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey)); - if (privKey == NULL) { crv = CKR_HOST_MEMORY; goto loser; } + PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPrivateKey)); + if (privKey == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } privKey->arena = arena; - /* Secret keys are represented in the database as "fake" RSA keys. - * The RSA key is marked as a secret key representation by setting the - * public exponent field to 0, which is an invalid RSA exponent. + /* Secret keys are represented in the database as "fake" RSA keys. + * The RSA key is marked as a secret key representation by setting the + * public exponent field to 0, which is an invalid RSA exponent. * The other fields are set as follows: * modulus - CKA_ID value for the secret key * private exponent - CKA_VALUE (the key itself) @@ -784,10 +811,10 @@ static NSSLOWKEYPrivateKey *lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, /* The modulus is set to the key id of the symmetric key */ privKey->u.rsa.modulus.data = - (unsigned char *) PORT_ArenaAlloc(arena, pubkey->len); + (unsigned char *)PORT_ArenaAlloc(arena, pubkey->len); if (privKey->u.rsa.modulus.data == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } privKey->u.rsa.modulus.len = pubkey->len; PORT_Memcpy(privKey->u.rsa.modulus.data, pubkey->data, pubkey->len); @@ -798,8 +825,9 @@ static NSSLOWKEYPrivateKey *lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, /* The private exponent is the actual key value */ crv = lg_PrivAttr2SecItem(arena, CKA_VALUE, templ, count, - &privKey->u.rsa.privateExponent, sdbpw); - if (crv != CKR_OK) goto loser; + &privKey->u.rsa.privateExponent, sdbpw); + if (crv != CKR_OK) + goto loser; /* All other fields empty - needs testing */ privKey->u.rsa.prime1.len = sizeof derZero; @@ -816,43 +844,47 @@ static NSSLOWKEYPrivateKey *lg_mkSecretKeyRep(const CK_ATTRIBUTE *templ, /* Coeficient set to KEY_TYPE */ crv = lg_GetULongAttribute(CKA_KEY_TYPE, templ, count, &keyType); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; /* on 64 bit platforms, we still want to store 32 bits of keyType (This is * safe since the PKCS #11 defines for all types are 32 bits or less). */ - keyTypeStorage = (PRUint32) keyType; + keyTypeStorage = (PRUint32)keyType; keyTypeStorage = PR_htonl(keyTypeStorage); keyTypeItem.data = (unsigned char *)&keyTypeStorage; - keyTypeItem.len = sizeof (keyTypeStorage); + keyTypeItem.len = sizeof(keyTypeStorage); rv = SECITEM_CopyItem(arena, &privKey->u.rsa.coefficient, &keyTypeItem); if (rv != SECSuccess) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } - + /* Private key version field set normally for compatibility */ - rv = DER_SetUInteger(privKey->arena, - &privKey->u.rsa.version, NSSLOWKEY_VERSION); - if (rv != SECSuccess) { crv = CKR_HOST_MEMORY; goto loser; } + rv = DER_SetUInteger(privKey->arena, + &privKey->u.rsa.version, NSSLOWKEY_VERSION); + if (rv != SECSuccess) { + crv = CKR_HOST_MEMORY; + goto loser; + } loser: if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - privKey = 0; + PORT_FreeArena(arena, PR_FALSE); + privKey = 0; } return privKey; } /* - * check the consistancy and initialize a Secret Key Object + * check the consistancy and initialize a Secret Key Object */ static CK_RV lg_createSecretKeyObject(SDB *sdb, CK_KEY_TYPE key_type, - CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) + CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) { CK_RV crv; - NSSLOWKEYPrivateKey *privKey = NULL; - NSSLOWKEYDBHandle *keyHandle = NULL; + NSSLOWKEYPrivateKey *privKey = NULL; + NSSLOWKEYDBHandle *keyHandle = NULL; SECItem pubKey; char *label = NULL; SECStatus rv = SECSuccess; @@ -863,54 +895,59 @@ lg_createSecretKeyObject(SDB *sdb, CK_KEY_TYPE key_type, keyHandle = lg_getKeyDB(sdb); if (keyHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - label = lg_getString(CKA_LABEL,templ,count); + label = lg_getString(CKA_LABEL, templ, count); - crv = lg_Attribute2SecItem(NULL,CKA_ID,templ,count,&pubKey); - /* Should this be ID? */ - if (crv != CKR_OK) goto loser; + crv = lg_Attribute2SecItem(NULL, CKA_ID, templ, count, &pubKey); + /* Should this be ID? */ + if (crv != CKR_OK) + goto loser; /* if we don't have an ID, generate one */ if (pubKey.len == 0) { - if (pubKey.data) { - PORT_Free(pubKey.data); - pubKey.data = NULL; - } - crv = lg_GenerateSecretCKA_ID(keyHandle, &pubKey, label); - if (crv != CKR_OK) goto loser; + if (pubKey.data) { + PORT_Free(pubKey.data); + pubKey.data = NULL; + } + crv = lg_GenerateSecretCKA_ID(keyHandle, &pubKey, label); + if (crv != CKR_OK) + goto loser; } privKey = lg_mkSecretKeyRep(templ, count, key_type, &pubKey, sdb); if (privKey == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } rv = nsslowkey_StoreKeyByPublicKey(keyHandle, - privKey, &pubKey, label, sdb /*->password*/); + privKey, &pubKey, label, sdb /*->password*/); if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - goto loser; + crv = CKR_DEVICE_ERROR; + goto loser; } *handle = lg_mkHandle(sdb, &pubKey, LG_TOKEN_TYPE_KEY); loser: - if (label) PORT_Free(label); - if (privKey) lg_nsslowkey_DestroyPrivateKey(privKey); - if (pubKey.data) PORT_Free(pubKey.data); + if (label) + PORT_Free(label); + if (privKey) + lg_nsslowkey_DestroyPrivateKey(privKey); + if (pubKey.data) + PORT_Free(pubKey.data); return crv; } /* - * check the consistancy and initialize a Key Object + * check the consistancy and initialize a Key Object */ static CK_RV -lg_createKeyObject(SDB *sdb, CK_OBJECT_CLASS objclass, - CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) +lg_createKeyObject(SDB *sdb, CK_OBJECT_CLASS objclass, + CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count) { CK_RV crv; CK_KEY_TYPE key_type; @@ -918,29 +955,29 @@ lg_createKeyObject(SDB *sdb, CK_OBJECT_CLASS objclass, /* get the key type */ crv = lg_GetULongAttribute(CKA_KEY_TYPE, templ, count, &key_type); if (crv != CKR_OK) { - return crv; + return crv; } switch (objclass) { - case CKO_PUBLIC_KEY: - return lg_createPublicKeyObject(sdb,key_type,handle,templ,count); - case CKO_PRIVATE_KEY: - return lg_createPrivateKeyObject(sdb,key_type,handle,templ,count); - case CKO_SECRET_KEY: - return lg_createSecretKeyObject(sdb,key_type,handle,templ,count); - default: - break; + case CKO_PUBLIC_KEY: + return lg_createPublicKeyObject(sdb, key_type, handle, templ, count); + case CKO_PRIVATE_KEY: + return lg_createPrivateKeyObject(sdb, key_type, handle, templ, count); + case CKO_SECRET_KEY: + return lg_createSecretKeyObject(sdb, key_type, handle, templ, count); + default: + break; } return CKR_ATTRIBUTE_VALUE_INVALID; } -/* +/* * Parse the template and create an object stored in the DB that reflects. * the object specified in the database. */ CK_RV lg_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count) + const CK_ATTRIBUTE *templ, CK_ULONG count) { CK_RV crv; CK_OBJECT_CLASS objclass; @@ -948,34 +985,33 @@ lg_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *handle, /* get the object class */ crv = lg_GetULongAttribute(CKA_CLASS, templ, count, &objclass); if (crv != CKR_OK) { - return crv; + return crv; } - /* Now handle the specific object class. + /* Now handle the specific object class. */ switch (objclass) { - case CKO_CERTIFICATE: - crv = lg_createCertObject(sdb,handle,templ,count); - break; - case CKO_NSS_TRUST: - crv = lg_createTrustObject(sdb,handle,templ,count); - break; - case CKO_NSS_CRL: - crv = lg_createCrlObject(sdb,handle,templ,count); - break; - case CKO_NSS_SMIME: - crv = lg_createSMimeObject(sdb,handle,templ,count); - break; - case CKO_PRIVATE_KEY: - case CKO_PUBLIC_KEY: - case CKO_SECRET_KEY: - crv = lg_createKeyObject(sdb,objclass,handle,templ,count); - break; - default: - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; + case CKO_CERTIFICATE: + crv = lg_createCertObject(sdb, handle, templ, count); + break; + case CKO_NSS_TRUST: + crv = lg_createTrustObject(sdb, handle, templ, count); + break; + case CKO_NSS_CRL: + crv = lg_createCrlObject(sdb, handle, templ, count); + break; + case CKO_NSS_SMIME: + crv = lg_createSMimeObject(sdb, handle, templ, count); + break; + case CKO_PRIVATE_KEY: + case CKO_PUBLIC_KEY: + case CKO_SECRET_KEY: + crv = lg_createKeyObject(sdb, objclass, handle, templ, count); + break; + default: + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; } return crv; } - diff --git a/nss/lib/softoken/legacydb/lgdb.h b/nss/lib/softoken/legacydb/lgdb.h index c67bffa..ee80f4b 100644 --- a/nss/lib/softoken/legacydb/lgdb.h +++ b/nss/lib/softoken/legacydb/lgdb.h @@ -13,12 +13,10 @@ #include "lowkeyti.h" #include "pkcs11t.h" #include "sdb.h" -#include "cdbhdl.h" - +#include "cdbhdl.h" #define MULTIACCESS "multiaccess:" - /* path stuff (was machine dependent) used by dbinit.c and pk11db.c */ #define PATH_SEPARATOR "/" #define SECMOD_DB "secmod.db" @@ -27,39 +25,37 @@ SEC_BEGIN_PROTOS - /* internal utility functions used by pkcs11.c */ extern const CK_ATTRIBUTE *lg_FindAttribute(CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count); -extern CK_RV lg_Attribute2SecItem(PLArenaPool *,CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item); -extern CK_RV lg_Attribute2SSecItem(PLArenaPool *,CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item); -extern CK_RV lg_PrivAttr2SecItem(PLArenaPool *,CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item, SDB *sdbpw); -extern CK_RV lg_PrivAttr2SSecItem(PLArenaPool *,CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item, SDB *sdbpw); + const CK_ATTRIBUTE *templ, CK_ULONG count); +extern CK_RV lg_Attribute2SecItem(PLArenaPool *, CK_ATTRIBUTE_TYPE type, + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item); +extern CK_RV lg_Attribute2SSecItem(PLArenaPool *, CK_ATTRIBUTE_TYPE type, + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item); +extern CK_RV lg_PrivAttr2SecItem(PLArenaPool *, CK_ATTRIBUTE_TYPE type, + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item, SDB *sdbpw); +extern CK_RV lg_PrivAttr2SSecItem(PLArenaPool *, CK_ATTRIBUTE_TYPE type, + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item, SDB *sdbpw); extern CK_RV lg_GetULongAttribute(CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - CK_ULONG *out); + const CK_ATTRIBUTE *templ, CK_ULONG count, + CK_ULONG *out); extern PRBool lg_hasAttribute(CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count); + const CK_ATTRIBUTE *templ, CK_ULONG count); extern PRBool lg_isTrue(CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count); + const CK_ATTRIBUTE *templ, CK_ULONG count); extern PRBool lg_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass); extern char *lg_getString(CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count); + const CK_ATTRIBUTE *templ, CK_ULONG count); extern unsigned int lg_MapTrust(CK_TRUST trust, PRBool clientAuth); /* clear out all the existing object ID to database key mappings. * used to reinit a token */ extern CK_RV lg_ClearTokenKeyHashTable(SDB *sdb); - extern void lg_FreeSearch(SDBFind *search); NSSLOWCERTCertDBHandle *lg_getCertDB(SDB *sdb); @@ -67,28 +63,30 @@ NSSLOWKEYDBHandle *lg_getKeyDB(SDB *sdb); const char *lg_EvaluateConfigDir(const char *configdir, char **domain); +/* verify the FIPS selftests ran and were successful */ +PRBool lg_FIPSEntryOK(void); /* * object handle modifiers */ -#define LG_TOKEN_MASK 0xc0000000L -#define LG_TOKEN_TYPE_MASK 0x38000000L -#define LG_TOKEN_TYPE_SHIFT 27 +#define LG_TOKEN_MASK 0xc0000000L +#define LG_TOKEN_TYPE_MASK 0x38000000L +#define LG_TOKEN_TYPE_SHIFT 27 /* keydb (high bit == 0) */ -#define LG_TOKEN_TYPE_PRIV 0x08000000L -#define LG_TOKEN_TYPE_PUB 0x10000000L -#define LG_TOKEN_TYPE_KEY 0x18000000L +#define LG_TOKEN_TYPE_PRIV 0x08000000L +#define LG_TOKEN_TYPE_PUB 0x10000000L +#define LG_TOKEN_TYPE_KEY 0x18000000L /* certdb (high bit == 1) */ -#define LG_TOKEN_TYPE_TRUST 0x20000000L -#define LG_TOKEN_TYPE_CRL 0x28000000L -#define LG_TOKEN_TYPE_SMIME 0x30000000L -#define LG_TOKEN_TYPE_CERT 0x38000000L +#define LG_TOKEN_TYPE_TRUST 0x20000000L +#define LG_TOKEN_TYPE_CRL 0x28000000L +#define LG_TOKEN_TYPE_SMIME 0x30000000L +#define LG_TOKEN_TYPE_CERT 0x38000000L -#define LG_TOKEN_KRL_HANDLE (LG_TOKEN_TYPE_CRL|1) +#define LG_TOKEN_KRL_HANDLE (LG_TOKEN_TYPE_CRL | 1) -#define LG_SEARCH_BLOCK_SIZE 10 -#define LG_BUF_SPACE 50 -#define LG_STRICT PR_FALSE +#define LG_SEARCH_BLOCK_SIZE 10 +#define LG_BUF_SPACE 50 +#define LG_STRICT PR_FALSE /* * token object utilities @@ -96,48 +94,47 @@ const char *lg_EvaluateConfigDir(const char *configdir, char **domain); void lg_addHandle(SDBFind *search, CK_OBJECT_HANDLE handle); PRBool lg_poisonHandle(SDB *sdb, SECItem *dbkey, CK_OBJECT_HANDLE handle); PRBool lg_tokenMatch(SDB *sdb, const SECItem *dbKey, CK_OBJECT_HANDLE class, - const CK_ATTRIBUTE *templ, CK_ULONG count); + const CK_ATTRIBUTE *templ, CK_ULONG count); const SECItem *lg_lookupTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle); CK_OBJECT_HANDLE lg_mkHandle(SDB *sdb, SECItem *dbKey, CK_OBJECT_HANDLE class); SECStatus lg_deleteTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle); -SECStatus lg_util_encrypt(PLArenaPool *arena, SDB *sdbpw, - SECItem *plainText, SECItem **cipherText); -SECStatus lg_util_decrypt(SDB *sdbpw, - SECItem *cipherText, SECItem **plainText); +SECStatus lg_util_encrypt(PLArenaPool *arena, SDB *sdbpw, + SECItem *plainText, SECItem **cipherText); +SECStatus lg_util_decrypt(SDB *sdbpw, + SECItem *cipherText, SECItem **plainText); PLHashTable *lg_GetHashTable(SDB *sdb); void lg_DBLock(SDB *sdb); void lg_DBUnlock(SDB *sdb); typedef void (*LGFreeFunc)(void *); - /* * database functions */ -/* lg_FindObjectsInit initializes a search for token and session objects +/* lg_FindObjectsInit initializes a search for token and session objects * that match a template. */ -CK_RV lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, - CK_ULONG ulCount, SDBFind **search); -/* lg_FindObjects continues a search for token and session objects +CK_RV lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, + CK_ULONG ulCount, SDBFind **search); +/* lg_FindObjects continues a search for token and session objects * that match a template, obtaining additional object handles. */ -CK_RV lg_FindObjects(SDB *sdb, SDBFind *search, - CK_OBJECT_HANDLE *phObject,CK_ULONG ulMaxObjectCount, - CK_ULONG *pulObjectCount); +CK_RV lg_FindObjects(SDB *sdb, SDBFind *search, + CK_OBJECT_HANDLE *phObject, CK_ULONG ulMaxObjectCount, + CK_ULONG *pulObjectCount); /* lg_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV lg_FindObjectsFinal(SDB* lgdb, SDBFind *search); +CK_RV lg_FindObjectsFinal(SDB *lgdb, SDBFind *search); -/* lg_CreateObject parses the template and create an object stored in the +/* lg_CreateObject parses the template and create an object stored in the * DB that reflects the object specified in the template. */ CK_RV lg_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *handle, - const CK_ATTRIBUTE *templ, CK_ULONG count); + const CK_ATTRIBUTE *templ, CK_ULONG count); -CK_RV lg_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, - CK_ATTRIBUTE *template, CK_ULONG count); -CK_RV lg_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, - const CK_ATTRIBUTE *template, CK_ULONG count); +CK_RV lg_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, + CK_ATTRIBUTE *template, CK_ULONG count); +CK_RV lg_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, + const CK_ATTRIBUTE *template, CK_ULONG count); CK_RV lg_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id); CK_RV lg_Close(SDB *sdb); @@ -151,8 +148,8 @@ CK_RV lg_Begin(SDB *sdb); CK_RV lg_Commit(SDB *sdb); CK_RV lg_Abort(SDB *sdb); CK_RV lg_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2); -CK_RV lg_PutMetaData(SDB *sdb, const char *id, - const SECItem *item1, const SECItem *item2); +CK_RV lg_PutMetaData(SDB *sdb, const char *id, + const SECItem *item1, const SECItem *item2); SEC_END_PROTOS @@ -165,7 +162,9 @@ SEC_END_PROTOS #ifndef NO_FORK_CHECK extern PRBool lg_parentForkedAfterC_Initialize; -#define SKIP_AFTER_FORK(x) if (!lg_parentForkedAfterC_Initialize) x +#define SKIP_AFTER_FORK(x) \ + if (!lg_parentForkedAfterC_Initialize) \ + x #else @@ -174,4 +173,3 @@ extern PRBool lg_parentForkedAfterC_Initialize; #endif /* NO_FORK_CHECK */ #endif /* _LGDB_H_ */ - diff --git a/nss/lib/softoken/legacydb/lgdestroy.c b/nss/lib/softoken/legacydb/lgdestroy.c index 914da51..1e3839d 100644 --- a/nss/lib/softoken/legacydb/lgdestroy.c +++ b/nss/lib/softoken/legacydb/lgdestroy.c @@ -25,87 +25,86 @@ lg_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id) const SECItem *dbKey; object_id &= ~LG_TOKEN_MASK; - dbKey = lg_lookupTokenKeyByHandle(sdb,object_id); + dbKey = lg_lookupTokenKeyByHandle(sdb, object_id); if (dbKey == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } /* remove the objects from the real data base */ switch (object_id & LG_TOKEN_TYPE_MASK) { - case LG_TOKEN_TYPE_PRIV: - case LG_TOKEN_TYPE_KEY: - /* KEYID is the public KEY for DSA and DH, and the MODULUS for - * RSA */ - keyHandle = lg_getKeyDB(sdb); - if (!keyHandle) { - crv = CKR_TOKEN_WRITE_PROTECTED; - break; - } - rv = nsslowkey_DeleteKey(keyHandle, dbKey); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - } - break; - case LG_TOKEN_TYPE_PUB: - break; /* public keys only exist at the behest of the priv key */ - case LG_TOKEN_TYPE_CERT: - certHandle = lg_getCertDB(sdb); - if (!certHandle) { - crv = CKR_TOKEN_WRITE_PROTECTED; - break; - } - cert = nsslowcert_FindCertByKey(certHandle,dbKey); - if (cert == NULL) { - crv = CKR_DEVICE_ERROR; - break; - } - rv = nsslowcert_DeletePermCertificate(cert); - if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - } - nsslowcert_DestroyCertificate(cert); - break; - case LG_TOKEN_TYPE_CRL: - certHandle = lg_getCertDB(sdb); - if (!certHandle) { - crv = CKR_TOKEN_WRITE_PROTECTED; - break; - } - isKrl = (PRBool) (object_id == LG_TOKEN_KRL_HANDLE); - rv = nsslowcert_DeletePermCRL(certHandle, dbKey, isKrl); - if (rv == SECFailure) crv = CKR_DEVICE_ERROR; - break; - case LG_TOKEN_TYPE_TRUST: - certHandle = lg_getCertDB(sdb); - if (!certHandle) { - crv = CKR_TOKEN_WRITE_PROTECTED; - break; - } - cert = nsslowcert_FindCertByKey(certHandle, dbKey); - if (cert == NULL) { - crv = CKR_DEVICE_ERROR; - break; - } - tmptrust = *cert->trust; - tmptrust.sslFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.emailFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.objectSigningFlags &= CERTDB_PRESERVE_TRUST_BITS; - tmptrust.sslFlags |= CERTDB_TRUSTED_UNKNOWN; - tmptrust.emailFlags |= CERTDB_TRUSTED_UNKNOWN; - tmptrust.objectSigningFlags |= CERTDB_TRUSTED_UNKNOWN; - rv = nsslowcert_ChangeCertTrust(certHandle, cert, &tmptrust); - if (rv != SECSuccess) crv = CKR_DEVICE_ERROR; - nsslowcert_DestroyCertificate(cert); - break; - default: - break; + case LG_TOKEN_TYPE_PRIV: + case LG_TOKEN_TYPE_KEY: + /* KEYID is the public KEY for DSA and DH, and the MODULUS for + * RSA */ + keyHandle = lg_getKeyDB(sdb); + if (!keyHandle) { + crv = CKR_TOKEN_WRITE_PROTECTED; + break; + } + rv = nsslowkey_DeleteKey(keyHandle, dbKey); + if (rv != SECSuccess) { + crv = CKR_DEVICE_ERROR; + } + break; + case LG_TOKEN_TYPE_PUB: + break; /* public keys only exist at the behest of the priv key */ + case LG_TOKEN_TYPE_CERT: + certHandle = lg_getCertDB(sdb); + if (!certHandle) { + crv = CKR_TOKEN_WRITE_PROTECTED; + break; + } + cert = nsslowcert_FindCertByKey(certHandle, dbKey); + if (cert == NULL) { + crv = CKR_DEVICE_ERROR; + break; + } + rv = nsslowcert_DeletePermCertificate(cert); + if (rv != SECSuccess) { + crv = CKR_DEVICE_ERROR; + } + nsslowcert_DestroyCertificate(cert); + break; + case LG_TOKEN_TYPE_CRL: + certHandle = lg_getCertDB(sdb); + if (!certHandle) { + crv = CKR_TOKEN_WRITE_PROTECTED; + break; + } + isKrl = (PRBool)(object_id == LG_TOKEN_KRL_HANDLE); + rv = nsslowcert_DeletePermCRL(certHandle, dbKey, isKrl); + if (rv == SECFailure) + crv = CKR_DEVICE_ERROR; + break; + case LG_TOKEN_TYPE_TRUST: + certHandle = lg_getCertDB(sdb); + if (!certHandle) { + crv = CKR_TOKEN_WRITE_PROTECTED; + break; + } + cert = nsslowcert_FindCertByKey(certHandle, dbKey); + if (cert == NULL) { + crv = CKR_DEVICE_ERROR; + break; + } + tmptrust = *cert->trust; + tmptrust.sslFlags &= CERTDB_PRESERVE_TRUST_BITS; + tmptrust.emailFlags &= CERTDB_PRESERVE_TRUST_BITS; + tmptrust.objectSigningFlags &= CERTDB_PRESERVE_TRUST_BITS; + tmptrust.sslFlags |= CERTDB_TRUSTED_UNKNOWN; + tmptrust.emailFlags |= CERTDB_TRUSTED_UNKNOWN; + tmptrust.objectSigningFlags |= CERTDB_TRUSTED_UNKNOWN; + rv = nsslowcert_ChangeCertTrust(certHandle, cert, &tmptrust); + if (rv != SECSuccess) + crv = CKR_DEVICE_ERROR; + nsslowcert_DestroyCertificate(cert); + break; + default: + break; } lg_DBLock(sdb); - lg_deleteTokenKeyByHandle(sdb,object_id); + lg_deleteTokenKeyByHandle(sdb, object_id); lg_DBUnlock(sdb); return crv; } - - - diff --git a/nss/lib/softoken/legacydb/lgfind.c b/nss/lib/softoken/legacydb/lgfind.c index a512cba..288e56c 100644 --- a/nss/lib/softoken/legacydb/lgfind.c +++ b/nss/lib/softoken/legacydb/lgfind.c @@ -8,7 +8,7 @@ #include "pcert.h" #include "blapi.h" -#include "keydbi.h" +#include "keydbi.h" /* * This code maps PKCS #11 Finds to legacy database searches. This code @@ -16,13 +16,12 @@ */ struct SDBFindStr { - CK_OBJECT_HANDLE *handles; - int size; - int index; - int array_size; + CK_OBJECT_HANDLE *handles; + int size; + int index; + int array_size; }; - /* * free a search structure */ @@ -30,7 +29,7 @@ void lg_FreeSearch(SDBFind *search) { if (search->handles) { - PORT_Free(search->handles); + PORT_Free(search->handles); } PORT_Free(search); } @@ -39,15 +38,15 @@ void lg_addHandle(SDBFind *search, CK_OBJECT_HANDLE handle) { if (search->handles == NULL) { - return; + return; } if (search->size >= search->array_size) { - search->array_size += LG_SEARCH_BLOCK_SIZE; - search->handles = (CK_OBJECT_HANDLE *) PORT_Realloc(search->handles, - sizeof(CK_OBJECT_HANDLE)* search->array_size); - if (search->handles == NULL) { - return; - } + search->array_size += LG_SEARCH_BLOCK_SIZE; + search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles, + sizeof(CK_OBJECT_HANDLE) * search->array_size); + if (search->handles == NULL) { + return; + } } search->handles[search->size] = handle; search->size++; @@ -56,13 +55,13 @@ lg_addHandle(SDBFind *search, CK_OBJECT_HANDLE handle) /* * find any certs that may match the template and load them. */ -#define LG_CERT 0x00000001 -#define LG_TRUST 0x00000002 -#define LG_CRL 0x00000004 -#define LG_SMIME 0x00000008 -#define LG_PRIVATE 0x00000010 -#define LG_PUBLIC 0x00000020 -#define LG_KEY 0x00000040 +#define LG_CERT 0x00000001 +#define LG_TRUST 0x00000002 +#define LG_CRL 0x00000004 +#define LG_SMIME 0x00000008 +#define LG_PRIVATE 0x00000010 +#define LG_PUBLIC 0x00000020 +#define LG_KEY 0x00000040 /* * structure to collect key handles. @@ -74,60 +73,58 @@ typedef struct lgEntryDataStr { CK_ULONG templ_count; } lgEntryData; - static SECStatus lg_crl_collect(SECItem *data, SECItem *key, certDBEntryType type, void *arg) { lgEntryData *crlData; CK_OBJECT_HANDLE class_handle; SDB *sdb; - + crlData = (lgEntryData *)arg; sdb = crlData->sdb; - class_handle = (type == certDBEntryTypeRevocation) ? LG_TOKEN_TYPE_CRL : - LG_TOKEN_KRL_HANDLE; + class_handle = (type == certDBEntryTypeRevocation) ? LG_TOKEN_TYPE_CRL : LG_TOKEN_KRL_HANDLE; if (lg_tokenMatch(sdb, key, class_handle, - crlData->template, crlData->templ_count)) { - lg_addHandle(crlData->searchHandles, - lg_mkHandle(sdb,key,class_handle)); + crlData->template, crlData->templ_count)) { + lg_addHandle(crlData->searchHandles, + lg_mkHandle(sdb, key, class_handle)); } - return(SECSuccess); + return (SECSuccess); } static void -lg_searchCrls(SDB *sdb, SECItem *derSubject, PRBool isKrl, - unsigned long classFlags, SDBFind *search, - const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) +lg_searchCrls(SDB *sdb, SECItem *derSubject, PRBool isKrl, + unsigned long classFlags, SDBFind *search, + const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) { NSSLOWCERTCertDBHandle *certHandle = NULL; certHandle = lg_getCertDB(sdb); if (certHandle == NULL) { - return; + return; } - if (derSubject->data != NULL) { - certDBEntryRevocation *crl = - nsslowcert_FindCrlByKey(certHandle, derSubject, isKrl); + if (derSubject->data != NULL) { + certDBEntryRevocation *crl = + nsslowcert_FindCrlByKey(certHandle, derSubject, isKrl); - if (crl != NULL) { - lg_addHandle(search, lg_mkHandle(sdb, derSubject, - isKrl ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL)); - nsslowcert_DestroyDBEntry((certDBEntry *)crl); - } + if (crl != NULL) { + lg_addHandle(search, lg_mkHandle(sdb, derSubject, + isKrl ? LG_TOKEN_KRL_HANDLE : LG_TOKEN_TYPE_CRL)); + nsslowcert_DestroyDBEntry((certDBEntry *)crl); + } } else { - lgEntryData crlData; - - /* traverse */ - crlData.sdb = sdb; - crlData.searchHandles = search; - crlData.template = pTemplate; - crlData.templ_count = ulCount; - nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeRevocation, - lg_crl_collect, (void *)&crlData); - nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeKeyRevocation, - lg_crl_collect, (void *)&crlData); - } + lgEntryData crlData; + + /* traverse */ + crlData.sdb = sdb; + crlData.searchHandles = search; + crlData.template = pTemplate; + crlData.templ_count = ulCount; + nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeRevocation, + lg_crl_collect, (void *)&crlData); + nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeKeyRevocation, + lg_crl_collect, (void *)&crlData); + } } /* @@ -147,16 +144,14 @@ typedef struct lgKeyDataStr { static PRBool isSecretKey(NSSLOWKEYPrivateKey *privKey) { - if (privKey->keyType == NSSLOWKEYRSAKey && - privKey->u.rsa.publicExponent.len == 1 && - privKey->u.rsa.publicExponent.data[0] == 0) - return PR_TRUE; + if (privKey->keyType == NSSLOWKEYRSAKey && + privKey->u.rsa.publicExponent.len == 1 && + privKey->u.rsa.publicExponent.data[0] == 0) + return PR_TRUE; - return PR_FALSE; + return PR_FALSE; } - - static SECStatus lg_key_collect(DBT *key, DBT *data, void *arg) { @@ -165,7 +160,7 @@ lg_key_collect(DBT *key, DBT *data, void *arg) SECItem tmpDBKey; SDB *sdb; unsigned long classFlags; - + keyData = (lgKeyData *)arg; sdb = keyData->sdb; classFlags = keyData->classFlags; @@ -176,97 +171,95 @@ lg_key_collect(DBT *key, DBT *data, void *arg) PORT_Assert(keyData->keyHandle); if (!keyData->strict && keyData->id && keyData->id->data) { - SECItem result; - PRBool haveMatch= PR_FALSE; - unsigned char hashKey[SHA1_LENGTH]; - result.data = hashKey; - result.len = sizeof(hashKey); - - if (keyData->id->len == 0) { - /* Make sure this isn't a LG_KEY */ - privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle, - &tmpDBKey, keyData->sdb/*->password*/); - if (privKey) { - /* turn off the unneeded class flags */ - classFlags &= isSecretKey(privKey) ? ~(LG_PRIVATE|LG_PUBLIC) : - ~LG_KEY; - haveMatch = (PRBool) - ((classFlags & (LG_KEY|LG_PRIVATE|LG_PUBLIC)) != 0); - lg_nsslowkey_DestroyPrivateKey(privKey); - } - } else { - SHA1_HashBuf( hashKey, key->data, key->size ); /* match id */ - haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result); - if (!haveMatch && ((unsigned char *)key->data)[0] == 0) { - /* This is a fix for backwards compatibility. The key - * database indexes private keys by the public key, and - * versions of NSS prior to 3.4 stored the public key as - * a signed integer. The public key is now treated as an - * unsigned integer, with no leading zero. In order to - * correctly compute the hash of an old key, it is necessary - * to fallback and detect the leading zero. - */ - SHA1_HashBuf(hashKey, - (unsigned char *)key->data + 1, key->size - 1); - haveMatch = SECITEM_ItemsAreEqual(keyData->id,&result); - } - } - if (haveMatch) { - if (classFlags & LG_PRIVATE) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(sdb,&tmpDBKey,LG_TOKEN_TYPE_PRIV)); - } - if (classFlags & LG_PUBLIC) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(sdb,&tmpDBKey,LG_TOKEN_TYPE_PUB)); - } - if (classFlags & LG_KEY) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(sdb,&tmpDBKey,LG_TOKEN_TYPE_KEY)); - } - } - return SECSuccess; - } - - privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle, &tmpDBKey, - keyData->sdb/*->password*/); - if ( privKey == NULL ) { - goto loser; + SECItem result; + PRBool haveMatch = PR_FALSE; + unsigned char hashKey[SHA1_LENGTH]; + result.data = hashKey; + result.len = sizeof(hashKey); + + if (keyData->id->len == 0) { + /* Make sure this isn't a LG_KEY */ + privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle, + &tmpDBKey, keyData->sdb /*->password*/); + if (privKey) { + /* turn off the unneeded class flags */ + classFlags &= isSecretKey(privKey) ? ~(LG_PRIVATE | LG_PUBLIC) : ~LG_KEY; + haveMatch = (PRBool)((classFlags & (LG_KEY | LG_PRIVATE | LG_PUBLIC)) != 0); + lg_nsslowkey_DestroyPrivateKey(privKey); + } + } else { + SHA1_HashBuf(hashKey, key->data, key->size); /* match id */ + haveMatch = SECITEM_ItemsAreEqual(keyData->id, &result); + if (!haveMatch && ((unsigned char *)key->data)[0] == 0) { + /* This is a fix for backwards compatibility. The key + * database indexes private keys by the public key, and + * versions of NSS prior to 3.4 stored the public key as + * a signed integer. The public key is now treated as an + * unsigned integer, with no leading zero. In order to + * correctly compute the hash of an old key, it is necessary + * to fallback and detect the leading zero. + */ + SHA1_HashBuf(hashKey, + (unsigned char *)key->data + 1, key->size - 1); + haveMatch = SECITEM_ItemsAreEqual(keyData->id, &result); + } + } + if (haveMatch) { + if (classFlags & LG_PRIVATE) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(sdb, &tmpDBKey, LG_TOKEN_TYPE_PRIV)); + } + if (classFlags & LG_PUBLIC) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(sdb, &tmpDBKey, LG_TOKEN_TYPE_PUB)); + } + if (classFlags & LG_KEY) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(sdb, &tmpDBKey, LG_TOKEN_TYPE_KEY)); + } + } + return SECSuccess; + } + + privKey = nsslowkey_FindKeyByPublicKey(keyData->keyHandle, &tmpDBKey, + keyData->sdb /*->password*/); + if (privKey == NULL) { + goto loser; } if (isSecretKey(privKey)) { - if ((classFlags & LG_KEY) && - lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_KEY, - keyData->template, keyData->templ_count)) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_KEY)); - } + if ((classFlags & LG_KEY) && + lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_KEY, + keyData->template, keyData->templ_count)) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_KEY)); + } } else { - if ((classFlags & LG_PRIVATE) && - lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PRIV, - keyData->template, keyData->templ_count)) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(keyData->sdb,&tmpDBKey,LG_TOKEN_TYPE_PRIV)); - } - if ((classFlags & LG_PUBLIC) && - lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PUB, - keyData->template, keyData->templ_count)) { - lg_addHandle(keyData->searchHandles, - lg_mkHandle(keyData->sdb, &tmpDBKey,LG_TOKEN_TYPE_PUB)); - } + if ((classFlags & LG_PRIVATE) && + lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PRIV, + keyData->template, keyData->templ_count)) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PRIV)); + } + if ((classFlags & LG_PUBLIC) && + lg_tokenMatch(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PUB, + keyData->template, keyData->templ_count)) { + lg_addHandle(keyData->searchHandles, + lg_mkHandle(keyData->sdb, &tmpDBKey, LG_TOKEN_TYPE_PUB)); + } } loser: - if ( privKey ) { - lg_nsslowkey_DestroyPrivateKey(privKey); + if (privKey) { + lg_nsslowkey_DestroyPrivateKey(privKey); } - return(SECSuccess); + return (SECSuccess); } static void lg_searchKeys(SDB *sdb, SECItem *key_id, - unsigned long classFlags, SDBFind *search, PRBool mustStrict, - const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) + unsigned long classFlags, SDBFind *search, PRBool mustStrict, + const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) { NSSLOWKEYDBHandle *keyHandle = NULL; NSSLOWKEYPrivateKey *privKey; @@ -275,42 +268,42 @@ lg_searchKeys(SDB *sdb, SECItem *key_id, keyHandle = lg_getKeyDB(sdb); if (keyHandle == NULL) { - return; + return; } if (key_id->data) { - privKey = nsslowkey_FindKeyByPublicKey(keyHandle, key_id, sdb); - if (privKey) { - if ((classFlags & LG_KEY) && isSecretKey(privKey)) { - lg_addHandle(search, - lg_mkHandle(sdb,key_id,LG_TOKEN_TYPE_KEY)); - found = PR_TRUE; - } - if ((classFlags & LG_PRIVATE) && !isSecretKey(privKey)) { - lg_addHandle(search, - lg_mkHandle(sdb,key_id,LG_TOKEN_TYPE_PRIV)); - found = PR_TRUE; - } - if ((classFlags & LG_PUBLIC) && !isSecretKey(privKey)) { - lg_addHandle(search, - lg_mkHandle(sdb,key_id,LG_TOKEN_TYPE_PUB)); - found = PR_TRUE; - } - lg_nsslowkey_DestroyPrivateKey(privKey); - } - /* don't do the traversal if we have an up to date db */ - if (keyHandle->version != 3) { - goto loser; - } - /* don't do the traversal if it can't possibly be the correct id */ - /* all soft token id's are SHA1_HASH_LEN's */ - if (key_id->len != SHA1_LENGTH) { - goto loser; - } - if (found) { - /* if we already found some keys, don't do the traversal */ - goto loser; - } + privKey = nsslowkey_FindKeyByPublicKey(keyHandle, key_id, sdb); + if (privKey) { + if ((classFlags & LG_KEY) && isSecretKey(privKey)) { + lg_addHandle(search, + lg_mkHandle(sdb, key_id, LG_TOKEN_TYPE_KEY)); + found = PR_TRUE; + } + if ((classFlags & LG_PRIVATE) && !isSecretKey(privKey)) { + lg_addHandle(search, + lg_mkHandle(sdb, key_id, LG_TOKEN_TYPE_PRIV)); + found = PR_TRUE; + } + if ((classFlags & LG_PUBLIC) && !isSecretKey(privKey)) { + lg_addHandle(search, + lg_mkHandle(sdb, key_id, LG_TOKEN_TYPE_PUB)); + found = PR_TRUE; + } + lg_nsslowkey_DestroyPrivateKey(privKey); + } + /* don't do the traversal if we have an up to date db */ + if (keyHandle->version != 3) { + goto loser; + } + /* don't do the traversal if it can't possibly be the correct id */ + /* all soft token id's are SHA1_HASH_LEN's */ + if (key_id->len != SHA1_LENGTH) { + goto loser; + } + if (found) { + /* if we already found some keys, don't do the traversal */ + goto loser; + } } keyData.sdb = sdb; keyData.keyHandle = keyHandle; @@ -336,49 +329,48 @@ typedef struct lgCertDataStr { int max_cert_count; NSSLOWCERTCertificate **certs; const CK_ATTRIBUTE *template; - CK_ULONG templ_count; + CK_ULONG templ_count; unsigned long classFlags; - PRBool strict; + PRBool strict; } lgCertData; /* * collect all the certs from the traverse call. - */ + */ static SECStatus -lg_cert_collect(NSSLOWCERTCertificate *cert,void *arg) +lg_cert_collect(NSSLOWCERTCertificate *cert, void *arg) { lgCertData *cd = (lgCertData *)arg; if (cert == NULL) { - return SECSuccess; + return SECSuccess; } if (cd->certs == NULL) { - return SECFailure; + return SECFailure; } if (cd->strict) { - if ((cd->classFlags & LG_CERT) && !lg_tokenMatch(cd->sdb, - &cert->certKey, LG_TOKEN_TYPE_CERT, cd->template,cd->templ_count)) { - return SECSuccess; - } - if ((cd->classFlags & LG_TRUST) && !lg_tokenMatch(cd->sdb, - &cert->certKey, LG_TOKEN_TYPE_TRUST, - cd->template, cd->templ_count)) { - return SECSuccess; - } + if ((cd->classFlags & LG_CERT) && + !lg_tokenMatch(cd->sdb, &cert->certKey, LG_TOKEN_TYPE_CERT, cd->template, cd->templ_count)) { + return SECSuccess; + } + if ((cd->classFlags & LG_TRUST) && + !lg_tokenMatch(cd->sdb, &cert->certKey, LG_TOKEN_TYPE_TRUST, cd->template, cd->templ_count)) { + return SECSuccess; + } } /* allocate more space if we need it. This should only happen in * the general traversal case */ if (cd->cert_count >= cd->max_cert_count) { - int size; - cd->max_cert_count += LG_SEARCH_BLOCK_SIZE; - size = cd->max_cert_count * sizeof (NSSLOWCERTCertificate *); - cd->certs = (NSSLOWCERTCertificate **)PORT_Realloc(cd->certs,size); - if (cd->certs == NULL) { - return SECFailure; - } + int size; + cd->max_cert_count += LG_SEARCH_BLOCK_SIZE; + size = cd->max_cert_count * sizeof(NSSLOWCERTCertificate *); + cd->certs = (NSSLOWCERTCertificate **)PORT_Realloc(cd->certs, size); + if (cd->certs == NULL) { + return SECFailure; + } } cd->certs[cd->cert_count++] = nsslowcert_DupCertificate(cert); @@ -393,53 +385,54 @@ lg_cert_collect2(NSSLOWCERTCertificate *cert, SECItem *dymmy, void *arg) } static void -lg_searchSingleCert(lgCertData *certData,NSSLOWCERTCertificate *cert) +lg_searchSingleCert(lgCertData *certData, NSSLOWCERTCertificate *cert) { if (cert == NULL) { - return; + return; } - if (certData->strict && - !lg_tokenMatch(certData->sdb, &cert->certKey, LG_TOKEN_TYPE_CERT, - certData->template,certData->templ_count)) { - nsslowcert_DestroyCertificate(cert); - return; + if (certData->strict && + !lg_tokenMatch(certData->sdb, &cert->certKey, LG_TOKEN_TYPE_CERT, + certData->template, certData->templ_count)) { + nsslowcert_DestroyCertificate(cert); + return; } - certData->certs = (NSSLOWCERTCertificate **) - PORT_Alloc(sizeof (NSSLOWCERTCertificate *)); + certData->certs = (NSSLOWCERTCertificate **) + PORT_Alloc(sizeof(NSSLOWCERTCertificate *)); if (certData->certs == NULL) { - nsslowcert_DestroyCertificate(cert); - return; + nsslowcert_DestroyCertificate(cert); + return; } certData->certs[0] = cert; certData->cert_count = 1; } static void -lg_CertSetupData(lgCertData *certData,int count) +lg_CertSetupData(lgCertData *certData, int count) { certData->max_cert_count = count; if (certData->max_cert_count <= 0) { - return; + return; } certData->certs = (NSSLOWCERTCertificate **) - PORT_Alloc( count * sizeof(NSSLOWCERTCertificate *)); + PORT_Alloc(count * sizeof(NSSLOWCERTCertificate *)); return; } static void -lg_searchCertsAndTrust(SDB *sdb, SECItem *derCert, SECItem *name, - SECItem *derSubject, NSSLOWCERTIssuerAndSN *issuerSN, - SECItem *email, - unsigned long classFlags, SDBFind *handles, - const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) +lg_searchCertsAndTrust(SDB *sdb, SECItem *derCert, SECItem *name, + SECItem *derSubject, NSSLOWCERTIssuerAndSN *issuerSN, + SECItem *email, + unsigned long classFlags, SDBFind *handles, + const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) { NSSLOWCERTCertDBHandle *certHandle = NULL; lgCertData certData; int i; certHandle = lg_getCertDB(sdb); - if (certHandle == NULL) return; + if (certHandle == NULL) + return; certData.sdb = sdb; certData.max_cert_count = 0; @@ -447,107 +440,107 @@ lg_searchCertsAndTrust(SDB *sdb, SECItem *derCert, SECItem *name, certData.cert_count = 0; certData.template = pTemplate; certData.templ_count = ulCount; - certData.classFlags = classFlags; - certData.strict = LG_STRICT; - + certData.classFlags = classFlags; + certData.strict = LG_STRICT; /* * Find the Cert. */ if (derCert->data != NULL) { - NSSLOWCERTCertificate *cert = - nsslowcert_FindCertByDERCert(certHandle,derCert); - lg_searchSingleCert(&certData,cert); + NSSLOWCERTCertificate *cert = + nsslowcert_FindCertByDERCert(certHandle, derCert); + lg_searchSingleCert(&certData, cert); } else if (name->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(name->len+1); - int count; - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,name->data,name->len); - tmp_name[name->len] = 0; - - count= nsslowcert_NumPermCertsForNickname(certHandle,tmp_name); - lg_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForNickname(certHandle,tmp_name, - lg_cert_collect, &certData); - PORT_Free(tmp_name); + char *tmp_name = (char *)PORT_Alloc(name->len + 1); + int count; + + if (tmp_name == NULL) { + return; + } + PORT_Memcpy(tmp_name, name->data, name->len); + tmp_name[name->len] = 0; + + count = nsslowcert_NumPermCertsForNickname(certHandle, tmp_name); + lg_CertSetupData(&certData, count); + nsslowcert_TraversePermCertsForNickname(certHandle, tmp_name, + lg_cert_collect, &certData); + PORT_Free(tmp_name); } else if (derSubject->data != NULL) { - int count; - - count = nsslowcert_NumPermCertsForSubject(certHandle,derSubject); - lg_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForSubject(certHandle,derSubject, - lg_cert_collect, &certData); - } else if ((issuerSN->derIssuer.data != NULL) && - (issuerSN->serialNumber.data != NULL)) { + int count; + + count = nsslowcert_NumPermCertsForSubject(certHandle, derSubject); + lg_CertSetupData(&certData, count); + nsslowcert_TraversePermCertsForSubject(certHandle, derSubject, + lg_cert_collect, &certData); + } else if ((issuerSN->derIssuer.data != NULL) && + (issuerSN->serialNumber.data != NULL)) { if (classFlags & LG_CERT) { - NSSLOWCERTCertificate *cert = - nsslowcert_FindCertByIssuerAndSN(certHandle,issuerSN); - - lg_searchSingleCert(&certData,cert); - } - if (classFlags & LG_TRUST) { - NSSLOWCERTTrust *trust = - nsslowcert_FindTrustByIssuerAndSN(certHandle, issuerSN); - - if (trust) { - lg_addHandle(handles, - lg_mkHandle(sdb,&trust->dbKey,LG_TOKEN_TYPE_TRUST)); - nsslowcert_DestroyTrust(trust); - } - } + NSSLOWCERTCertificate *cert = + nsslowcert_FindCertByIssuerAndSN(certHandle, issuerSN); + + lg_searchSingleCert(&certData, cert); + } + if (classFlags & LG_TRUST) { + NSSLOWCERTTrust *trust = + nsslowcert_FindTrustByIssuerAndSN(certHandle, issuerSN); + + if (trust) { + lg_addHandle(handles, + lg_mkHandle(sdb, &trust->dbKey, LG_TOKEN_TYPE_TRUST)); + nsslowcert_DestroyTrust(trust); + } + } } else if (email->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(email->len+1); - certDBEntrySMime *entry = NULL; - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,email->data,email->len); - tmp_name[email->len] = 0; - - entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name); - if (entry) { - int count; - SECItem *subjectName = &entry->subjectName; - - count = nsslowcert_NumPermCertsForSubject(certHandle, subjectName); - lg_CertSetupData(&certData,count); - nsslowcert_TraversePermCertsForSubject(certHandle, subjectName, - lg_cert_collect, &certData); - - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(tmp_name); + char *tmp_name = (char *)PORT_Alloc(email->len + 1); + certDBEntrySMime *entry = NULL; + + if (tmp_name == NULL) { + return; + } + PORT_Memcpy(tmp_name, email->data, email->len); + tmp_name[email->len] = 0; + + entry = nsslowcert_ReadDBSMimeEntry(certHandle, tmp_name); + if (entry) { + int count; + SECItem *subjectName = &entry->subjectName; + + count = nsslowcert_NumPermCertsForSubject(certHandle, subjectName); + lg_CertSetupData(&certData, count); + nsslowcert_TraversePermCertsForSubject(certHandle, subjectName, + lg_cert_collect, &certData); + + nsslowcert_DestroyDBEntry((certDBEntry *)entry); + } + PORT_Free(tmp_name); } else { - /* we aren't filtering the certs, we are working on all, so turn - * on the strict filters. */ - certData.strict = PR_TRUE; - lg_CertSetupData(&certData,LG_SEARCH_BLOCK_SIZE); - nsslowcert_TraversePermCerts(certHandle, lg_cert_collect2, &certData); + /* we aren't filtering the certs, we are working on all, so turn + * on the strict filters. */ + certData.strict = PR_TRUE; + lg_CertSetupData(&certData, LG_SEARCH_BLOCK_SIZE); + nsslowcert_TraversePermCerts(certHandle, lg_cert_collect2, &certData); } /* * build the handles - */ - for (i=0 ; i < certData.cert_count ; i++) { - NSSLOWCERTCertificate *cert = certData.certs[i]; - - /* if we filtered it would have been on the stuff above */ - if (classFlags & LG_CERT) { - lg_addHandle(handles, - lg_mkHandle(sdb,&cert->certKey,LG_TOKEN_TYPE_CERT)); - } - if ((classFlags & LG_TRUST) && nsslowcert_hasTrust(cert->trust)) { - lg_addHandle(handles, - lg_mkHandle(sdb,&cert->certKey,LG_TOKEN_TYPE_TRUST)); - } - nsslowcert_DestroyCertificate(cert); - } - - if (certData.certs) PORT_Free(certData.certs); + */ + for (i = 0; i < certData.cert_count; i++) { + NSSLOWCERTCertificate *cert = certData.certs[i]; + + /* if we filtered it would have been on the stuff above */ + if (classFlags & LG_CERT) { + lg_addHandle(handles, + lg_mkHandle(sdb, &cert->certKey, LG_TOKEN_TYPE_CERT)); + } + if ((classFlags & LG_TRUST) && nsslowcert_hasTrust(cert->trust)) { + lg_addHandle(handles, + lg_mkHandle(sdb, &cert->certKey, LG_TOKEN_TYPE_TRUST)); + } + nsslowcert_DestroyCertificate(cert); + } + + if (certData.certs) + PORT_Free(certData.certs); return; } @@ -556,67 +549,68 @@ lg_smime_collect(SECItem *data, SECItem *key, certDBEntryType type, void *arg) { lgEntryData *smimeData; SDB *sdb; - + smimeData = (lgEntryData *)arg; sdb = smimeData->sdb; if (lg_tokenMatch(sdb, key, LG_TOKEN_TYPE_SMIME, - smimeData->template, smimeData->templ_count)) { - lg_addHandle(smimeData->searchHandles, - lg_mkHandle(sdb,key,LG_TOKEN_TYPE_SMIME)); + smimeData->template, smimeData->templ_count)) { + lg_addHandle(smimeData->searchHandles, + lg_mkHandle(sdb, key, LG_TOKEN_TYPE_SMIME)); } - return(SECSuccess); + return (SECSuccess); } static void -lg_searchSMime(SDB *sdb, SECItem *email, SDBFind *handles, - const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) +lg_searchSMime(SDB *sdb, SECItem *email, SDBFind *handles, + const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) { NSSLOWCERTCertDBHandle *certHandle = NULL; certDBEntrySMime *entry; certHandle = lg_getCertDB(sdb); - if (certHandle == NULL) return; + if (certHandle == NULL) + return; if (email->data != NULL) { - char *tmp_name = (char*)PORT_Alloc(email->len+1); - - if (tmp_name == NULL) { - return; - } - PORT_Memcpy(tmp_name,email->data,email->len); - tmp_name[email->len] = 0; - - entry = nsslowcert_ReadDBSMimeEntry(certHandle,tmp_name); - if (entry) { - SECItem emailKey; - - emailKey.data = (unsigned char *)tmp_name; - emailKey.len = PORT_Strlen(tmp_name)+1; - emailKey.type = 0; - lg_addHandle(handles, - lg_mkHandle(sdb,&emailKey,LG_TOKEN_TYPE_SMIME)); - nsslowcert_DestroyDBEntry((certDBEntry *)entry); - } - PORT_Free(tmp_name); + char *tmp_name = (char *)PORT_Alloc(email->len + 1); + + if (tmp_name == NULL) { + return; + } + PORT_Memcpy(tmp_name, email->data, email->len); + tmp_name[email->len] = 0; + + entry = nsslowcert_ReadDBSMimeEntry(certHandle, tmp_name); + if (entry) { + SECItem emailKey; + + emailKey.data = (unsigned char *)tmp_name; + emailKey.len = PORT_Strlen(tmp_name) + 1; + emailKey.type = 0; + lg_addHandle(handles, + lg_mkHandle(sdb, &emailKey, LG_TOKEN_TYPE_SMIME)); + nsslowcert_DestroyDBEntry((certDBEntry *)entry); + } + PORT_Free(tmp_name); } else { - /* traverse */ - lgEntryData smimeData; + /* traverse */ + lgEntryData smimeData; - /* traverse */ - smimeData.sdb = sdb; - smimeData.searchHandles = handles; - smimeData.template = pTemplate; - smimeData.templ_count = ulCount; - nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeSMimeProfile, - lg_smime_collect, (void *)&smimeData); + /* traverse */ + smimeData.sdb = sdb; + smimeData.searchHandles = handles; + smimeData.template = pTemplate; + smimeData.templ_count = ulCount; + nsslowcert_TraverseDBEntries(certHandle, certDBEntryTypeSMimeProfile, + lg_smime_collect, (void *)&smimeData); } return; } static CK_RV lg_searchTokenList(SDB *sdb, SDBFind *search, - const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) + const CK_ATTRIBUTE *pTemplate, CK_LONG ulCount) { int i; PRBool isKrl = PR_FALSE; @@ -626,10 +620,10 @@ lg_searchTokenList(SDB *sdb, SDBFind *search, SECItem email = { siBuffer, NULL, 0 }; SECItem key_id = { siBuffer, NULL, 0 }; SECItem cert_sha1_hash = { siBuffer, NULL, 0 }; - SECItem cert_md5_hash = { siBuffer, NULL, 0 }; + SECItem cert_md5_hash = { siBuffer, NULL, 0 }; NSSLOWCERTIssuerAndSN issuerSN = { - { siBuffer, NULL, 0 }, - { siBuffer, NULL, 0 } + { siBuffer, NULL, 0 }, + { siBuffer, NULL, 0 } }; SECItem *copy = NULL; CK_CERTIFICATE_TYPE certType; @@ -638,9 +632,9 @@ lg_searchTokenList(SDB *sdb, SDBFind *search, unsigned long classFlags; if (lg_getCertDB(sdb) == NULL) { - classFlags = LG_PRIVATE|LG_KEY; + classFlags = LG_PRIVATE | LG_KEY; } else { - classFlags = LG_CERT|LG_TRUST|LG_PUBLIC|LG_SMIME|LG_CRL; + classFlags = LG_CERT | LG_TRUST | LG_PUBLIC | LG_SMIME | LG_CRL; } /* @@ -650,214 +644,216 @@ lg_searchTokenList(SDB *sdb, SDBFind *search, * limit the kinds of objects we are searching for. Later we can use this * array to filter the remaining objects more finely. */ - for (i=0 ;classFlags && i < (int)ulCount; i++) { - - switch (pTemplate[i].type) { - case CKA_SUBJECT: - copy = &derSubject; - classFlags &= (LG_CERT|LG_PRIVATE|LG_PUBLIC|LG_SMIME|LG_CRL); - break; - case CKA_ISSUER: - copy = &issuerSN.derIssuer; - classFlags &= (LG_CERT|LG_TRUST); - break; - case CKA_SERIAL_NUMBER: - copy = &issuerSN.serialNumber; - classFlags &= (LG_CERT|LG_TRUST); - break; - case CKA_VALUE: - copy = &derCert; - classFlags &= (LG_CERT|LG_CRL|LG_SMIME); - break; - case CKA_LABEL: - copy = &name; - break; - case CKA_NETSCAPE_EMAIL: - copy = &email; - classFlags &= LG_SMIME|LG_CERT; - break; - case CKA_NETSCAPE_SMIME_TIMESTAMP: - classFlags &= LG_SMIME; - break; - case CKA_CLASS: - crv = lg_GetULongAttribute(CKA_CLASS,&pTemplate[i],1, &objectClass); - if (crv != CKR_OK) { - classFlags = 0; - break; - } - switch (objectClass) { - case CKO_CERTIFICATE: - classFlags &= LG_CERT; - break; - case CKO_NETSCAPE_TRUST: - classFlags &= LG_TRUST; - break; - case CKO_NETSCAPE_CRL: - classFlags &= LG_CRL; - break; - case CKO_NETSCAPE_SMIME: - classFlags &= LG_SMIME; - break; - case CKO_PRIVATE_KEY: - classFlags &= LG_PRIVATE; - break; - case CKO_PUBLIC_KEY: - classFlags &= LG_PUBLIC; - break; - case CKO_SECRET_KEY: - classFlags &= LG_KEY; - break; - default: - classFlags = 0; - break; - } - break; - case CKA_PRIVATE: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - break; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { - classFlags &= (LG_PRIVATE|LG_KEY); - } else { - classFlags &= ~(LG_PRIVATE|LG_KEY); - } - break; - case CKA_SENSITIVE: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - break; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { - classFlags &= (LG_PRIVATE|LG_KEY); - } else { - classFlags = 0; - } - break; - case CKA_TOKEN: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - break; - } - if (*((CK_BBOOL *)pTemplate[i].pValue) != CK_TRUE) { - classFlags = 0; - } - break; - case CKA_CERT_SHA1_HASH: - classFlags &= LG_TRUST; - copy = &cert_sha1_hash; break; - case CKA_CERT_MD5_HASH: - classFlags &= LG_TRUST; - copy = &cert_md5_hash; break; - case CKA_CERTIFICATE_TYPE: - crv = lg_GetULongAttribute(CKA_CERTIFICATE_TYPE,&pTemplate[i], - 1,&certType); - if (crv != CKR_OK) { - classFlags = 0; - break; - } - classFlags &= LG_CERT; - if (certType != CKC_X_509) { - classFlags = 0; - } - break; - case CKA_ID: - copy = &key_id; - classFlags &= (LG_CERT|LG_PRIVATE|LG_KEY|LG_PUBLIC); - break; - case CKA_NETSCAPE_KRL: - if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { - classFlags = 0; - break; - } - classFlags &= LG_CRL; - isKrl = (PRBool)(*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE); - break; - case CKA_MODIFIABLE: - break; - case CKA_KEY_TYPE: - case CKA_DERIVE: - classFlags &= LG_PUBLIC|LG_PRIVATE|LG_KEY; - break; - case CKA_VERIFY_RECOVER: - classFlags &= LG_PUBLIC; - break; - case CKA_SIGN_RECOVER: - classFlags &= LG_PRIVATE; - break; - case CKA_ENCRYPT: - case CKA_VERIFY: - case CKA_WRAP: - classFlags &= LG_PUBLIC|LG_KEY; - break; - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_UNWRAP: - case CKA_ALWAYS_SENSITIVE: - case CKA_EXTRACTABLE: - case CKA_NEVER_EXTRACTABLE: - classFlags &= LG_PRIVATE|LG_KEY; - break; - /* can't be a certificate if it doesn't match one of the above - * attributes */ - default: - classFlags = 0; - break; - } - if (copy) { - copy->data = (unsigned char*)pTemplate[i].pValue; - copy->len = pTemplate[i].ulValueLen; - } - copy = NULL; + for (i = 0; classFlags && i < (int)ulCount; i++) { + + switch (pTemplate[i].type) { + case CKA_SUBJECT: + copy = &derSubject; + classFlags &= (LG_CERT | LG_PRIVATE | LG_PUBLIC | LG_SMIME | LG_CRL); + break; + case CKA_ISSUER: + copy = &issuerSN.derIssuer; + classFlags &= (LG_CERT | LG_TRUST); + break; + case CKA_SERIAL_NUMBER: + copy = &issuerSN.serialNumber; + classFlags &= (LG_CERT | LG_TRUST); + break; + case CKA_VALUE: + copy = &derCert; + classFlags &= (LG_CERT | LG_CRL | LG_SMIME); + break; + case CKA_LABEL: + copy = &name; + break; + case CKA_NETSCAPE_EMAIL: + copy = &email; + classFlags &= LG_SMIME | LG_CERT; + break; + case CKA_NETSCAPE_SMIME_TIMESTAMP: + classFlags &= LG_SMIME; + break; + case CKA_CLASS: + crv = lg_GetULongAttribute(CKA_CLASS, &pTemplate[i], 1, &objectClass); + if (crv != CKR_OK) { + classFlags = 0; + break; + } + switch (objectClass) { + case CKO_CERTIFICATE: + classFlags &= LG_CERT; + break; + case CKO_NETSCAPE_TRUST: + classFlags &= LG_TRUST; + break; + case CKO_NETSCAPE_CRL: + classFlags &= LG_CRL; + break; + case CKO_NETSCAPE_SMIME: + classFlags &= LG_SMIME; + break; + case CKO_PRIVATE_KEY: + classFlags &= LG_PRIVATE; + break; + case CKO_PUBLIC_KEY: + classFlags &= LG_PUBLIC; + break; + case CKO_SECRET_KEY: + classFlags &= LG_KEY; + break; + default: + classFlags = 0; + break; + } + break; + case CKA_PRIVATE: + if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { + classFlags = 0; + break; + } + if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { + classFlags &= (LG_PRIVATE | LG_KEY); + } else { + classFlags &= ~(LG_PRIVATE | LG_KEY); + } + break; + case CKA_SENSITIVE: + if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { + classFlags = 0; + break; + } + if (*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE) { + classFlags &= (LG_PRIVATE | LG_KEY); + } else { + classFlags = 0; + } + break; + case CKA_TOKEN: + if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { + classFlags = 0; + break; + } + if (*((CK_BBOOL *)pTemplate[i].pValue) != CK_TRUE) { + classFlags = 0; + } + break; + case CKA_CERT_SHA1_HASH: + classFlags &= LG_TRUST; + copy = &cert_sha1_hash; + break; + case CKA_CERT_MD5_HASH: + classFlags &= LG_TRUST; + copy = &cert_md5_hash; + break; + case CKA_CERTIFICATE_TYPE: + crv = lg_GetULongAttribute(CKA_CERTIFICATE_TYPE, &pTemplate[i], + 1, &certType); + if (crv != CKR_OK) { + classFlags = 0; + break; + } + classFlags &= LG_CERT; + if (certType != CKC_X_509) { + classFlags = 0; + } + break; + case CKA_ID: + copy = &key_id; + classFlags &= (LG_CERT | LG_PRIVATE | LG_KEY | LG_PUBLIC); + break; + case CKA_NETSCAPE_KRL: + if (pTemplate[i].ulValueLen != sizeof(CK_BBOOL)) { + classFlags = 0; + break; + } + classFlags &= LG_CRL; + isKrl = (PRBool)(*((CK_BBOOL *)pTemplate[i].pValue) == CK_TRUE); + break; + case CKA_MODIFIABLE: + break; + case CKA_KEY_TYPE: + case CKA_DERIVE: + classFlags &= LG_PUBLIC | LG_PRIVATE | LG_KEY; + break; + case CKA_VERIFY_RECOVER: + classFlags &= LG_PUBLIC; + break; + case CKA_SIGN_RECOVER: + classFlags &= LG_PRIVATE; + break; + case CKA_ENCRYPT: + case CKA_VERIFY: + case CKA_WRAP: + classFlags &= LG_PUBLIC | LG_KEY; + break; + case CKA_DECRYPT: + case CKA_SIGN: + case CKA_UNWRAP: + case CKA_ALWAYS_SENSITIVE: + case CKA_EXTRACTABLE: + case CKA_NEVER_EXTRACTABLE: + classFlags &= LG_PRIVATE | LG_KEY; + break; + /* can't be a certificate if it doesn't match one of the above + * attributes */ + default: + classFlags = 0; + break; + } + if (copy) { + copy->data = (unsigned char *)pTemplate[i].pValue; + copy->len = pTemplate[i].ulValueLen; + } + copy = NULL; } /* certs */ - if (classFlags & (LG_CERT|LG_TRUST)) { - lg_searchCertsAndTrust(sdb,&derCert,&name,&derSubject, - &issuerSN, &email,classFlags,search, - pTemplate, ulCount); + if (classFlags & (LG_CERT | LG_TRUST)) { + lg_searchCertsAndTrust(sdb, &derCert, &name, &derSubject, + &issuerSN, &email, classFlags, search, + pTemplate, ulCount); } /* keys */ - if (classFlags & (LG_PRIVATE|LG_PUBLIC|LG_KEY)) { - PRBool mustStrict = (name.len != 0); - lg_searchKeys(sdb, &key_id, classFlags, search, - mustStrict, pTemplate, ulCount); + if (classFlags & (LG_PRIVATE | LG_PUBLIC | LG_KEY)) { + PRBool mustStrict = (name.len != 0); + lg_searchKeys(sdb, &key_id, classFlags, search, + mustStrict, pTemplate, ulCount); } /* crl's */ if (classFlags & LG_CRL) { - lg_searchCrls(sdb, &derSubject, isKrl, classFlags, search, - pTemplate, ulCount); + lg_searchCrls(sdb, &derSubject, isKrl, classFlags, search, + pTemplate, ulCount); } /* Add S/MIME entry stuff */ if (classFlags & LG_SMIME) { - lg_searchSMime(sdb, &email, search, pTemplate, ulCount); + lg_searchSMime(sdb, &email, search, pTemplate, ulCount); } return CKR_OK; } - -/* lg_FindObjectsInit initializes a search for token and session objects +/* lg_FindObjectsInit initializes a search for token and session objects * that match a template. */ -CK_RV lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, - CK_ULONG ulCount, SDBFind **retSearch) +CK_RV +lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, + CK_ULONG ulCount, SDBFind **retSearch) { SDBFind *search; CK_RV crv = CKR_OK; - - *retSearch = NULL; + + *retSearch = NULL; search = (SDBFind *)PORT_Alloc(sizeof(SDBFind)); if (search == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } search->handles = (CK_OBJECT_HANDLE *) - PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * LG_SEARCH_BLOCK_SIZE); + PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * LG_SEARCH_BLOCK_SIZE); if (search->handles == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } search->index = 0; search->size = 0; @@ -866,7 +862,7 @@ CK_RV lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, crv = lg_searchTokenList(sdb, search, pTemplate, ulCount); if (crv != CKR_OK) { - goto loser; + goto loser; } *retSearch = search; @@ -874,29 +870,29 @@ CK_RV lg_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *pTemplate, loser: if (search) { - lg_FreeSearch(search); + lg_FreeSearch(search); } return crv; } - -/* lg_FindObjects continues a search for token and session objects +/* lg_FindObjects continues a search for token and session objects * that match a template, obtaining additional object handles. */ -CK_RV lg_FindObjects(SDB *sdb, SDBFind *search, - CK_OBJECT_HANDLE *phObject,CK_ULONG ulMaxObjectCount, - CK_ULONG *pulObjectCount) +CK_RV +lg_FindObjects(SDB *sdb, SDBFind *search, + CK_OBJECT_HANDLE *phObject, CK_ULONG ulMaxObjectCount, + CK_ULONG *pulObjectCount) { - int transfer; + int transfer; int left; *pulObjectCount = 0; left = search->size - search->index; transfer = ((int)ulMaxObjectCount > left) ? left : ulMaxObjectCount; if (transfer > 0) { - PORT_Memcpy(phObject,&search->handles[search->index], - transfer*sizeof(CK_OBJECT_HANDLE)); + PORT_Memcpy(phObject, &search->handles[search->index], + transfer * sizeof(CK_OBJECT_HANDLE)); } else { - *phObject = CK_INVALID_HANDLE; + *phObject = CK_INVALID_HANDLE; } search->index += transfer; @@ -905,11 +901,12 @@ CK_RV lg_FindObjects(SDB *sdb, SDBFind *search, } /* lg_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV lg_FindObjectsFinal(SDB* lgdb, SDBFind *search) +CK_RV +lg_FindObjectsFinal(SDB *lgdb, SDBFind *search) { if (search != NULL) { - lg_FreeSearch(search); + lg_FreeSearch(search); } return CKR_OK; } diff --git a/nss/lib/softoken/legacydb/lgfips.c b/nss/lib/softoken/legacydb/lgfips.c new file mode 100644 index 0000000..b017424 --- /dev/null +++ b/nss/lib/softoken/legacydb/lgfips.c @@ -0,0 +1,115 @@ +/* + * PKCS #11 FIPS Power-Up Self Test. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* $Id: fipstest.c,v 1.31 2012/06/28 17:55:06 rrelyea%redhat.com Exp $ */ + +#include "seccomon.h" +#include "lgdb.h" +#include "blapi.h" + +/* + * different platforms have different ways of calling and initial entry point + * when the dll/.so is loaded. Most platforms support either a posix pragma + * or the GCC attribute. Some platforms suppor a pre-defined name, and some + * platforms have a link line way of invoking this function. + */ + +/* The pragma */ +#if defined(USE_INIT_PRAGMA) +#pragma init(lg_startup_tests) +#endif + +/* GCC Attribute */ +#if defined(__GNUC__) && !defined(NSS_NO_INIT_SUPPORT) +#define INIT_FUNCTION __attribute__((constructor)) +#else +#define INIT_FUNCTION +#endif + +static void INIT_FUNCTION lg_startup_tests(void); + +/* Windows pre-defined entry */ +#if defined(XP_WIN) && !defined(NSS_NO_INIT_SUPPORT) +#include <windows.h> + +BOOL WINAPI DllMain( + HINSTANCE hinstDLL, // handle to DLL module + DWORD fdwReason, // reason for calling function + LPVOID lpReserved) // reserved +{ + // Perform actions based on the reason for calling. + switch (fdwReason) { + case DLL_PROCESS_ATTACH: + // Initialize once for each new process. + // Return FALSE to fail DLL load. + lg_startup_tests(); + break; + + case DLL_THREAD_ATTACH: + // Do thread-specific initialization. + break; + + case DLL_THREAD_DETACH: + // Do thread-specific cleanup. + break; + + case DLL_PROCESS_DETACH: + // Perform any necessary cleanup. + break; + } + return TRUE; // Successful DLL_PROCESS_ATTACH. +} +#endif + +static PRBool lg_self_tests_ran = PR_FALSE; +static PRBool lg_self_tests_success = PR_FALSE; + +static void +lg_local_function(void) +{ +} + +/* + * This function is called at dll load time, the code tha makes this + * happen is platform specific on defined above. + */ +static void +lg_startup_tests(void) +{ + const char *libraryName = LG_LIB_NAME; + + PORT_Assert(!lg_self_tests_ran); + PORT_Assert(!lg_self_tests_success); + lg_self_tests_ran = PR_TRUE; + lg_self_tests_success = PR_FALSE; /* just in case */ + + /* no self tests required for the legacy db, only the integrity check */ + /* check the integrity of our shared library */ + if (!BLAPI_SHVerify(libraryName, (PRFuncPtr)&lg_local_function)) { + /* something is wrong with the library, fail without enabling + * the fips token */ + return; + } + /* FIPS product has been installed and is functioning, allow + * the module to operate in fips mode */ + lg_self_tests_success = PR_TRUE; +} + +PRBool +lg_FIPSEntryOK() +{ +#ifdef NSS_NO_INIT_SUPPORT + /* this should only be set on platforms that can't handle one of the INIT + * schemes. This code allows those platforms to continue to function, + * though they don't meet the strict NIST requirements. If NO_INIT_SUPPORT + * is not set, and init support has not been properly enabled, softken + * will always fail because of the test below */ + if (!lg_self_tests_ran) { + lg_startup_tests(); + } +#endif + return lg_self_tests_success; +} diff --git a/nss/lib/softoken/legacydb/lginit.c b/nss/lib/softoken/legacydb/lginit.c index b49f3fe..6913eea 100644 --- a/nss/lib/softoken/legacydb/lginit.c +++ b/nss/lib/softoken/legacydb/lginit.c @@ -42,34 +42,34 @@ lg_certdb_name_cb(void *arg, int dbVersion) char *dbname = NULL; switch (dbVersion) { - case 8: - dbver = "8"; - break; - case 7: - dbver = "7"; - break; - case 6: - dbver = "6"; - break; - case 5: - dbver = "5"; - break; - case 4: - default: - dbver = ""; - break; + case 8: + dbver = "8"; + break; + case 7: + dbver = "7"; + break; + case 6: + dbver = "6"; + break; + case 5: + dbver = "5"; + break; + case 4: + default: + dbver = ""; + break; } /* make sure we return something allocated with PORT_ so we have properly * matched frees at the end */ smpname = PR_smprintf(CERT_DB_FMT, configdir, dbver); if (smpname) { - dbname = PORT_Strdup(smpname); - PR_smprintf_free(smpname); + dbname = PORT_Strdup(smpname); + PR_smprintf_free(smpname); } return dbname; } - + static char * lg_keydb_name_cb(void *arg, int dbVersion) { @@ -77,50 +77,50 @@ lg_keydb_name_cb(void *arg, int dbVersion) const char *dbver; char *smpname = NULL; char *dbname = NULL; - + switch (dbVersion) { - case 4: - dbver = "4"; - break; - case 3: - dbver = "3"; - break; - case 1: - dbver = "1"; - break; - case 2: - default: - dbver = ""; - break; + case 4: + dbver = "4"; + break; + case 3: + dbver = "3"; + break; + case 1: + dbver = "1"; + break; + case 2: + default: + dbver = ""; + break; } smpname = PR_smprintf(KEY_DB_FMT, configdir, dbver); if (smpname) { - dbname = PORT_Strdup(smpname); - PR_smprintf_free(smpname); + dbname = PORT_Strdup(smpname); + PR_smprintf_free(smpname); } return dbname; } const char * -lg_EvaluateConfigDir(const char *configdir,char **appName) +lg_EvaluateConfigDir(const char *configdir, char **appName) { - if (PORT_Strncmp(configdir, MULTIACCESS, sizeof(MULTIACCESS)-1) == 0) { - char *cdir; - - *appName = PORT_Strdup(configdir+sizeof(MULTIACCESS)-1); - if (*appName == NULL) { - return configdir; - } - cdir = *appName; - while (*cdir && *cdir != ':') { - cdir++; - } - if (*cdir == ':') { - *cdir = 0; - cdir++; - } - configdir = cdir; + if (PORT_Strncmp(configdir, MULTIACCESS, sizeof(MULTIACCESS) - 1) == 0) { + char *cdir; + + *appName = PORT_Strdup(configdir + sizeof(MULTIACCESS) - 1); + if (*appName == NULL) { + return configdir; + } + cdir = *appName; + while (*cdir && *cdir != ':') { + cdir++; + } + if (*cdir == ':') { + *cdir = 0; + cdir++; + } + configdir = cdir; } return configdir; } @@ -130,21 +130,22 @@ static rdbfunc lg_rdbfunc = NULL; static rdbstatusfunc lg_rdbstatusfunc = NULL; /* NOTE: SHLIB_SUFFIX is defined on the command line */ -#define RDBLIB SHLIB_PREFIX"rdb."SHLIB_SUFFIX +#define RDBLIB SHLIB_PREFIX "rdb." SHLIB_SUFFIX -DB * rdbopen(const char *appName, const char *prefix, - const char *type, int flags, int *status) +DB * +rdbopen(const char *appName, const char *prefix, + const char *type, int flags, int *status) { PRLibrary *lib; DB *db; char *disableUnload = NULL; if (lg_rdbfunc) { - db = (*lg_rdbfunc)(appName,prefix,type,rdbmapflags(flags)); - if (!db && status && lg_rdbstatusfunc) { - *status = (*lg_rdbstatusfunc)(); - } - return db; + db = (*lg_rdbfunc)(appName, prefix, type, rdbmapflags(flags)); + if (!db && status && lg_rdbstatusfunc) { + *status = (*lg_rdbstatusfunc)(); + } + return db; } /* @@ -153,22 +154,22 @@ DB * rdbopen(const char *appName, const char *prefix, lib = PR_LoadLibrary(RDBLIB); if (!lib) { - return NULL; + return NULL; } /* get the entry points */ - lg_rdbstatusfunc = (rdbstatusfunc) PR_FindSymbol(lib,"rdbstatus"); - lg_rdbfunc = (rdbfunc) PR_FindSymbol(lib,"rdbopen"); + lg_rdbstatusfunc = (rdbstatusfunc)PR_FindSymbol(lib, "rdbstatus"); + lg_rdbfunc = (rdbfunc)PR_FindSymbol(lib, "rdbopen"); if (lg_rdbfunc) { - db = (*lg_rdbfunc)(appName,prefix,type,rdbmapflags(flags)); - if (!db && status && lg_rdbstatusfunc) { - *status = (*lg_rdbstatusfunc)(); - } - return db; + db = (*lg_rdbfunc)(appName, prefix, type, rdbmapflags(flags)); + if (!db && status && lg_rdbstatusfunc) { + *status = (*lg_rdbstatusfunc)(); + } + return db; } /* couldn't find the entry point, unload the library and fail */ - disableUnload = PR_GetEnv("NSS_DISABLE_UNLOAD"); + disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD"); if (!disableUnload) { PR_UnloadLibrary(lib); } @@ -179,37 +180,38 @@ DB * rdbopen(const char *appName, const char *prefix, * the following data structures are from rdb.h. */ struct RDBStr { - DB db; + DB db; int (*xactstart)(DB *db); int (*xactdone)(DB *db, PRBool abort); int version; int (*dbinitcomplete)(DB *db); }; -#define DB_RDB ((DBTYPE) 0xff) -#define RDB_RDONLY 1 -#define RDB_RDWR 2 -#define RDB_CREATE 4 +#define DB_RDB ((DBTYPE)0xff) +#define RDB_RDONLY 1 +#define RDB_RDWR 2 +#define RDB_CREATE 4 static int -rdbmapflags(int flags) { - switch (flags) { - case NO_RDONLY: - return RDB_RDONLY; - case NO_RDWR: - return RDB_RDWR; - case NO_CREATE: - return RDB_CREATE; - default: - break; - } - return 0; +rdbmapflags(int flags) +{ + switch (flags) { + case NO_RDONLY: + return RDB_RDONLY; + case NO_RDWR: + return RDB_RDWR; + case NO_CREATE: + return RDB_CREATE; + default: + break; + } + return 0; } PRBool db_IsRDB(DB *db) { - return (PRBool) db->type == DB_RDB; + return (PRBool)db->type == DB_RDB; } int @@ -217,7 +219,7 @@ db_BeginTransaction(DB *db) { struct RDBStr *rdb = (struct RDBStr *)db; if (db->type != DB_RDB) { - return 0; + return 0; } return rdb->xactstart(db); @@ -228,7 +230,7 @@ db_FinishTransaction(DB *db, PRBool abort) { struct RDBStr *rdb = (struct RDBStr *)db; if (db->type != DB_RDB) { - return 0; + return 0; } return rdb->xactdone(db, abort); @@ -242,11 +244,11 @@ lg_getRawDB(SDB *sdb) certDB = lg_getCertDB(sdb); if (certDB) { - return certDB->permCertDB; + return certDB->permCertDB; } keyDB = lg_getKeyDB(sdb); if (keyDB) { - return keyDB->db; + return keyDB->db; } return NULL; } @@ -258,11 +260,11 @@ lg_Begin(SDB *sdb) int ret; if (db == NULL) { - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } ret = db_BeginTransaction(db); if (ret != 0) { - return CKR_GENERAL_ERROR; /* could happen */ + return CKR_GENERAL_ERROR; /* could happen */ } return CKR_OK; } @@ -274,11 +276,11 @@ lg_Commit(SDB *sdb) int ret; if (db == NULL) { - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } ret = db_FinishTransaction(db, PR_FALSE); if (ret != 0) { - return CKR_GENERAL_ERROR; /* could happen */ + return CKR_GENERAL_ERROR; /* could happen */ } return CKR_OK; } @@ -290,11 +292,11 @@ lg_Abort(SDB *sdb) int ret; if (db == NULL) { - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } ret = db_FinishTransaction(db, PR_TRUE); if (ret != 0) { - return CKR_GENERAL_ERROR; /* could happen */ + return CKR_GENERAL_ERROR; /* could happen */ } return CKR_OK; } @@ -304,100 +306,102 @@ db_InitComplete(DB *db) { struct RDBStr *rdb = (struct RDBStr *)db; if (db->type != DB_RDB) { - return 0; + return 0; } /* we should have added a version number to the RDBS structure. Since we * didn't, we detect that we have and 'extended' structure if the rdbstatus * func exists */ if (!lg_rdbstatusfunc) { - return 0; + return 0; } return rdb->dbinitcomplete(db); } - - SECStatus -db_Copy(DB *dest,DB *src) +db_Copy(DB *dest, DB *src) { int ret; - DBT key,data; + DBT key, data; ret = (*src->seq)(src, &key, &data, R_FIRST); - if (ret) { - return SECSuccess; + if (ret) { + return SECSuccess; } do { - (void)(*dest->put)(dest,&key,&data, R_NOOVERWRITE); - } while ( (*src->seq)(src, &key, &data, R_NEXT) == 0); - (void)(*dest->sync)(dest,0); + (void)(*dest->put)(dest, &key, &data, R_NOOVERWRITE); + } while ((*src->seq)(src, &key, &data, R_NEXT) == 0); + (void)(*dest->sync)(dest, 0); return SECSuccess; } - static CK_RV -lg_OpenCertDB(const char * configdir, const char *prefix, PRBool readOnly, - NSSLOWCERTCertDBHandle **certdbPtr) +lg_OpenCertDB(const char *configdir, const char *prefix, PRBool readOnly, + NSSLOWCERTCertDBHandle **certdbPtr) { NSSLOWCERTCertDBHandle *certdb = NULL; - CK_RV crv = CKR_NETSCAPE_CERTDB_FAILED; - SECStatus rv; - char * name = NULL; - char * appName = NULL; + CK_RV crv = CKR_NETSCAPE_CERTDB_FAILED; + SECStatus rv; + char *name = NULL; + char *appName = NULL; if (prefix == NULL) { - prefix = ""; + prefix = ""; } configdir = lg_EvaluateConfigDir(configdir, &appName); - name = PR_smprintf("%s" PATH_SEPARATOR "%s",configdir,prefix); - if (name == NULL) goto loser; + name = PR_smprintf("%s" PATH_SEPARATOR "%s", configdir, prefix); + if (name == NULL) + goto loser; - certdb = (NSSLOWCERTCertDBHandle*)PORT_ZAlloc(sizeof(NSSLOWCERTCertDBHandle)); - if (certdb == NULL) - goto loser; + certdb = (NSSLOWCERTCertDBHandle *)PORT_ZAlloc(sizeof(NSSLOWCERTCertDBHandle)); + if (certdb == NULL) + goto loser; certdb->ref = 1; -/* fix when we get the DB in */ + /* fix when we get the DB in */ rv = nsslowcert_OpenCertDB(certdb, readOnly, appName, prefix, - lg_certdb_name_cb, (void *)name, PR_FALSE); + lg_certdb_name_cb, (void *)name, PR_FALSE); if (rv == SECSuccess) { - crv = CKR_OK; - *certdbPtr = certdb; - certdb = NULL; - } -loser: - if (certdb) PR_Free(certdb); - if (name) PR_smprintf_free(name); - if (appName) PORT_Free(appName); + crv = CKR_OK; + *certdbPtr = certdb; + certdb = NULL; + } +loser: + if (certdb) + PR_Free(certdb); + if (name) + PR_smprintf_free(name); + if (appName) + PORT_Free(appName); return crv; } static CK_RV -lg_OpenKeyDB(const char * configdir, const char *prefix, PRBool readOnly, - NSSLOWKEYDBHandle **keydbPtr) +lg_OpenKeyDB(const char *configdir, const char *prefix, PRBool readOnly, + NSSLOWKEYDBHandle **keydbPtr) { NSSLOWKEYDBHandle *keydb; - char * name = NULL; - char * appName = NULL; + char *name = NULL; + char *appName = NULL; if (prefix == NULL) { - prefix = ""; + prefix = ""; } configdir = lg_EvaluateConfigDir(configdir, &appName); - name = PR_smprintf("%s" PATH_SEPARATOR "%s",configdir,prefix); - if (name == NULL) - return CKR_HOST_MEMORY; - keydb = nsslowkey_OpenKeyDB(readOnly, appName, prefix, - lg_keydb_name_cb, (void *)name); + name = PR_smprintf("%s" PATH_SEPARATOR "%s", configdir, prefix); + if (name == NULL) + return CKR_HOST_MEMORY; + keydb = nsslowkey_OpenKeyDB(readOnly, appName, prefix, + lg_keydb_name_cb, (void *)name); PR_smprintf_free(name); - if (appName) PORT_Free(appName); + if (appName) + PORT_Free(appName); if (keydb == NULL) - return CKR_NETSCAPE_KEYDB_FAILED; + return CKR_NETSCAPE_KEYDB_FAILED; *keydbPtr = keydb; return CKR_OK; @@ -407,21 +411,21 @@ lg_OpenKeyDB(const char * configdir, const char *prefix, PRBool readOnly, * Accessors for the private parts of the sdb structure. */ void -lg_DBLock(SDB *sdb) +lg_DBLock(SDB *sdb) { LGPrivate *lgdb_p = (LGPrivate *)sdb->private; SKIP_AFTER_FORK(PR_Lock(lgdb_p->dbLock)); } void -lg_DBUnlock(SDB *sdb) +lg_DBUnlock(SDB *sdb) { LGPrivate *lgdb_p = (LGPrivate *)sdb->private; SKIP_AFTER_FORK(PR_Unlock(lgdb_p->dbLock)); } PLHashTable * -lg_GetHashTable(SDB *sdb) +lg_GetHashTable(SDB *sdb) { LGPrivate *lgdb_p = (LGPrivate *)sdb->private; return lgdb_p->hashTable; @@ -445,7 +449,8 @@ lg_getKeyDB(SDB *sdb) PRBool lg_parentForkedAfterC_Initialize; -void lg_SetForkState(PRBool forked) +void +lg_SetForkState(PRBool forked) { lg_parentForkedAfterC_Initialize = forked; } @@ -456,18 +461,18 @@ lg_Close(SDB *sdb) LGPrivate *lgdb_p = (LGPrivate *)sdb->private; lg_ClearTokenKeyHashTable(sdb); if (lgdb_p) { - if (lgdb_p->certDB) { - nsslowcert_ClosePermCertDB(lgdb_p->certDB); - } else if (lgdb_p->keyDB) { - nsslowkey_CloseKeyDB(lgdb_p->keyDB); - } - if (lgdb_p->dbLock) { - SKIP_AFTER_FORK(PR_DestroyLock(lgdb_p->dbLock)); - } - if (lgdb_p->hashTable) { - PL_HashTableDestroy(lgdb_p->hashTable); - } - PORT_Free(lgdb_p); + if (lgdb_p->certDB) { + nsslowcert_ClosePermCertDB(lgdb_p->certDB); + } else if (lgdb_p->keyDB) { + nsslowkey_CloseKeyDB(lgdb_p->keyDB); + } + if (lgdb_p->dbLock) { + SKIP_AFTER_FORK(PR_DestroyLock(lgdb_p->dbLock)); + } + if (lgdb_p->hashTable) { + PL_HashTableDestroy(lgdb_p->hashTable); + } + PORT_Free(lgdb_p); } PORT_Free(sdb); return CKR_OK; @@ -483,39 +488,38 @@ lg_HashNumber(const void *key) * helper function to wrap a NSSLOWCERTCertDBHandle or a NSSLOWKEYDBHandle * with and sdb structure. */ -CK_RV +CK_RV lg_init(SDB **pSdb, int flags, NSSLOWCERTCertDBHandle *certdbPtr, - NSSLOWKEYDBHandle *keydbPtr) + NSSLOWKEYDBHandle *keydbPtr) { SDB *sdb = NULL; LGPrivate *lgdb_p = NULL; CK_RV error = CKR_HOST_MEMORY; *pSdb = NULL; - sdb = (SDB *) PORT_Alloc(sizeof(SDB)); + sdb = (SDB *)PORT_Alloc(sizeof(SDB)); if (sdb == NULL) { - goto loser; + goto loser; } - lgdb_p = (LGPrivate *) PORT_Alloc(sizeof(LGPrivate)); + lgdb_p = (LGPrivate *)PORT_Alloc(sizeof(LGPrivate)); if (lgdb_p == NULL) { - goto loser; + goto loser; } /* invariant fields */ lgdb_p->certDB = certdbPtr; lgdb_p->keyDB = keydbPtr; lgdb_p->dbLock = PR_NewLock(); if (lgdb_p->dbLock == NULL) { - goto loser; + goto loser; } lgdb_p->hashTable = PL_NewHashTable(64, lg_HashNumber, PL_CompareValues, - SECITEM_HashCompare, NULL, 0); + SECITEM_HashCompare, NULL, 0); if (lgdb_p->hashTable == NULL) { - goto loser; + goto loser; } sdb->private = lgdb_p; sdb->version = 0; - /*sdb->sdb_type = SDB_LEGACY; */ sdb->sdb_flags = flags; sdb->app_private = NULL; sdb->sdb_FindObjectsInit = lg_FindObjectsInit; @@ -539,19 +543,18 @@ lg_init(SDB **pSdb, int flags, NSSLOWCERTCertDBHandle *certdbPtr, loser: if (sdb) { - PORT_Free(sdb); + PORT_Free(sdb); } if (lgdb_p) { - if (lgdb_p->dbLock) { - PR_DestroyLock(lgdb_p->dbLock); - } - if (lgdb_p->hashTable) { - PL_HashTableDestroy(lgdb_p->hashTable); - } - PORT_Free(lgdb_p); + if (lgdb_p->dbLock) { + PR_DestroyLock(lgdb_p->dbLock); + } + if (lgdb_p->hashTable) { + PL_HashTableDestroy(lgdb_p->hashTable); + } + PORT_Free(lgdb_p); } return error; - } /* @@ -559,80 +562,88 @@ loser: * * configdir - base directory where all the cert, key, and module datbases live. * certPrefix - prefix added to the beginning of the cert database example: " - * "https-server1-" + * "https-server1-" * keyPrefix - prefix added to the beginning of the key database example: " - * "https-server1-" + * "https-server1-" * secmodName - name of the security module database (usually "secmod.db"). * readOnly - Boolean: true if the databases are to be openned read only. - * nocertdb - Don't open the cert DB and key DB's, just initialize the - * Volatile certdb. - * nomoddb - Don't open the security module DB, just initialize the - * PKCS #11 module. + * nocertdb - Don't open the cert DB and key DB's, just initialize the + * Volatile certdb. + * nomoddb - Don't open the security module DB, just initialize the + * PKCS #11 module. * forceOpen - Continue to force initializations even if the databases cannot - * be opened. + * be opened. */ CK_RV -legacy_Open(const char *configdir, const char *certPrefix, - const char *keyPrefix, int certVersion, int keyVersion, - int flags, SDB **certDB, SDB **keyDB) +legacy_Open(const char *configdir, const char *certPrefix, + const char *keyPrefix, int certVersion, int keyVersion, + int flags, SDB **certDB, SDB **keyDB) { CK_RV crv = CKR_OK; SECStatus rv; - PRBool readOnly = (flags == SDB_RDONLY)? PR_TRUE: PR_FALSE; + PRBool readOnly = ((flags & 0x7) == SDB_RDONLY) ? PR_TRUE : PR_FALSE; #define NSS_VERSION_VARIABLE __nss_dbm_version #include "verref.h" + if (flags & SDB_FIPS) { + if (!lg_FIPSEntryOK()) { + return CKR_DEVICE_ERROR; + } + } + rv = SECOID_Init(); if (SECSuccess != rv) { return CKR_DEVICE_ERROR; } nsslowcert_InitLocks(); - if (keyDB) *keyDB = NULL; - if (certDB) *certDB = NULL; + if (keyDB) + *keyDB = NULL; + if (certDB) + *certDB = NULL; if (certDB) { - NSSLOWCERTCertDBHandle *certdbPtr = NULL; - - crv = lg_OpenCertDB(configdir, certPrefix, readOnly, &certdbPtr); - if (crv != CKR_OK) { - goto loser; - } - crv = lg_init(certDB, flags, certdbPtr, NULL); - if (crv != CKR_OK) { - nsslowcert_ClosePermCertDB(certdbPtr); - goto loser; - } + NSSLOWCERTCertDBHandle *certdbPtr = NULL; + + crv = lg_OpenCertDB(configdir, certPrefix, readOnly, &certdbPtr); + if (crv != CKR_OK) { + goto loser; + } + crv = lg_init(certDB, flags, certdbPtr, NULL); + if (crv != CKR_OK) { + nsslowcert_ClosePermCertDB(certdbPtr); + goto loser; + } } if (keyDB) { - NSSLOWKEYDBHandle *keydbPtr; - - crv = lg_OpenKeyDB(configdir, keyPrefix, readOnly, &keydbPtr); - if (crv != CKR_OK) { - goto loser; - } - crv = lg_init(keyDB, flags, NULL, keydbPtr); - if (crv != CKR_OK) { - nsslowkey_CloseKeyDB(keydbPtr); - goto loser; - } - if (certDB && *certDB) { - LGPrivate *lgdb_p = (LGPrivate *)(*certDB)->private; - lgdb_p->keyDB = keydbPtr; - } + NSSLOWKEYDBHandle *keydbPtr; + + crv = lg_OpenKeyDB(configdir, keyPrefix, readOnly, &keydbPtr); + if (crv != CKR_OK) { + goto loser; + } + crv = lg_init(keyDB, flags, NULL, keydbPtr); + if (crv != CKR_OK) { + nsslowkey_CloseKeyDB(keydbPtr); + goto loser; + } + if (certDB && *certDB) { + LGPrivate *lgdb_p = (LGPrivate *)(*certDB)->private; + lgdb_p->keyDB = keydbPtr; + } } loser: if (crv != CKR_OK) { - if (keyDB && *keyDB) { - lg_Close(*keyDB); - *keyDB = NULL; - } - if (certDB && *certDB) { - lg_Close(*certDB); - *certDB = NULL; - } + if (keyDB && *keyDB) { + lg_Close(*keyDB); + *keyDB = NULL; + } + if (certDB && *certDB) { + lg_Close(*certDB); + *certDB = NULL; + } } return crv; } @@ -647,4 +658,3 @@ legacy_Shutdown(PRBool forked) lg_SetForkState(PR_FALSE); return CKR_OK; } - diff --git a/nss/lib/softoken/legacydb/lgutil.c b/nss/lib/softoken/legacydb/lgutil.c index 1b45bb0..d872bf4 100644 --- a/nss/lib/softoken/legacydb/lgutil.c +++ b/nss/lib/softoken/legacydb/lgutil.c @@ -11,98 +11,100 @@ /* * look up and attribute structure from a type and Object structure. - * The returned attribute is referenced and needs to be freed when + * The returned attribute is referenced and needs to be freed when * it is no longer needed. */ const CK_ATTRIBUTE * lg_FindAttribute(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, - CK_ULONG count ) + CK_ULONG count) { unsigned int i; - for (i=0; i < count; i++) { - if (templ[i].type == type) { - return &templ[i]; - } + for (i = 0; i < count; i++) { + if (templ[i].type == type) { + return &templ[i]; + } } return NULL; } - /* * return true if object has attribute */ PRBool lg_hasAttribute(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, - CK_ULONG count ) + CK_ULONG count) { - if (lg_FindAttribute(type, templ, count) == NULL) { - return PR_FALSE; - } - return PR_TRUE; + if (lg_FindAttribute(type, templ, count) == NULL) { + return PR_FALSE; + } + return PR_TRUE; } -/* +/* * copy an attribute into a SECItem. Secitem is allocated in the specified * arena. */ CK_RV lg_Attribute2SecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item) + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item) { int len; const CK_ATTRIBUTE *attribute; attribute = lg_FindAttribute(type, templ, count); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; len = attribute->ulValueLen; if (arena) { - item->data = (unsigned char *) PORT_ArenaAlloc(arena,len); + item->data = (unsigned char *)PORT_ArenaAlloc(arena, len); } else { - item->data = (unsigned char *) PORT_Alloc(len); + item->data = (unsigned char *)PORT_Alloc(len); } if (item->data == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } item->len = len; - PORT_Memcpy(item->data, attribute->pValue, len); + if (item->len) { + PORT_Memcpy(item->data, attribute->pValue, len); + } return CKR_OK; } - -/* +/* * copy an unsigned attribute into a SECItem. Secitem is allocated in * the specified arena. */ CK_RV lg_Attribute2SSecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item) + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item) { const CK_ATTRIBUTE *attribute; item->data = NULL; attribute = lg_FindAttribute(type, templ, count); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; (void)SECITEM_AllocItem(arena, item, attribute->ulValueLen); if (item->data == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } PORT_Memcpy(item->data, attribute->pValue, item->len); return CKR_OK; } -/* +/* * copy an unsigned attribute into a SECItem. Secitem is allocated in * the specified arena. */ CK_RV lg_PrivAttr2SSecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item, SDB *sdbpw) + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item, SDB *sdbpw) { const CK_ATTRIBUTE *attribute; SECItem epki, *dest = NULL; @@ -111,21 +113,22 @@ lg_PrivAttr2SSecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, item->data = NULL; attribute = lg_FindAttribute(type, templ, count); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; epki.data = attribute->pValue; epki.len = attribute->ulValueLen; rv = lg_util_decrypt(sdbpw, &epki, &dest); if (rv != SECSuccess) { - return CKR_USER_NOT_LOGGED_IN; + return CKR_USER_NOT_LOGGED_IN; } (void)SECITEM_AllocItem(arena, item, dest->len); if (item->data == NULL) { - SECITEM_FreeItem(dest, PR_TRUE); - return CKR_HOST_MEMORY; + SECITEM_FreeItem(dest, PR_TRUE); + return CKR_HOST_MEMORY; } - + PORT_Memcpy(item->data, dest->data, item->len); SECITEM_FreeItem(dest, PR_TRUE); return CKR_OK; @@ -133,8 +136,8 @@ lg_PrivAttr2SSecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, CK_RV lg_PrivAttr2SecItem(PLArenaPool *arena, CK_ATTRIBUTE_TYPE type, - const CK_ATTRIBUTE *templ, CK_ULONG count, - SECItem *item, SDB *sdbpw) + const CK_ATTRIBUTE *templ, CK_ULONG count, + SECItem *item, SDB *sdbpw) { return lg_PrivAttr2SSecItem(arena, type, templ, count, item, sdbpw); } @@ -149,8 +152,10 @@ lg_isTrue(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, CK_ULONG count) const CK_ATTRIBUTE *attribute; PRBool tok = PR_FALSE; - attribute=lg_FindAttribute(type, templ, count); - if (attribute == NULL) { return PR_FALSE; } + attribute = lg_FindAttribute(type, templ, count); + if (attribute == NULL) { + return PR_FALSE; + } tok = (PRBool)(*(CK_BBOOL *)attribute->pValue); return tok; @@ -167,23 +172,24 @@ lg_getString(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, CK_ULONG count) char *label = NULL; attribute = lg_FindAttribute(type, templ, count); - if (attribute == NULL) return NULL; + if (attribute == NULL) + return NULL; if (attribute->pValue != NULL) { - label = (char *) PORT_Alloc(attribute->ulValueLen+1); - if (label == NULL) { - return NULL; - } + label = (char *)PORT_Alloc(attribute->ulValueLen + 1); + if (label == NULL) { + return NULL; + } - PORT_Memcpy(label,attribute->pValue, attribute->ulValueLen); - label[attribute->ulValueLen] = 0; + PORT_Memcpy(label, attribute->pValue, attribute->ulValueLen); + label[attribute->ulValueLen] = 0; } return label; } CK_RV lg_GetULongAttribute(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, - CK_ULONG count, CK_ULONG *longData) + CK_ULONG count, CK_ULONG *longData) { const CK_ATTRIBUTE *attribute; CK_ULONG value = 0; @@ -191,14 +197,15 @@ lg_GetULongAttribute(CK_ATTRIBUTE_TYPE type, const CK_ATTRIBUTE *templ, int i; attribute = lg_FindAttribute(type, templ, count); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; if (attribute->ulValueLen != 4) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } data = (const unsigned char *)attribute->pValue; - for (i=0; i < 4; i++) { - value |= (CK_ULONG)(data[i]) << ((3-i)*8); + for (i = 0; i < 4; i++) { + value |= (CK_ULONG)(data[i]) << ((3 - i) * 8); } *longData = value; @@ -214,12 +221,12 @@ lg_deleteTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle) { SECItem *item; PRBool rem; - PLHashTable *hashTable= lg_GetHashTable(sdb); + PLHashTable *hashTable = lg_GetHashTable(sdb); item = (SECItem *)PL_HashTableLookup(hashTable, (void *)handle); - rem = PL_HashTableRemove(hashTable,(void *)handle) ; + rem = PL_HashTableRemove(hashTable, (void *)handle); if (rem && item) { - SECITEM_FreeItem(item,PR_TRUE); + SECITEM_FreeItem(item, PR_TRUE); } return rem ? SECSuccess : SECFailure; } @@ -230,16 +237,16 @@ lg_addTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle, SECItem *key) { PLHashEntry *entry; SECItem *item; - PLHashTable *hashTable= lg_GetHashTable(sdb); + PLHashTable *hashTable = lg_GetHashTable(sdb); item = SECITEM_DupItem(key); if (item == NULL) { - return SECFailure; + return SECFailure; } - entry = PL_HashTableAdd(hashTable,(void *)handle,item); + entry = PL_HashTableAdd(hashTable, (void *)handle, item); if (entry == NULL) { - SECITEM_FreeItem(item,PR_TRUE); - return SECFailure; + SECITEM_FreeItem(item, PR_TRUE); + return SECFailure; } return SECSuccess; } @@ -248,13 +255,12 @@ lg_addTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle, SECItem *key) const SECItem * lg_lookupTokenKeyByHandle(SDB *sdb, CK_OBJECT_HANDLE handle) { - PLHashTable *hashTable= lg_GetHashTable(sdb); + PLHashTable *hashTable = lg_GetHashTable(sdb); return (const SECItem *)PL_HashTableLookup(hashTable, (void *)handle); } - static PRIntn -lg_freeHashItem(PLHashEntry* entry, PRIntn index, void *arg) +lg_freeHashItem(PLHashEntry *entry, PRIntn index, void *arg) { SECItem *item = (SECItem *)entry->value; @@ -267,7 +273,7 @@ lg_ClearTokenKeyHashTable(SDB *sdb) { PLHashTable *hashTable; lg_DBLock(sdb); - hashTable= lg_GetHashTable(sdb); + hashTable = lg_GetHashTable(sdb); PL_HashTableEnumerateEntries(hashTable, lg_freeHashItem, NULL); lg_DBUnlock(sdb); return CKR_OK; @@ -279,16 +285,16 @@ lg_ClearTokenKeyHashTable(SDB *sdb) static void lg_XORHash(unsigned char *key, unsigned char *dbkey, int len) { - int i; + int i; - PORT_Memset(key, 0, 4); + PORT_Memset(key, 0, 4); - for (i=0; i < len-4; i += 4) { - key[0] ^= dbkey[i]; - key[1] ^= dbkey[i+1]; - key[2] ^= dbkey[i+2]; - key[3] ^= dbkey[i+3]; - } + for (i = 0; i < len - 4; i += 4) { + key[0] ^= dbkey[i]; + key[1] ^= dbkey[i + 1]; + key[2] ^= dbkey[i + 2]; + key[3] ^= dbkey[i + 3]; + } } /* Make a token handle for an object and record it so we can find it again */ @@ -302,28 +308,28 @@ lg_mkHandle(SDB *sdb, SECItem *dbKey, CK_OBJECT_HANDLE class) handle = class; /* there is only one KRL, use a fixed handle for it */ if (handle != LG_TOKEN_KRL_HANDLE) { - lg_XORHash(hashBuf,dbKey->data,dbKey->len); + lg_XORHash(hashBuf, dbKey->data, dbKey->len); handle = ((CK_OBJECT_HANDLE)hashBuf[0] << 24) | ((CK_OBJECT_HANDLE)hashBuf[1] << 16) | - ((CK_OBJECT_HANDLE)hashBuf[2] << 8) | + ((CK_OBJECT_HANDLE)hashBuf[2] << 8) | (CK_OBJECT_HANDLE)hashBuf[3]; - handle = class | (handle & ~(LG_TOKEN_TYPE_MASK|LG_TOKEN_MASK)); - /* we have a CRL who's handle has randomly matched the reserved KRL - * handle, increment it */ - if (handle == LG_TOKEN_KRL_HANDLE) { - handle++; - } + handle = class | (handle & ~(LG_TOKEN_TYPE_MASK | LG_TOKEN_MASK)); + /* we have a CRL who's handle has randomly matched the reserved KRL + * handle, increment it */ + if (handle == LG_TOKEN_KRL_HANDLE) { + handle++; + } } lg_DBLock(sdb); - while ((key = lg_lookupTokenKeyByHandle(sdb,handle)) != NULL) { - if (SECITEM_ItemsAreEqual(key,dbKey)) { - lg_DBUnlock(sdb); - return handle; - } - handle++; + while ((key = lg_lookupTokenKeyByHandle(sdb, handle)) != NULL) { + if (SECITEM_ItemsAreEqual(key, dbKey)) { + lg_DBUnlock(sdb); + return handle; + } + handle++; } - lg_addTokenKeyByHandle(sdb,handle,dbKey); + lg_addTokenKeyByHandle(sdb, handle, dbKey); lg_DBUnlock(sdb); return handle; } @@ -338,24 +344,24 @@ lg_poisonHandle(SDB *sdb, SECItem *dbKey, CK_OBJECT_HANDLE class) handle = class; /* there is only one KRL, use a fixed handle for it */ if (handle != LG_TOKEN_KRL_HANDLE) { - lg_XORHash(hashBuf,dbKey->data,dbKey->len); - handle = (hashBuf[0] << 24) | (hashBuf[1] << 16) | - (hashBuf[2] << 8) | hashBuf[3]; - handle = class | (handle & ~(LG_TOKEN_TYPE_MASK|LG_TOKEN_MASK)); - /* we have a CRL who's handle has randomly matched the reserved KRL - * handle, increment it */ - if (handle == LG_TOKEN_KRL_HANDLE) { - handle++; - } + lg_XORHash(hashBuf, dbKey->data, dbKey->len); + handle = (hashBuf[0] << 24) | (hashBuf[1] << 16) | + (hashBuf[2] << 8) | hashBuf[3]; + handle = class | (handle & ~(LG_TOKEN_TYPE_MASK | LG_TOKEN_MASK)); + /* we have a CRL who's handle has randomly matched the reserved KRL + * handle, increment it */ + if (handle == LG_TOKEN_KRL_HANDLE) { + handle++; + } } lg_DBLock(sdb); - while ((key = lg_lookupTokenKeyByHandle(sdb,handle)) != NULL) { - if (SECITEM_ItemsAreEqual(key,dbKey)) { - key->data[0] ^= 0x80; - lg_DBUnlock(sdb); - return PR_TRUE; - } - handle++; + while ((key = lg_lookupTokenKeyByHandle(sdb, handle)) != NULL) { + if (SECITEM_ItemsAreEqual(key, dbKey)) { + key->data[0] ^= 0x80; + lg_DBUnlock(sdb); + return PR_TRUE; + } + handle++; } lg_DBUnlock(sdb); return PR_FALSE; @@ -367,27 +373,27 @@ static LGDecryptFunc lg_decrypt_stub = NULL; void legacy_SetCryptFunctions(LGEncryptFunc enc, LGDecryptFunc dec) { - lg_encrypt_stub = enc; - lg_decrypt_stub = dec; + lg_encrypt_stub = enc; + lg_decrypt_stub = dec; } -SECStatus lg_util_encrypt(PLArenaPool *arena, SDB *sdb, - SECItem *plainText, SECItem **cipherText) +SECStatus +lg_util_encrypt(PLArenaPool *arena, SDB *sdb, + SECItem *plainText, SECItem **cipherText) { if (lg_encrypt_stub == NULL) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } return (*lg_encrypt_stub)(arena, sdb, plainText, cipherText); } -SECStatus lg_util_decrypt(SDB *sdb, SECItem *cipherText, SECItem **plainText) +SECStatus +lg_util_decrypt(SDB *sdb, SECItem *cipherText, SECItem **plainText) { if (lg_decrypt_stub == NULL) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } return (*lg_decrypt_stub)(sdb, cipherText, plainText); } - - diff --git a/nss/lib/softoken/legacydb/lowcert.c b/nss/lib/softoken/legacydb/lowcert.c index a8191d8..2906120 100644 --- a/nss/lib/softoken/legacydb/lowcert.c +++ b/nss/lib/softoken/legacydb/lowcert.c @@ -20,26 +20,26 @@ SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) static const SEC_ASN1Template nsslowcert_SubjectPublicKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWCERTSubjectPublicKeyInfo) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(NSSLOWCERTSubjectPublicKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(NSSLOWCERTSubjectPublicKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_BIT_STRING, - offsetof(NSSLOWCERTSubjectPublicKeyInfo,subjectPublicKey), }, - { 0, } + offsetof(NSSLOWCERTSubjectPublicKeyInfo, subjectPublicKey) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_RSAPublicKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPublicKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.modulus), }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.rsa.publicExponent), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.rsa.publicExponent) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_DSAPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dsa.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.dsa.publicValue) }, + { 0 } }; static const SEC_ASN1Template nsslowcert_DHPublicKeyTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey,u.dh.publicValue), }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPublicKey, u.dh.publicValue) }, + { 0 } }; /* @@ -77,17 +77,18 @@ prepare_low_dh_pub_key_for_asn1(NSSLOWKEYPublicKey *pubk) /* * simple cert decoder to avoid the cost of asn1 engine - */ + */ static unsigned char * -nsslowcert_dataStart(unsigned char *buf, unsigned int length, - unsigned int *data_length, PRBool includeTag, - unsigned char* rettag) { +nsslowcert_dataStart(unsigned char *buf, unsigned int length, + unsigned int *data_length, PRBool includeTag, + unsigned char *rettag) +{ unsigned char tag; - unsigned int used_length= 0; + unsigned int used_length = 0; /* need at least a tag and a 1 byte length */ if (length < 2) { - return NULL; + return NULL; } tag = buf[used_length++]; @@ -98,35 +99,37 @@ nsslowcert_dataStart(unsigned char *buf, unsigned int length, /* blow out when we come to the end */ if (tag == 0) { - return NULL; + return NULL; } *data_length = buf[used_length++]; - if (*data_length&0x80) { - int len_count = *data_length & 0x7f; + if (*data_length & 0x80) { + int len_count = *data_length & 0x7f; - if (len_count+used_length > length) { - return NULL; - } + if (len_count + used_length > length) { + return NULL; + } - *data_length = 0; + *data_length = 0; - while (len_count-- > 0) { - *data_length = (*data_length << 8) | buf[used_length++]; - } + while (len_count-- > 0) { + *data_length = (*data_length << 8) | buf[used_length++]; + } } - if (*data_length > (length-used_length) ) { - *data_length = length-used_length; - return NULL; + if (*data_length > (length - used_length)) { + *data_length = length - used_length; + return NULL; } - if (includeTag) *data_length += used_length; + if (includeTag) + *data_length += used_length; - return (buf + (includeTag ? 0 : used_length)); + return (buf + (includeTag ? 0 : used_length)); } -static void SetTimeType(SECItem* item, unsigned char tagtype) +static void +SetTimeType(SECItem *item, unsigned char tagtype) { switch (tagtype) { case SEC_ASN1_UTC_TIME: @@ -144,27 +147,29 @@ static void SetTimeType(SECItem* item, unsigned char tagtype) } static int -nsslowcert_GetValidityFields(unsigned char *buf,int buf_length, - SECItem *notBefore, SECItem *notAfter) +nsslowcert_GetValidityFields(unsigned char *buf, int buf_length, + SECItem *notBefore, SECItem *notAfter) { unsigned char tagtype; - notBefore->data = nsslowcert_dataStart(buf,buf_length, - ¬Before->len,PR_FALSE, &tagtype); - if (notBefore->data == NULL) return SECFailure; + notBefore->data = nsslowcert_dataStart(buf, buf_length, + ¬Before->len, PR_FALSE, &tagtype); + if (notBefore->data == NULL) + return SECFailure; SetTimeType(notBefore, tagtype); - buf_length -= (notBefore->data-buf) + notBefore->len; + buf_length -= (notBefore->data - buf) + notBefore->len; buf = notBefore->data + notBefore->len; - notAfter->data = nsslowcert_dataStart(buf,buf_length, - ¬After->len,PR_FALSE, &tagtype); - if (notAfter->data == NULL) return SECFailure; + notAfter->data = nsslowcert_dataStart(buf, buf_length, + ¬After->len, PR_FALSE, &tagtype); + if (notAfter->data == NULL) + return SECFailure; SetTimeType(notAfter, tagtype); return SECSuccess; } static int -nsslowcert_GetCertFields(unsigned char *cert,int cert_length, - SECItem *issuer, SECItem *serial, SECItem *derSN, SECItem *subject, - SECItem *valid, SECItem *subjkey, SECItem *extensions) +nsslowcert_GetCertFields(unsigned char *cert, int cert_length, + SECItem *issuer, SECItem *serial, SECItem *derSN, SECItem *subject, + SECItem *valid, SECItem *subjkey, SECItem *extensions) { unsigned char *buf; unsigned int buf_length; @@ -172,87 +177,97 @@ nsslowcert_GetCertFields(unsigned char *cert,int cert_length, unsigned int dummylen; /* get past the signature wrap */ - buf = nsslowcert_dataStart(cert,cert_length,&buf_length,PR_FALSE, NULL); - if (buf == NULL) return SECFailure; + buf = nsslowcert_dataStart(cert, cert_length, &buf_length, PR_FALSE, NULL); + if (buf == NULL) + return SECFailure; /* get into the raw cert data */ - buf = nsslowcert_dataStart(buf,buf_length,&buf_length,PR_FALSE, NULL); - if (buf == NULL) return SECFailure; + buf = nsslowcert_dataStart(buf, buf_length, &buf_length, PR_FALSE, NULL); + if (buf == NULL) + return SECFailure; /* skip past any optional version number */ if ((buf[0] & 0xa0) == 0xa0) { - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE, NULL); - if (dummy == NULL) return SECFailure; - buf_length -= (dummy-buf) + dummylen; - buf = dummy + dummylen; + dummy = nsslowcert_dataStart(buf, buf_length, &dummylen, PR_FALSE, NULL); + if (dummy == NULL) + return SECFailure; + buf_length -= (dummy - buf) + dummylen; + buf = dummy + dummylen; } /* serial number */ if (derSN) { - derSN->data=nsslowcert_dataStart(buf,buf_length,&derSN->len,PR_TRUE, NULL); - /* derSN->data doesn't need to be checked because if it fails so will - * serial->data below. The only difference between the two calls is - * whether or not the tags are included in the returned buffer */ - } - serial->data = nsslowcert_dataStart(buf,buf_length,&serial->len,PR_FALSE, NULL); - if (serial->data == NULL) return SECFailure; - buf_length -= (serial->data-buf) + serial->len; + derSN->data = nsslowcert_dataStart(buf, buf_length, &derSN->len, PR_TRUE, NULL); + /* derSN->data doesn't need to be checked because if it fails so will + * serial->data below. The only difference between the two calls is + * whether or not the tags are included in the returned buffer */ + } + serial->data = nsslowcert_dataStart(buf, buf_length, &serial->len, PR_FALSE, NULL); + if (serial->data == NULL) + return SECFailure; + buf_length -= (serial->data - buf) + serial->len; buf = serial->data + serial->len; /* skip the OID */ - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE, NULL); - if (dummy == NULL) return SECFailure; - buf_length -= (dummy-buf) + dummylen; + dummy = nsslowcert_dataStart(buf, buf_length, &dummylen, PR_FALSE, NULL); + if (dummy == NULL) + return SECFailure; + buf_length -= (dummy - buf) + dummylen; buf = dummy + dummylen; /* issuer */ - issuer->data = nsslowcert_dataStart(buf,buf_length,&issuer->len,PR_TRUE, NULL); - if (issuer->data == NULL) return SECFailure; - buf_length -= (issuer->data-buf) + issuer->len; + issuer->data = nsslowcert_dataStart(buf, buf_length, &issuer->len, PR_TRUE, NULL); + if (issuer->data == NULL) + return SECFailure; + buf_length -= (issuer->data - buf) + issuer->len; buf = issuer->data + issuer->len; /* only wanted issuer/SN */ if (valid == NULL) { - return SECSuccess; + return SECSuccess; } /* validity */ - valid->data = nsslowcert_dataStart(buf,buf_length,&valid->len,PR_FALSE, NULL); - if (valid->data == NULL) return SECFailure; - buf_length -= (valid->data-buf) + valid->len; + valid->data = nsslowcert_dataStart(buf, buf_length, &valid->len, PR_FALSE, NULL); + if (valid->data == NULL) + return SECFailure; + buf_length -= (valid->data - buf) + valid->len; buf = valid->data + valid->len; /*subject */ - subject->data=nsslowcert_dataStart(buf,buf_length,&subject->len,PR_TRUE, NULL); - if (subject->data == NULL) return SECFailure; - buf_length -= (subject->data-buf) + subject->len; + subject->data = nsslowcert_dataStart(buf, buf_length, &subject->len, PR_TRUE, NULL); + if (subject->data == NULL) + return SECFailure; + buf_length -= (subject->data - buf) + subject->len; buf = subject->data + subject->len; /* subject key info */ - subjkey->data=nsslowcert_dataStart(buf,buf_length,&subjkey->len,PR_TRUE, NULL); - if (subjkey->data == NULL) return SECFailure; - buf_length -= (subjkey->data-buf) + subjkey->len; + subjkey->data = nsslowcert_dataStart(buf, buf_length, &subjkey->len, PR_TRUE, NULL); + if (subjkey->data == NULL) + return SECFailure; + buf_length -= (subjkey->data - buf) + subjkey->len; buf = subjkey->data + subjkey->len; extensions->data = NULL; extensions->len = 0; while (buf_length > 0) { - /* EXTENSIONS */ - if (buf[0] == 0xa3) { - extensions->data = nsslowcert_dataStart(buf,buf_length, - &extensions->len, PR_FALSE, NULL); - /* if the DER is bad, we should fail. Previously we accepted - * bad DER here and treated the extension as missin */ - if (extensions->data == NULL || - (extensions->data - buf) + extensions->len != buf_length) + /* EXTENSIONS */ + if (buf[0] == 0xa3) { + extensions->data = nsslowcert_dataStart(buf, buf_length, + &extensions->len, PR_FALSE, NULL); + /* if the DER is bad, we should fail. Previously we accepted + * bad DER here and treated the extension as missin */ + if (extensions->data == NULL || + (extensions->data - buf) + extensions->len != buf_length) return SECFailure; buf = extensions->data; - buf_length = extensions->len; + buf_length = extensions->len; /* now parse the SEQUENCE holding the extensions. */ - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE,NULL); + dummy = nsslowcert_dataStart(buf, buf_length, &dummylen, PR_FALSE, NULL); if (dummy == NULL || - (dummy - buf) + dummylen != buf_length) + (dummy - buf) + dummylen != buf_length) return SECFailure; buf_length -= (dummy - buf); buf = dummy; /* Now parse the extensions inside this sequence */ - } - dummy = nsslowcert_dataStart(buf,buf_length,&dummylen,PR_FALSE,NULL); - if (dummy == NULL) return SECFailure; - buf_length -= (dummy - buf) + dummylen; - buf = dummy + dummylen; + } + dummy = nsslowcert_dataStart(buf, buf_length, &dummylen, PR_FALSE, NULL); + if (dummy == NULL) + return SECFailure; + buf_length -= (dummy - buf) + dummylen; + buf = dummy + dummylen; } return SECSuccess; } @@ -263,25 +278,25 @@ nsslowcert_GetCertTimes(NSSLOWCERTCertificate *c, PRTime *notBefore, PRTime *not int rv; NSSLOWCERTValidity validity; - rv = nsslowcert_GetValidityFields(c->validity.data,c->validity.len, - &validity.notBefore,&validity.notAfter); + rv = nsslowcert_GetValidityFields(c->validity.data, c->validity.len, + &validity.notBefore, &validity.notAfter); if (rv != SECSuccess) { - return rv; + return rv; } - + /* convert DER not-before time */ rv = DER_DecodeTimeChoice(notBefore, &validity.notBefore); if (rv) { - return(SECFailure); + return (SECFailure); } - + /* convert DER not-after time */ rv = DER_DecodeTimeChoice(notAfter, &validity.notAfter); if (rv) { - return(SECFailure); + return (SECFailure); } - return(SECSuccess); + return (SECSuccess); } /* @@ -293,52 +308,52 @@ nsslowcert_IsNewer(NSSLOWCERTCertificate *certa, NSSLOWCERTCertificate *certb) PRTime notBeforeA, notAfterA, notBeforeB, notAfterB, now; SECStatus rv; PRBool newerbefore, newerafter; - + rv = nsslowcert_GetCertTimes(certa, ¬BeforeA, ¬AfterA); - if ( rv != SECSuccess ) { - return(PR_FALSE); + if (rv != SECSuccess) { + return (PR_FALSE); } - + rv = nsslowcert_GetCertTimes(certb, ¬BeforeB, ¬AfterB); - if ( rv != SECSuccess ) { - return(PR_TRUE); + if (rv != SECSuccess) { + return (PR_TRUE); } newerbefore = PR_FALSE; - if ( LL_CMP(notBeforeA, >, notBeforeB) ) { - newerbefore = PR_TRUE; + if (LL_CMP(notBeforeA, >, notBeforeB)) { + newerbefore = PR_TRUE; } newerafter = PR_FALSE; - if ( LL_CMP(notAfterA, >, notAfterB) ) { - newerafter = PR_TRUE; + if (LL_CMP(notAfterA, >, notAfterB)) { + newerafter = PR_TRUE; } - - if ( newerbefore && newerafter ) { - return(PR_TRUE); + + if (newerbefore && newerafter) { + return (PR_TRUE); } - - if ( ( !newerbefore ) && ( !newerafter ) ) { - return(PR_FALSE); + + if ((!newerbefore) && (!newerafter)) { + return (PR_FALSE); } /* get current time */ now = PR_Now(); - if ( newerbefore ) { - /* cert A was issued after cert B, but expires sooner */ - /* if A is expired, then pick B */ - if ( LL_CMP(notAfterA, <, now ) ) { - return(PR_FALSE); - } - return(PR_TRUE); + if (newerbefore) { + /* cert A was issued after cert B, but expires sooner */ + /* if A is expired, then pick B */ + if (LL_CMP(notAfterA, <, now)) { + return (PR_FALSE); + } + return (PR_TRUE); } else { - /* cert B was issued after cert A, but expires sooner */ - /* if B is expired, then pick A */ - if ( LL_CMP(notAfterB, <, now ) ) { - return(PR_TRUE); - } - return(PR_FALSE); + /* cert B was issued after cert A, but expires sooner */ + /* if B is expired, then pick A */ + if (LL_CMP(notAfterB, <, now)) { + return (PR_TRUE); + } + return (PR_FALSE); } } @@ -346,21 +361,21 @@ nsslowcert_IsNewer(NSSLOWCERTCertificate *certa, NSSLOWCERTCertificate *certb) static SECStatus nsslowcert_KeyFromIssuerAndSN(PLArenaPool *arena, - SECItem *issuer, SECItem *sn, SECItem *key) + SECItem *issuer, SECItem *sn, SECItem *key) { unsigned int len = sn->len + issuer->len; if (!arena) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; + goto loser; } if (len > NSS_MAX_LEGACY_DB_KEY_SIZE) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - goto loser; + PORT_SetError(SEC_ERROR_INPUT_LEN); + goto loser; } - key->data = (unsigned char*)PORT_ArenaAlloc(arena, len); - if ( !key->data ) { - goto loser; + key->data = (unsigned char *)PORT_ArenaAlloc(arena, len); + if (!key->data) { + goto loser; } key->len = len; @@ -370,21 +385,21 @@ nsslowcert_KeyFromIssuerAndSN(PLArenaPool *arena, /* copy the issuer */ PORT_Memcpy(&key->data[sn->len], issuer->data, issuer->len); - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus nsslowcert_KeyFromIssuerAndSNStatic(unsigned char *space, - int spaceLen, SECItem *issuer, SECItem *sn, SECItem *key) + int spaceLen, SECItem *issuer, SECItem *sn, SECItem *key) { unsigned int len = sn->len + issuer->len; key->data = pkcs11_allocStaticData(len, space, spaceLen); - if ( !key->data ) { - goto loser; + if (!key->data) { + goto loser; } key->len = len; @@ -394,13 +409,12 @@ nsslowcert_KeyFromIssuerAndSNStatic(unsigned char *space, /* copy the issuer */ PORT_Memcpy(&key->data[sn->len], issuer->data, issuer->len); - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } - static char * nsslowcert_EmailName(SECItem *derDN, char *space, unsigned int len) { @@ -408,161 +422,178 @@ nsslowcert_EmailName(SECItem *derDN, char *space, unsigned int len) unsigned int buf_length; /* unwrap outer sequence */ - buf=nsslowcert_dataStart(derDN->data,derDN->len,&buf_length,PR_FALSE,NULL); - if (buf == NULL) return NULL; + buf = nsslowcert_dataStart(derDN->data, derDN->len, &buf_length, PR_FALSE, NULL); + if (buf == NULL) + return NULL; /* Walk each RDN */ while (buf_length > 0) { - unsigned char *rdn; - unsigned int rdn_length; - - /* grab next rdn */ - rdn=nsslowcert_dataStart(buf, buf_length, &rdn_length, PR_FALSE, NULL); - if (rdn == NULL) { return NULL; } - buf_length -= (rdn - buf) + rdn_length; - buf = rdn+rdn_length; - - while (rdn_length > 0) { - unsigned char *ava; - unsigned int ava_length; - unsigned char *oid; - unsigned int oid_length; - unsigned char *name; - unsigned int name_length; - SECItem oidItem; - SECOidTag type; - - /* unwrap the ava */ - ava=nsslowcert_dataStart(rdn, rdn_length, &ava_length, PR_FALSE, - NULL); - if (ava == NULL) return NULL; - rdn_length -= (ava-rdn)+ava_length; - rdn = ava + ava_length; - - oid=nsslowcert_dataStart(ava, ava_length, &oid_length, PR_FALSE, - NULL); - if (oid == NULL) { return NULL; } - ava_length -= (oid-ava)+oid_length; - ava = oid+oid_length; - - name=nsslowcert_dataStart(ava, ava_length, &name_length, PR_FALSE, - NULL); - if (name == NULL) { return NULL; } - ava_length -= (name-ava)+name_length; - ava = name+name_length; - - oidItem.data = oid; - oidItem.len = oid_length; - type = SECOID_FindOIDTag(&oidItem); - if ((type == SEC_OID_PKCS9_EMAIL_ADDRESS) || - (type == SEC_OID_RFC1274_MAIL)) { - /* Email is supposed to be IA5String, so no - * translation necessary */ - char *emailAddr; - emailAddr = (char *)pkcs11_copyStaticData(name,name_length+1, - (unsigned char *)space,len); - if (emailAddr) { - emailAddr[name_length] = 0; - } - return emailAddr; - } - } + unsigned char *rdn; + unsigned int rdn_length; + + /* grab next rdn */ + rdn = nsslowcert_dataStart(buf, buf_length, &rdn_length, PR_FALSE, NULL); + if (rdn == NULL) { + return NULL; + } + buf_length -= (rdn - buf) + rdn_length; + buf = rdn + rdn_length; + + while (rdn_length > 0) { + unsigned char *ava; + unsigned int ava_length; + unsigned char *oid; + unsigned int oid_length; + unsigned char *name; + unsigned int name_length; + SECItem oidItem; + SECOidTag type; + + /* unwrap the ava */ + ava = nsslowcert_dataStart(rdn, rdn_length, &ava_length, PR_FALSE, + NULL); + if (ava == NULL) + return NULL; + rdn_length -= (ava - rdn) + ava_length; + rdn = ava + ava_length; + + oid = nsslowcert_dataStart(ava, ava_length, &oid_length, PR_FALSE, + NULL); + if (oid == NULL) { + return NULL; + } + ava_length -= (oid - ava) + oid_length; + ava = oid + oid_length; + + name = nsslowcert_dataStart(ava, ava_length, &name_length, PR_FALSE, + NULL); + if (name == NULL) { + return NULL; + } + ava_length -= (name - ava) + name_length; + ava = name + name_length; + + oidItem.data = oid; + oidItem.len = oid_length; + type = SECOID_FindOIDTag(&oidItem); + if ((type == SEC_OID_PKCS9_EMAIL_ADDRESS) || + (type == SEC_OID_RFC1274_MAIL)) { + /* Email is supposed to be IA5String, so no + * translation necessary */ + char *emailAddr; + emailAddr = (char *)pkcs11_copyStaticData(name, name_length + 1, + (unsigned char *)space, len); + if (emailAddr) { + emailAddr[name_length] = 0; + } + return emailAddr; + } + } } return NULL; } static char * -nsslowcert_EmailAltName(NSSLOWCERTCertificate *cert, char *space, - unsigned int len) +nsslowcert_EmailAltName(NSSLOWCERTCertificate *cert, char *space, + unsigned int len) { unsigned char *exts; unsigned int exts_length; /* unwrap the sequence */ exts = nsslowcert_dataStart(cert->extensions.data, cert->extensions.len, - &exts_length, PR_FALSE, NULL); + &exts_length, PR_FALSE, NULL); /* loop through extension */ while (exts && exts_length > 0) { - unsigned char * ext; - unsigned int ext_length; - unsigned char *oid; - unsigned int oid_length; - unsigned char *nameList; - unsigned int nameList_length; - SECItem oidItem; - SECOidTag type; - - ext = nsslowcert_dataStart(exts, exts_length, &ext_length, - PR_FALSE, NULL); - if (ext == NULL) { break; } - exts_length -= (ext - exts) + ext_length; - exts = ext+ext_length; - - oid=nsslowcert_dataStart(ext, ext_length, &oid_length, PR_FALSE, NULL); - if (oid == NULL) { break; } - ext_length -= (oid - ext) + oid_length; - ext = oid+oid_length; - oidItem.data = oid; - oidItem.len = oid_length; - type = SECOID_FindOIDTag(&oidItem); - - /* get Alt Extension */ - if (type != SEC_OID_X509_SUBJECT_ALT_NAME) { - continue; - } - - /* skip passed the critical flag */ - if (ext[0] == 0x01) { /* BOOLEAN */ - unsigned char *dummy; - unsigned int dummy_length; - dummy = nsslowcert_dataStart(ext, ext_length, &dummy_length, - PR_FALSE, NULL); - if (dummy == NULL) { break; } - ext_length -= (dummy - ext) + dummy_length; - ext = dummy+dummy_length; - } - - - /* unwrap the name list */ - nameList = nsslowcert_dataStart(ext, ext_length, &nameList_length, - PR_FALSE, NULL); - if (nameList == NULL) { break; } - ext_length -= (nameList - ext) + nameList_length; - ext = nameList+nameList_length; - nameList = nsslowcert_dataStart(nameList, nameList_length, - &nameList_length, PR_FALSE, NULL); - /* loop through the name list */ - while (nameList && nameList_length > 0) { - unsigned char *thisName; - unsigned int thisName_length; - - thisName = nsslowcert_dataStart(nameList, nameList_length, - &thisName_length, PR_FALSE, NULL); - if (thisName == NULL) { break; } - if (nameList[0] == 0xa2) { /* DNS Name */ - SECItem dn; - char *emailAddr; - - dn.data = thisName; - dn.len = thisName_length; - emailAddr = nsslowcert_EmailName(&dn, space, len); - if (emailAddr) { - return emailAddr; - } - } - if (nameList[0] == 0x81) { /* RFC 822name */ - char *emailAddr; - emailAddr = (char *)pkcs11_copyStaticData(thisName, - thisName_length+1, (unsigned char *)space,len); - if (emailAddr) { - emailAddr[thisName_length] = 0; - } - return emailAddr; - } - nameList_length -= (thisName-nameList) + thisName_length; - nameList = thisName + thisName_length; - } - break; + unsigned char *ext; + unsigned int ext_length; + unsigned char *oid; + unsigned int oid_length; + unsigned char *nameList; + unsigned int nameList_length; + SECItem oidItem; + SECOidTag type; + + ext = nsslowcert_dataStart(exts, exts_length, &ext_length, + PR_FALSE, NULL); + if (ext == NULL) { + break; + } + exts_length -= (ext - exts) + ext_length; + exts = ext + ext_length; + + oid = nsslowcert_dataStart(ext, ext_length, &oid_length, PR_FALSE, NULL); + if (oid == NULL) { + break; + } + ext_length -= (oid - ext) + oid_length; + ext = oid + oid_length; + oidItem.data = oid; + oidItem.len = oid_length; + type = SECOID_FindOIDTag(&oidItem); + + /* get Alt Extension */ + if (type != SEC_OID_X509_SUBJECT_ALT_NAME) { + continue; + } + + /* skip passed the critical flag */ + if (ext[0] == 0x01) { /* BOOLEAN */ + unsigned char *dummy; + unsigned int dummy_length; + dummy = nsslowcert_dataStart(ext, ext_length, &dummy_length, + PR_FALSE, NULL); + if (dummy == NULL) { + break; + } + ext_length -= (dummy - ext) + dummy_length; + ext = dummy + dummy_length; + } + + /* unwrap the name list */ + nameList = nsslowcert_dataStart(ext, ext_length, &nameList_length, + PR_FALSE, NULL); + if (nameList == NULL) { + break; + } + ext_length -= (nameList - ext) + nameList_length; + ext = nameList + nameList_length; + nameList = nsslowcert_dataStart(nameList, nameList_length, + &nameList_length, PR_FALSE, NULL); + /* loop through the name list */ + while (nameList && nameList_length > 0) { + unsigned char *thisName; + unsigned int thisName_length; + + thisName = nsslowcert_dataStart(nameList, nameList_length, + &thisName_length, PR_FALSE, NULL); + if (thisName == NULL) { + break; + } + if (nameList[0] == 0xa2) { /* DNS Name */ + SECItem dn; + char *emailAddr; + + dn.data = thisName; + dn.len = thisName_length; + emailAddr = nsslowcert_EmailName(&dn, space, len); + if (emailAddr) { + return emailAddr; + } + } + if (nameList[0] == 0x81) { /* RFC 822name */ + char *emailAddr; + emailAddr = (char *)pkcs11_copyStaticData(thisName, + thisName_length + 1, (unsigned char *)space, len); + if (emailAddr) { + emailAddr[thisName_length] = 0; + } + return emailAddr; + } + nameList_length -= (thisName - nameList) + thisName_length; + nameList = thisName + thisName_length; + } + break; } return NULL; } @@ -573,23 +604,21 @@ nsslowcert_GetCertificateEmailAddress(NSSLOWCERTCertificate *cert) char *emailAddr = NULL; char *str; - emailAddr = nsslowcert_EmailName(&cert->derSubject,cert->emailAddrSpace, - sizeof(cert->emailAddrSpace)); + emailAddr = nsslowcert_EmailName(&cert->derSubject, cert->emailAddrSpace, + sizeof(cert->emailAddrSpace)); /* couldn't find the email address in the DN, check the subject Alt name */ if (!emailAddr && cert->extensions.data) { - emailAddr = nsslowcert_EmailAltName(cert, cert->emailAddrSpace, - sizeof(cert->emailAddrSpace)); + emailAddr = nsslowcert_EmailAltName(cert, cert->emailAddrSpace, + sizeof(cert->emailAddrSpace)); } - /* make it lower case */ str = emailAddr; - while ( str && *str ) { - *str = tolower( *str ); - str++; + while (str && *str) { + *str = tolower(*str); + str++; } return emailAddr; - } /* @@ -603,12 +632,12 @@ nsslowcert_DecodeDERCertificate(SECItem *derSignedCert, char *nickname) /* allocate the certificate structure */ cert = nsslowcert_CreateCert(); - - if ( !cert ) { - goto loser; + + if (!cert) { + goto loser; } - - /* point to passed in DER data */ + + /* point to passed in DER data */ cert->derCert = *derSignedCert; cert->nickname = NULL; cert->certKey.data = NULL; @@ -616,59 +645,58 @@ nsslowcert_DecodeDERCertificate(SECItem *derSignedCert, char *nickname) /* decode the certificate info */ rv = nsslowcert_GetCertFields(cert->derCert.data, cert->derCert.len, - &cert->derIssuer, &cert->serialNumber, &cert->derSN, &cert->derSubject, - &cert->validity, &cert->derSubjKeyInfo, &cert->extensions); + &cert->derIssuer, &cert->serialNumber, &cert->derSN, &cert->derSubject, + &cert->validity, &cert->derSubjKeyInfo, &cert->extensions); if (rv != SECSuccess) { - goto loser; + goto loser; } - /* cert->subjectKeyID; x509v3 subject key identifier */ + /* cert->subjectKeyID; x509v3 subject key identifier */ cert->subjectKeyID.data = NULL; cert->subjectKeyID.len = 0; cert->dbEntry = NULL; - cert ->trust = NULL; - cert ->dbhandle = NULL; + cert->trust = NULL; + cert->dbhandle = NULL; /* generate and save the database key for the cert */ rv = nsslowcert_KeyFromIssuerAndSNStatic(cert->certKeySpace, - sizeof(cert->certKeySpace), &cert->derIssuer, - &cert->serialNumber, &cert->certKey); - if ( rv ) { - goto loser; + sizeof(cert->certKeySpace), &cert->derIssuer, + &cert->serialNumber, &cert->certKey); + if (rv) { + goto loser; } /* set the nickname */ - if ( nickname == NULL ) { - cert->nickname = NULL; + if (nickname == NULL) { + cert->nickname = NULL; } else { - /* copy and install the nickname */ - cert->nickname = pkcs11_copyNickname(nickname,cert->nicknameSpace, - sizeof(cert->nicknameSpace)); + /* copy and install the nickname */ + cert->nickname = pkcs11_copyNickname(nickname, cert->nicknameSpace, + sizeof(cert->nicknameSpace)); } #ifdef FIXME /* initialize the subjectKeyID */ rv = cert_GetKeyID(cert); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } #endif /* set the email address */ cert->emailAddr = nsslowcert_GetCertificateEmailAddress(cert); - - + cert->referenceCount = 1; - - return(cert); - + + return (cert); + loser: if (cert) { - nsslowcert_DestroyCertificate(cert); + nsslowcert_DestroyCertificate(cert); } - - return(0); + + return (0); } char * @@ -677,25 +705,24 @@ nsslowcert_FixupEmailAddr(char *emailAddr) char *retaddr; char *str; - if ( emailAddr == NULL ) { - return(NULL); + if (emailAddr == NULL) { + return (NULL); } - + /* copy the string */ str = retaddr = PORT_Strdup(emailAddr); - if ( str == NULL ) { - return(NULL); + if (str == NULL) { + return (NULL); } - + /* make it lower case */ - while ( *str ) { - *str = tolower( *str ); - str++; + while (*str) { + *str = tolower(*str); + str++; } - - return(retaddr); -} + return (retaddr); +} /* * Generate a database key, based on serial number and issuer, from a @@ -707,20 +734,20 @@ nsslowcert_KeyFromDERCert(PLArenaPool *arena, SECItem *derCert, SECItem *key) int rv; NSSLOWCERTCertKey certkey; - PORT_Memset(&certkey, 0, sizeof(NSSLOWCERTCertKey)); + PORT_Memset(&certkey, 0, sizeof(NSSLOWCERTCertKey)); rv = nsslowcert_GetCertFields(derCert->data, derCert->len, - &certkey.derIssuer, &certkey.serialNumber, NULL, NULL, - NULL, NULL, NULL); + &certkey.derIssuer, &certkey.serialNumber, NULL, NULL, + NULL, NULL, NULL); - if ( rv ) { - goto loser; + if (rv) { + goto loser; } - return(nsslowcert_KeyFromIssuerAndSN(arena, &certkey.derIssuer, - &certkey.serialNumber, key)); + return (nsslowcert_KeyFromIssuerAndSN(arena, &certkey.derIssuer, + &certkey.serialNumber, key)); loser: - return(SECFailure); + return (SECFailure); } NSSLOWKEYPublicKey * @@ -734,93 +761,96 @@ nsslowcert_ExtractPublicKey(NSSLOWCERTCertificate *cert) SECOidTag tag; SECItem newDerSubjKeyInfo; - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) return NULL; - pubk = (NSSLOWKEYPublicKey *) - PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPublicKey)); + pubk = (NSSLOWKEYPublicKey *) + PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPublicKey)); if (pubk == NULL) { - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } pubk->arena = arena; - PORT_Memset(&spki,0,sizeof(spki)); + PORT_Memset(&spki, 0, sizeof(spki)); /* copy the DER into the arena, since Quick DER returns data that points into the DER input, which may get freed by the caller */ rv = SECITEM_CopyItem(arena, &newDerSubjKeyInfo, &cert->derSubjKeyInfo); - if ( rv != SECSuccess ) { - PORT_FreeArena (arena, PR_FALSE); + if (rv != SECSuccess) { + PORT_FreeArena(arena, PR_FALSE); return NULL; } /* we haven't bothered decoding the spki struct yet, do it now */ - rv = SEC_QuickDERDecodeItem(arena, &spki, - nsslowcert_SubjectPublicKeyInfoTemplate, &newDerSubjKeyInfo); + rv = SEC_QuickDERDecodeItem(arena, &spki, + nsslowcert_SubjectPublicKeyInfoTemplate, &newDerSubjKeyInfo); if (rv != SECSuccess) { - PORT_FreeArena (arena, PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } /* Convert bit string length from bits to bytes */ os = spki.subjectPublicKey; - DER_ConvertBitString (&os); + DER_ConvertBitString(&os); tag = SECOID_GetAlgorithmTag(&spki.algorithm); - switch ( tag ) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - pubk->keyType = NSSLOWKEYRSAKey; - prepare_low_rsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_RSAPublicKeyTemplate, &os); - if (rv == SECSuccess) - return pubk; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - pubk->keyType = NSSLOWKEYDSAKey; - prepare_low_dsa_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_DSAPublicKeyTemplate, &os); - if (rv == SECSuccess) return pubk; - break; - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - pubk->keyType = NSSLOWKEYDHKey; - prepare_low_dh_pub_key_for_asn1(pubk); - rv = SEC_QuickDERDecodeItem(arena, pubk, - nsslowcert_DHPublicKeyTemplate, &os); - if (rv == SECSuccess) return pubk; - break; + switch (tag) { + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + pubk->keyType = NSSLOWKEYRSAKey; + prepare_low_rsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, + nsslowcert_RSAPublicKeyTemplate, &os); + if (rv == SECSuccess) + return pubk; + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: + pubk->keyType = NSSLOWKEYDSAKey; + prepare_low_dsa_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, + nsslowcert_DSAPublicKeyTemplate, &os); + if (rv == SECSuccess) + return pubk; + break; + case SEC_OID_X942_DIFFIE_HELMAN_KEY: + pubk->keyType = NSSLOWKEYDHKey; + prepare_low_dh_pub_key_for_asn1(pubk); + rv = SEC_QuickDERDecodeItem(arena, pubk, + nsslowcert_DHPublicKeyTemplate, &os); + if (rv == SECSuccess) + return pubk; + break; #ifndef NSS_DISABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - pubk->keyType = NSSLOWKEYECKey; - /* Since PKCS#11 directly takes the DER encoding of EC params - * and public value, we don't need any decoding here. - */ - rv = SECITEM_CopyItem(arena, &pubk->u.ec.ecParams.DEREncoding, - &spki.algorithm.parameters); - if ( rv != SECSuccess ) - break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (LGEC_FillParams(arena, &pubk->u.ec.ecParams.DEREncoding, - &pubk->u.ec.ecParams) != SECSuccess) - break; - - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &os); - if (rv == SECSuccess) return pubk; - break; + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + pubk->keyType = NSSLOWKEYECKey; + /* Since PKCS#11 directly takes the DER encoding of EC params + * and public value, we don't need any decoding here. + */ + rv = SECITEM_CopyItem(arena, &pubk->u.ec.ecParams.DEREncoding, + &spki.algorithm.parameters); + if (rv != SECSuccess) + break; + + /* Fill out the rest of the ecParams structure + * based on the encoded params + */ + if (LGEC_FillParams(arena, &pubk->u.ec.ecParams.DEREncoding, + &pubk->u.ec.ecParams) != SECSuccess) + break; + + rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &os); + if (rv == SECSuccess) + return pubk; + break; #endif /* NSS_DISABLE_ECC */ - default: - rv = SECFailure; - break; + default: + rv = SECFailure; + break; } - lg_nsslowkey_DestroyPublicKey (pubk); + lg_nsslowkey_DestroyPublicKey(pubk); return NULL; } - diff --git a/nss/lib/softoken/legacydb/lowkey.c b/nss/lib/softoken/legacydb/lowkey.c index 7521dac..7de4197 100644 --- a/nss/lib/softoken/legacydb/lowkey.c +++ b/nss/lib/softoken/legacydb/lowkey.c @@ -1,12 +1,12 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "lowkeyi.h" -#include "secoid.h" +#include "lowkeyi.h" +#include "secoid.h" #include "secitem.h" -#include "secder.h" +#include "secder.h" #include "secasn1.h" -#include "secerr.h" +#include "secerr.h" SEC_ASN1_MKSUB(SEC_AnyTemplate) SEC_ASN1_MKSUB(SEC_BitStringTemplate) @@ -14,11 +14,11 @@ SEC_ASN1_MKSUB(SEC_ObjectIDTemplate) SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) static const SEC_ASN1Template nsslowkey_AttributeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYAttribute) }, + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(NSSLOWKEYAttribute) }, { SEC_ASN1_OBJECT_ID, offsetof(NSSLOWKEYAttribute, attrType) }, - { SEC_ASN1_SET_OF | SEC_ASN1_XTRN, offsetof(NSSLOWKEYAttribute, attrValue), - SEC_ASN1_SUB(SEC_AnyTemplate) }, + { SEC_ASN1_SET_OF | SEC_ASN1_XTRN, offsetof(NSSLOWKEYAttribute, attrValue), + SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; @@ -28,41 +28,41 @@ static const SEC_ASN1Template nsslowkey_SetOfAttributeTemplate[] = { /* ASN1 Templates for new decoder/encoder */ const SEC_ASN1Template lg_nsslowkey_PrivateKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYPrivateKeyInfo) }, + 0, NULL, sizeof(NSSLOWKEYPrivateKeyInfo) }, { SEC_ASN1_INTEGER, - offsetof(NSSLOWKEYPrivateKeyInfo,version) }, + offsetof(NSSLOWKEYPrivateKeyInfo, version) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(NSSLOWKEYPrivateKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(NSSLOWKEYPrivateKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKeyInfo,privateKey) }, + offsetof(NSSLOWKEYPrivateKeyInfo, privateKey) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKeyInfo, attributes), - nsslowkey_SetOfAttributeTemplate }, + offsetof(NSSLOWKEYPrivateKeyInfo, attributes), + nsslowkey_SetOfAttributeTemplate }, { 0 } }; const SEC_ASN1Template lg_nsslowkey_PQGParamsTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(PQGParams, prime) }, + { SEC_ASN1_INTEGER, offsetof(PQGParams, subPrime) }, + { SEC_ASN1_INTEGER, offsetof(PQGParams, base) }, + { 0 } }; const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.version) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) }, - { 0 } -}; + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.version) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.publicExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.privateExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.coefficient) }, + { 0 } +}; /* * Allows u.rsa.modulus to be zero length for secret keys with an empty @@ -71,49 +71,36 @@ const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate[] = { */ const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate2[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.version) }, - { SEC_ASN1_ANY, offsetof(NSSLOWKEYPrivateKey,u.rsa.modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.version) }, + { SEC_ASN1_ANY, offsetof(NSSLOWKEYPrivateKey, u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.publicExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.privateExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.coefficient) }, { 0 } }; const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dsa.publicValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dsa.privateValue) }, + { 0 } }; const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.privateValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.base) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.prime) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.publicValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.privateValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.base) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.prime) }, + { 0 } }; #ifndef NSS_DISABLE_ECC -/* XXX This is just a placeholder for later when we support - * generic curves and need full-blown support for parsing EC - * parameters. For now, we only support named curves in which - * EC params are simply encoded as an object ID and we don't - * use lg_nsslowkey_ECParamsTemplate. - */ -const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[] = { - { SEC_ASN1_CHOICE, offsetof(ECParams,type), NULL, sizeof(ECParams) }, - { SEC_ASN1_OBJECT_ID, offsetof(ECParams,curveOID), NULL, ec_params_named }, - { 0, } -}; - - /* NOTE: The SECG specification allows the private key structure * to contain curve parameters but recommends that they be stored * in the PrivateKeyAlgorithmIdentifier field of the PrivateKeyInfo @@ -121,51 +108,41 @@ const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[] = { */ const SEC_ASN1Template lg_nsslowkey_ECPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.ec.version) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKey,u.ec.privateValue) }, - /* XXX The following template works for now since we only - * support named curves for which the parameters are - * encoded as an object ID. When we support generic curves, - * we'll need to define lg_nsslowkey_ECParamsTemplate + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.ec.version) }, + { SEC_ASN1_OCTET_STRING, + offsetof(NSSLOWKEYPrivateKey, u.ec.privateValue) }, + /* We only support named curves for which the parameters are + * encoded as an object ID. */ -#if 1 { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams.curveOID), - SEC_ASN1_SUB(SEC_ObjectIDTemplate) }, -#else - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams), - lg_nsslowkey_ECParamsTemplate }, -#endif + SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0, + offsetof(NSSLOWKEYPrivateKey, u.ec.ecParams.curveOID), + SEC_ASN1_SUB(SEC_ObjectIDTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 1, - offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { 0, } + SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 1, + offsetof(NSSLOWKEYPrivateKey, u.ec.publicValue), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { 0 } }; - /* * smaller version of EC_FillParams. In this code, we only need * oid and DER data. */ SECStatus LGEC_FillParams(PLArenaPool *arena, const SECItem *encodedParams, - ECParams *params) + ECParams *params) { SECOidTag tag; - SECItem oid = { siBuffer, NULL, 0}; + SECItem oid = { siBuffer, NULL, 0 }; #if EC_DEBUG int i; printf("Encoded params in EC_DecodeParams: "); for (i = 0; i < encodedParams->len; i++) { - printf("%02x:", encodedParams->data[i]); + printf("%02x:", encodedParams->data[i]); } printf("\n"); #endif @@ -173,18 +150,18 @@ LGEC_FillParams(PLArenaPool *arena, const SECItem *encodedParams, oid.len = encodedParams->len - 2; oid.data = encodedParams->data + 2; if ((encodedParams->data[0] != SEC_ASN1_OBJECT_ID) || - ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN)) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - return SECFailure; + ((tag = SECOID_FindOIDTag(&oid)) == SEC_OID_UNKNOWN)) { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return SECFailure; } params->arena = arena; /* For named curves, fill out curveOID */ params->curveOID.len = oid.len; - params->curveOID.data = (unsigned char *) PORT_ArenaAlloc(arena, oid.len); - if (params->curveOID.data == NULL) { - return SECFailure; + params->curveOID.data = (unsigned char *)PORT_ArenaAlloc(arena, oid.len); + if (params->curveOID.data == NULL) { + return SECFailure; } memcpy(params->curveOID.data, oid.data, oid.len); @@ -195,20 +172,20 @@ LGEC_FillParams(PLArenaPool *arena, const SECItem *encodedParams, */ SECStatus LGEC_CopyParams(PLArenaPool *arena, ECParams *dstParams, - const ECParams *srcParams) + const ECParams *srcParams) { SECStatus rv = SECFailure; dstParams->arena = arena; rv = SECITEM_CopyItem(arena, &dstParams->DEREncoding, - &srcParams->DEREncoding); + &srcParams->DEREncoding); if (rv != SECSuccess) { - goto loser; + goto loser; } - rv =SECITEM_CopyItem(arena, &dstParams->curveOID, - &srcParams->curveOID); + rv = SECITEM_CopyItem(arena, &dstParams->curveOID, + &srcParams->curveOID); if (rv != SECSuccess) { - goto loser; + goto loser; } return SECSuccess; @@ -289,7 +266,7 @@ void lg_nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *privk) { if (privk && privk->arena) { - PORT_FreeArena(privk->arena, PR_TRUE); + PORT_FreeArena(privk->arena, PR_TRUE); } } @@ -297,7 +274,7 @@ void lg_nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *pubk) { if (pubk && pubk->arena) { - PORT_FreeArena(pubk->arena, PR_FALSE); + PORT_FreeArena(pubk->arena, PR_FALSE); } } @@ -307,104 +284,112 @@ lg_nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privk) NSSLOWKEYPublicKey *pubk; PLArenaPool *arena; - - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); + PORT_SetError(SEC_ERROR_NO_MEMORY); return NULL; } - switch(privk->keyType) { - case NSSLOWKEYRSAKey: - case NSSLOWKEYNullKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof (NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - if (privk->keyType == NSSLOWKEYNullKey) return pubk; - rv = SECITEM_CopyItem(arena, &pubk->u.rsa.modulus, - &privk->u.rsa.modulus); - if (rv == SECSuccess) { - rv = SECITEM_CopyItem (arena, &pubk->u.rsa.publicExponent, - &privk->u.rsa.publicExponent); - if (rv == SECSuccess) - return pubk; - } - } else { - PORT_SetError (SEC_ERROR_NO_MEMORY); - } - break; - case NSSLOWKEYDSAKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.publicValue, - &privk->u.dsa.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime, - &privk->u.dsa.params.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime, - &privk->u.dsa.params.subPrime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base, - &privk->u.dsa.params.base); - if (rv == SECSuccess) return pubk; - } - break; - case NSSLOWKEYDHKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.publicValue, - &privk->u.dh.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime, - &privk->u.dh.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.base, - &privk->u.dh.base); - if (rv == SECSuccess) return pubk; - } - break; + switch (privk->keyType) { + case NSSLOWKEYRSAKey: + case NSSLOWKEYNullKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + if (privk->keyType == NSSLOWKEYNullKey) + return pubk; + rv = SECITEM_CopyItem(arena, &pubk->u.rsa.modulus, + &privk->u.rsa.modulus); + if (rv == SECSuccess) { + rv = SECITEM_CopyItem(arena, &pubk->u.rsa.publicExponent, + &privk->u.rsa.publicExponent); + if (rv == SECSuccess) + return pubk; + } + } else { + PORT_SetError(SEC_ERROR_NO_MEMORY); + } + break; + case NSSLOWKEYDSAKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.publicValue, + &privk->u.dsa.publicValue); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime, + &privk->u.dsa.params.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime, + &privk->u.dsa.params.subPrime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base, + &privk->u.dsa.params.base); + if (rv == SECSuccess) + return pubk; + } + break; + case NSSLOWKEYDHKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.publicValue, + &privk->u.dh.publicValue); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime, + &privk->u.dh.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.base, + &privk->u.dh.base); + if (rv == SECSuccess) + return pubk; + } + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, - &privk->u.ec.publicValue); - if (rv != SECSuccess) break; - pubk->u.ec.ecParams.arena = arena; - /* Copy the rest of the params */ - rv = LGEC_CopyParams(arena, &(pubk->u.ec.ecParams), - &(privk->u.ec.ecParams)); - if (rv == SECSuccess) return pubk; - } - break; + case NSSLOWKEYECKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, + &privk->u.ec.publicValue); + if (rv != SECSuccess) + break; + pubk->u.ec.ecParams.arena = arena; + /* Copy the rest of the params */ + rv = LGEC_CopyParams(arena, &(pubk->u.ec.ecParams), + &(privk->u.ec.ecParams)); + if (rv == SECSuccess) + return pubk; + } + break; #endif /* NSS_DISABLE_ECC */ - /* No Fortezza in Low Key implementations (Fortezza keys aren't - * stored in our data base */ - default: - break; + /* No Fortezza in Low Key implementations (Fortezza keys aren't + * stored in our data base */ + default: + break; } - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } - diff --git a/nss/lib/softoken/legacydb/lowkeyi.h b/nss/lib/softoken/legacydb/lowkeyi.h index 6739888..5136b56 100644 --- a/nss/lib/softoken/legacydb/lowkeyi.h +++ b/nss/lib/softoken/legacydb/lowkeyi.h @@ -10,7 +10,7 @@ #include "secoidt.h" #include "pcertt.h" #include "lowkeyti.h" -#include "sdb.h" +#include "sdb.h" SEC_BEGIN_PROTOS @@ -31,16 +31,16 @@ extern void lg_prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key); extern void lg_prepare_low_ecparams_for_asn1(ECParams *params); #endif /* NSS_DISABLE_ECC */ -typedef char * (* NSSLOWKEYDBNameFunc)(void *arg, int dbVersion); - +typedef char *(*NSSLOWKEYDBNameFunc)(void *arg, int dbVersion); + /* ** Open a key database. */ extern NSSLOWKEYDBHandle *nsslowkey_OpenKeyDB(PRBool readOnly, - const char *domain, - const char *prefix, - NSSLOWKEYDBNameFunc namecb, - void *cbarg); + const char *domain, + const char *prefix, + NSSLOWKEYDBNameFunc namecb, + void *cbarg); /* ** Close the specified key database. @@ -55,55 +55,54 @@ extern int nsslowkey_GetKeyDBVersion(NSSLOWKEYDBHandle *handle); /* ** Delete a key from the database */ -extern SECStatus nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, - const SECItem *pubkey); +extern SECStatus nsslowkey_DeleteKey(NSSLOWKEYDBHandle *handle, + const SECItem *pubkey); /* ** Store a key in the database, indexed by its public key modulus. -** "pk" is the private key to store -** "f" is the callback function for getting the password -** "arg" is the argument for the callback +** "pk" is the private key to store +** "f" is the callback function for getting the password +** "arg" is the argument for the callback */ -extern SECStatus nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *pk, - SECItem *pubKeyData, - char *nickname, - SDB *sdb); +extern SECStatus nsslowkey_StoreKeyByPublicKey(NSSLOWKEYDBHandle *handle, + NSSLOWKEYPrivateKey *pk, + SECItem *pubKeyData, + char *nickname, + SDB *sdb); /* does the key for this cert exist in the database filed by modulus */ extern PRBool nsslowkey_KeyForCertExists(NSSLOWKEYDBHandle *handle, - NSSLOWCERTCertificate *cert); + NSSLOWCERTCertificate *cert); /* does a key with this ID already exist? */ extern PRBool nsslowkey_KeyForIDExists(NSSLOWKEYDBHandle *handle, SECItem *id); /* ** Destroy a private key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects +** "key" the object +** "freeit" if PR_TRUE then free the object as well as its sub-objects */ extern void lg_nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *key); /* ** Destroy a public key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects +** "key" the object +** "freeit" if PR_TRUE then free the object as well as its sub-objects */ extern void lg_nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *key); - /* ** Convert a low private key "privateKey" into a public low key */ -extern NSSLOWKEYPublicKey - *lg_nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privateKey); - +extern NSSLOWKEYPublicKey + * + lg_nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privateKey); SECStatus nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SDB *sdb); + NSSLOWKEYPrivateKey *privkey, + SECItem *pubKeyData, + char *nickname, + SDB *sdb); /* Store key by modulus and specify an encryption algorithm to use. * handle is the pointer to the key database, @@ -113,27 +112,27 @@ nsslowkey_UpdateNickname(NSSLOWKEYDBHandle *handle, * algorithm is the algorithm which the privKey is to be stored. * A return of anything but SECSuccess indicates failure. */ -extern SECStatus -nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, - NSSLOWKEYPrivateKey *privkey, - SECItem *pubKeyData, - char *nickname, - SDB *sdb, - PRBool update); +extern SECStatus +nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWKEYDBHandle *handle, + NSSLOWKEYPrivateKey *privkey, + SECItem *pubKeyData, + char *nickname, + SDB *sdb, + PRBool update); /* Find key by modulus. This function is the inverse of store key - * by modulus. An attempt to locate the key with "modulus" is + * by modulus. An attempt to locate the key with "modulus" is * performed. If the key is found, the private key is returned, * else NULL is returned. * modulus is the modulus to locate */ extern NSSLOWKEYPrivateKey * -nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, - SDB *sdb); +nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, + SDB *sdb); extern char * nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, - SECItem *modulus, SDB *sdb); + SECItem *modulus, SDB *sdb); #ifndef NSS_DISABLE_ECC /* @@ -141,11 +140,11 @@ nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle, * oid and DER data. */ SECStatus LGEC_FillParams(PLArenaPool *arena, const SECItem *encodedParams, - ECParams *params); + ECParams *params); /* Copy all of the fields from srcParams into dstParams */ SECStatus LGEC_CopyParams(PLArenaPool *arena, ECParams *dstParams, - const ECParams *srcParams); + const ECParams *srcParams); #endif SEC_END_PROTOS diff --git a/nss/lib/softoken/legacydb/lowkeyti.h b/nss/lib/softoken/legacydb/lowkeyti.h index 47fff7d..ef92689 100644 --- a/nss/lib/softoken/legacydb/lowkeyti.h +++ b/nss/lib/softoken/legacydb/lowkeyti.h @@ -11,7 +11,6 @@ #include "secasn1t.h" #include "secoidt.h" - /* * a key in/for the data base */ @@ -32,7 +31,7 @@ typedef struct NSSLOWKEYDBHandleStr NSSLOWKEYDBHandle; #define NSSLOWKEY_DB_FILE_VERSION 3 #endif -#define NSSLOWKEY_VERSION 0 /* what we *create* */ +#define NSSLOWKEY_VERSION 0 /* what we *create* */ /* ** Typedef for callback to get a password "key". @@ -44,8 +43,7 @@ extern const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[]; extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[]; extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyExportTemplate[]; #ifndef NSS_DISABLE_ECC -#define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */ -extern const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[]; +#define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */ extern const SEC_ASN1Template lg_nsslowkey_ECPrivateKeyTemplate[]; #endif /* NSS_DISABLE_ECC */ @@ -72,7 +70,7 @@ struct NSSLOWKEYPrivateKeyInfoStr { NSSLOWKEYAttribute **attributes; }; typedef struct NSSLOWKEYPrivateKeyInfoStr NSSLOWKEYPrivateKeyInfo; -#define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */ +#define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */ /* ** A PKCS#8 private key info object @@ -84,11 +82,10 @@ struct NSSLOWKEYEncryptedPrivateKeyInfoStr { }; typedef struct NSSLOWKEYEncryptedPrivateKeyInfoStr NSSLOWKEYEncryptedPrivateKeyInfo; - -typedef enum { - NSSLOWKEYNullKey = 0, - NSSLOWKEYRSAKey = 1, - NSSLOWKEYDSAKey = 2, +typedef enum { + NSSLOWKEYNullKey = 0, + NSSLOWKEYRSAKey = 1, + NSSLOWKEYDSAKey = 2, NSSLOWKEYDHKey = 4, NSSLOWKEYECKey = 5 } NSSLOWKEYType; @@ -98,12 +95,12 @@ typedef enum { */ struct NSSLOWKEYPublicKeyStr { PLArenaPool *arena; - NSSLOWKEYType keyType ; + NSSLOWKEYType keyType; union { RSAPublicKey rsa; - DSAPublicKey dsa; - DHPublicKey dh; - ECPublicKey ec; + DSAPublicKey dsa; + DHPublicKey dh; + ECPublicKey ec; } u; }; typedef struct NSSLOWKEYPublicKeyStr NSSLOWKEYPublicKey; @@ -118,14 +115,13 @@ struct NSSLOWKEYPrivateKeyStr { NSSLOWKEYType keyType; union { RSAPrivateKey rsa; - DSAPrivateKey dsa; - DHPrivateKey dh; - ECPrivateKey ec; + DSAPrivateKey dsa; + DHPrivateKey dh; + ECPrivateKey ec; } u; }; typedef struct NSSLOWKEYPrivateKeyStr NSSLOWKEYPrivateKey; - typedef struct NSSLOWKEYPasswordEntryStr NSSLOWKEYPasswordEntry; struct NSSLOWKEYPasswordEntryStr { SECItem salt; @@ -133,5 +129,4 @@ struct NSSLOWKEYPasswordEntryStr { unsigned char data[128]; }; - -#endif /* _LOWKEYTI_H_ */ +#endif /* _LOWKEYTI_H_ */ diff --git a/nss/lib/softoken/legacydb/manifest.mn b/nss/lib/softoken/legacydb/manifest.mn index b0d3eef..9cce849 100644 --- a/nss/lib/softoken/legacydb/manifest.mn +++ b/nss/lib/softoken/legacydb/manifest.mn @@ -1,4 +1,4 @@ -# +# # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. @@ -6,13 +6,13 @@ CORE_DEPTH = ../../.. MODULE = nss -REQUIRES = dbm +REQUIRES = dbm LIBRARY_NAME = nssdbm LIBRARY_VERSION = 3 MAPFILE = $(OBJDIR)/nssdbm.def -DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\" +DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\" -DLG_LIB_NAME=\"$(notdir $(SHARED_LIBRARY))\" CSRCS = \ dbmshim.c \ @@ -21,6 +21,7 @@ CSRCS = \ lgcreate.c \ lgdestroy.c \ lgfind.c \ + lgfips.c \ lginit.c \ lgutil.c \ lowcert.c \ diff --git a/nss/lib/softoken/legacydb/nssdbm.def b/nss/lib/softoken/legacydb/nssdbm.def index e4dc6f2..dd6d5fa 100644 --- a/nss/lib/softoken/legacydb/nssdbm.def +++ b/nss/lib/softoken/legacydb/nssdbm.def @@ -5,13 +5,13 @@ ;+# ;+# OK, this file is meant to support SUN, LINUX, AIX and WINDOWS ;+# 1. For all unix platforms, the string ";-" means "remove this line" -;+# 2. For all unix platforms, the string " DATA " will be removed from any +;+# 2. For all unix platforms, the string " DATA " will be removed from any ;+# line on which it occurs. ;+# 3. Lines containing ";+" will have ";+" removed on SUN and LINUX. -;+# On AIX, lines containing ";+" will be removed. +;+# On AIX, lines containing ";+" will be removed. ;+# 4. For all unix platforms, the string ";;" will thave the ";;" removed. ;+# 5. For all unix platforms, after the above processing has taken place, -;+# all characters after the first ";" on the line will be removed. +;+# all characters after the first ";" on the line will be removed. ;+# And for AIX, the first ";" will also be removed. ;+# This file is passed directly to windows. Since ';' is a comment, all UNIX ;+# directives are hidden behind ";", ";+", and ";-" diff --git a/nss/lib/softoken/legacydb/pcert.h b/nss/lib/softoken/legacydb/pcert.h index 9d23cfc..d4be3f9 100644 --- a/nss/lib/softoken/legacydb/pcert.h +++ b/nss/lib/softoken/legacydb/pcert.h @@ -9,7 +9,7 @@ #include "prlong.h" #include "pcertt.h" -#include "lowkeyti.h" /* for struct NSSLOWKEYPublicKeyStr */ +#include "lowkeyti.h" /* for struct NSSLOWKEYPublicKeyStr */ SEC_BEGIN_PROTOS @@ -20,51 +20,51 @@ SECStatus nsslowcert_InitLocks(void); /* ** Add a DER encoded certificate to the permanent database. -** "derCert" is the DER encoded certificate. -** "nickname" is the nickname to use for the cert -** "trust" is the trust parameters for the cert +** "derCert" is the DER encoded certificate. +** "nickname" is the nickname to use for the cert +** "trust" is the trust parameters for the cert */ -SECStatus nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, - char *nickname, NSSLOWCERTCertTrust *trust); +SECStatus nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *handle, + NSSLOWCERTCertificate *cert, + char *nickname, NSSLOWCERTCertTrust *trust); SECStatus nsslowcert_AddPermNickname(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname); + NSSLOWCERTCertificate *cert, char *nickname); SECStatus nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert); -typedef SECStatus (PR_CALLBACK * PermCertCallback)(NSSLOWCERTCertificate *cert, - SECItem *k, void *pdata); +typedef SECStatus(PR_CALLBACK *PermCertCallback)(NSSLOWCERTCertificate *cert, + SECItem *k, void *pdata); /* ** Traverse the entire permanent database, and pass the certs off to a ** user supplied function. -** "certfunc" is the user function to call for each certificate -** "udata" is the user's data, which is passed through to "certfunc" +** "certfunc" is the user function to call for each certificate +** "udata" is the user's data, which is passed through to "certfunc" */ SECStatus nsslowcert_TraversePermCerts(NSSLOWCERTCertDBHandle *handle, - PermCertCallback certfunc, - void *udata ); + PermCertCallback certfunc, + void *udata); PRBool nsslowcert_CertDBKeyConflict(SECItem *derCert, NSSLOWCERTCertDBHandle *handle); certDBEntryRevocation * nsslowcert_FindCrlByKey(NSSLOWCERTCertDBHandle *handle, - SECItem *crlKey, PRBool isKRL); + SECItem *crlKey, PRBool isKRL); SECStatus -nsslowcert_DeletePermCRL(NSSLOWCERTCertDBHandle *handle,const SECItem *derName, - PRBool isKRL); +nsslowcert_DeletePermCRL(NSSLOWCERTCertDBHandle *handle, const SECItem *derName, + PRBool isKRL); SECStatus -nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl , - SECItem *derKey, char *url, PRBool isKRL); +nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, + SECItem *derKey, char *url, PRBool isKRL); NSSLOWCERTCertDBHandle *nsslowcert_GetDefaultCertDB(); NSSLOWKEYPublicKey *nsslowcert_ExtractPublicKey(NSSLOWCERTCertificate *); NSSLOWCERTCertificate * nsslowcert_NewTempCertificate(NSSLOWCERTCertDBHandle *handle, SECItem *derCert, - char *nickname, PRBool isperm, PRBool copyDER); + char *nickname, PRBool isperm, PRBool copyDER); NSSLOWCERTCertificate * nsslowcert_DupCertificate(NSSLOWCERTCertificate *cert); void nsslowcert_DestroyCertificate(NSSLOWCERTCertificate *cert); @@ -72,7 +72,7 @@ void nsslowcert_DestroyTrust(NSSLOWCERTTrust *Trust); /* * Lookup a certificate in the databases without locking - * "certKey" is the database key to look for + * "certKey" is the database key to look for * * XXX - this should be internal, but pkcs 11 needs to call it during a * traversal. @@ -82,7 +82,7 @@ nsslowcert_FindCertByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey) /* * Lookup trust for a certificate in the databases without locking - * "certKey" is the database key to look for + * "certKey" is the database key to look for * * XXX - this should be internal, but pkcs 11 needs to call it during a * traversal. @@ -93,22 +93,22 @@ nsslowcert_FindTrustByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey /* ** Generate a certificate key from the issuer and serialnumber, then look it ** up in the database. Return the cert if found. -** "issuerAndSN" is the issuer and serial number to look for +** "issuerAndSN" is the issuer and serial number to look for */ extern NSSLOWCERTCertificate * -nsslowcert_FindCertByIssuerAndSN (NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); +nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); /* ** Generate a certificate key from the issuer and serialnumber, then look it ** up in the database. Return the cert if found. -** "issuerAndSN" is the issuer and serial number to look for +** "issuerAndSN" is the issuer and serial number to look for */ extern NSSLOWCERTTrust * -nsslowcert_FindTrustByIssuerAndSN (NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); +nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssuerAndSN *issuerAndSN); /* ** Find a certificate in the database by a DER encoded certificate -** "derCert" is the DER encoded certificate +** "derCert" is the DER encoded certificate */ extern NSSLOWCERTCertificate * nsslowcert_FindCertByDERCert(NSSLOWCERTCertDBHandle *handle, SECItem *derCert); @@ -125,21 +125,21 @@ char *nsslowcert_FixupEmailAddr(char *emailAddr); ** then a temporary nickname is generated. */ extern NSSLOWCERTCertificate * -nsslowcert_DecodeDERCertificate (SECItem *derSignedCert, char *nickname); +nsslowcert_DecodeDERCertificate(SECItem *derSignedCert, char *nickname); SECStatus nsslowcert_KeyFromDERCert(PLArenaPool *arena, SECItem *derCert, SECItem *key); certDBEntrySMime * nsslowcert_ReadDBSMimeEntry(NSSLOWCERTCertDBHandle *certHandle, - char *emailAddr); + char *emailAddr); void nsslowcert_DestroyDBEntry(certDBEntry *entry); SECStatus nsslowcert_OpenCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *domain, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile); + const char *domain, const char *prefix, + NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile); void nsslowcert_ClosePermCertDB(NSSLOWCERTCertDBHandle *handle); @@ -150,42 +150,41 @@ nsslowcert_ClosePermCertDB(NSSLOWCERTCertDBHandle *handle); PRBool nsslowcert_IsNewer(NSSLOWCERTCertificate *certa, NSSLOWCERTCertificate *certb); - SECStatus nsslowcert_TraverseDBEntries(NSSLOWCERTCertDBHandle *handle, - certDBEntryType type, - SECStatus (* callback)(SECItem *data, SECItem *key, - certDBEntryType type, void *pdata), - void *udata ); + certDBEntryType type, + SECStatus (*callback)(SECItem *data, SECItem *key, + certDBEntryType type, void *pdata), + void *udata); SECStatus nsslowcert_TraversePermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject, - NSSLOWCERTCertCallback cb, void *cbarg); + SECItem *derSubject, + NSSLOWCERTCertCallback cb, void *cbarg); int nsslowcert_NumPermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject); + SECItem *derSubject); SECStatus nsslowcert_TraversePermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname, NSSLOWCERTCertCallback cb, void *cbarg); + char *nickname, NSSLOWCERTCertCallback cb, void *cbarg); int -nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname); +nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, + char *nickname); SECStatus nsslowcert_GetCertTrust(NSSLOWCERTCertificate *cert, - NSSLOWCERTCertTrust *trust); + NSSLOWCERTCertTrust *trust); SECStatus -nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, - SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime); +nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, + SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime); /* * Change the trust attributes of a certificate and make them permanent * in the database. */ SECStatus -nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust); +nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, + NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust); PRBool nsslowcert_needDBVerify(NSSLOWCERTCertDBHandle *handle); @@ -216,14 +215,14 @@ pkcs11_allocStaticData(int datalen, unsigned char *space, int spaceLen); unsigned char * pkcs11_copyStaticData(unsigned char *data, int datalen, unsigned char *space, - int spaceLen); + int spaceLen); NSSLOWCERTCertificate * nsslowcert_CreateCert(void); certDBEntry * -nsslowcert_DecodeAnyDBEntry(SECItem *dbData, const SECItem *dbKey, +nsslowcert_DecodeAnyDBEntry(SECItem *dbData, const SECItem *dbKey, certDBEntryType entryType, void *pdata); SEC_END_PROTOS - #endif /* _PCERTDB_H_ */ +#endif /* _PCERTDB_H_ */ diff --git a/nss/lib/softoken/legacydb/pcertdb.c b/nss/lib/softoken/legacydb/pcertdb.c index 418de0b..65da516 100644 --- a/nss/lib/softoken/legacydb/pcertdb.c +++ b/nss/lib/softoken/legacydb/pcertdb.c @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* - * Permanent Certificate database handling code + * Permanent Certificate database handling code */ #include "lowkeyti.h" #include "pcert.h" @@ -19,15 +19,15 @@ NSSLOWCERTCertificate * nsslowcert_FindCertByDERCertNoLocking(NSSLOWCERTCertDBHandle *handle, SECItem *derCert); static SECStatus -nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, - char *emailAddr, SECItem *derSubject, SECItem *emailProfile, - SECItem *profileTime); +nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, + char *emailAddr, SECItem *derSubject, SECItem *emailProfile, + SECItem *profileTime); static SECStatus nsslowcert_UpdatePermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust); + NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust); static SECStatus -nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL); +nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, + SECItem *crlKey, char *url, PRBool isKRL); static NSSLOWCERTCertificate *certListHead = NULL; static NSSLOWCERTTrust *trustListHead = NULL; @@ -52,8 +52,8 @@ void certdb_InitDBLock(NSSLOWCERTCertDBHandle *handle) { if (dbLock == NULL) { - dbLock = PZ_NewLock(nssILockCertDB); - PORT_Assert(dbLock != NULL); + dbLock = PZ_NewLock(nssILockCertDB); + PORT_Assert(dbLock != NULL); } } @@ -61,33 +61,33 @@ SECStatus nsslowcert_InitLocks(void) { if (freeListLock == NULL) { - freeListLock = PZ_NewLock(nssILockRefLock); - if (freeListLock == NULL) { - return SECFailure; - } + freeListLock = PZ_NewLock(nssILockRefLock); + if (freeListLock == NULL) { + return SECFailure; + } } if (certRefCountLock == NULL) { - certRefCountLock = PZ_NewLock(nssILockRefLock); - if (certRefCountLock == NULL) { - return SECFailure; - } - } - if (certTrustLock == NULL ) { - certTrustLock = PZ_NewLock(nssILockCertDB); - if (certTrustLock == NULL) { - return SECFailure; - } - } - + certRefCountLock = PZ_NewLock(nssILockRefLock); + if (certRefCountLock == NULL) { + return SECFailure; + } + } + if (certTrustLock == NULL) { + certTrustLock = PZ_NewLock(nssILockCertDB); + if (certTrustLock == NULL) { + return SECFailure; + } + } + return SECSuccess; } /* * Acquire the global lock on the cert database. * This lock is currently used for the following operations: - * adding or deleting a cert to either the temp or perm databases - * converting a temp to perm or perm to temp - * changing (maybe just adding!?) the trust of a cert + * adding or deleting a cert to either the temp or perm databases + * converting a temp to perm or perm to temp + * changing (maybe just adding!?) the trust of a cert * chaning the DB status checking Configuration */ static void @@ -111,7 +111,6 @@ nsslowcert_UnlockDB(NSSLOWCERTCertDBHandle *handle) #endif } - /* * Acquire the cert reference count lock * There is currently one global lock for all certs, but I'm putting a cert @@ -122,7 +121,7 @@ static void nsslowcert_LockCertRefCount(NSSLOWCERTCertificate *cert) { PORT_Assert(certRefCountLock != NULL); - + PZ_Lock(certRefCountLock); return; } @@ -134,7 +133,7 @@ static void nsslowcert_UnlockCertRefCount(NSSLOWCERTCertificate *cert) { PORT_Assert(certRefCountLock != NULL); - + #ifdef DEBUG { PRStatus prstat = PZ_Unlock(certRefCountLock); @@ -167,7 +166,7 @@ static void nsslowcert_UnlockCertTrust(NSSLOWCERTCertificate *cert) { PORT_Assert(certTrustLock != NULL); - + #ifdef DEBUG { PRStatus prstat = PZ_Unlock(certTrustLock); @@ -178,7 +177,6 @@ nsslowcert_UnlockCertTrust(NSSLOWCERTCertificate *cert) #endif } - /* * Acquire the cert reference count lock * There is currently one global lock for all certs, but I'm putting a cert @@ -189,7 +187,7 @@ static void nsslowcert_LockFreeList(void) { PORT_Assert(freeListLock != NULL); - + SKIP_AFTER_FORK(PZ_Lock(freeListLock)); return; } @@ -201,7 +199,7 @@ static void nsslowcert_UnlockFreeList(void) { PORT_Assert(freeListLock != NULL); - + #ifdef DEBUG { PRStatus prstat = PR_SUCCESS; @@ -217,9 +215,9 @@ NSSLOWCERTCertificate * nsslowcert_DupCertificate(NSSLOWCERTCertificate *c) { if (c) { - nsslowcert_LockCertRefCount(c); - ++c->referenceCount; - nsslowcert_UnlockCertRefCount(c); + nsslowcert_LockCertRefCount(c); + ++c->referenceCount; + nsslowcert_UnlockCertRefCount(c); } return c; } @@ -228,15 +226,15 @@ static int certdb_Get(DB *db, DBT *key, DBT *data, unsigned int flags) { int ret; - + PORT_Assert(dbLock != NULL); PZ_Lock(dbLock); - ret = (* db->get)(db, key, data, flags); + ret = (*db->get)(db, key, data, flags); (void)PZ_Unlock(dbLock); - return(ret); + return (ret); } static int @@ -247,11 +245,11 @@ certdb_Put(DB *db, DBT *key, DBT *data, unsigned int flags) PORT_Assert(dbLock != NULL); PZ_Lock(dbLock); - ret = (* db->put)(db, key, data, flags); - + ret = (*db->put)(db, key, data, flags); + (void)PZ_Unlock(dbLock); - return(ret); + return (ret); } static int @@ -262,14 +260,14 @@ certdb_Sync(DB *db, unsigned int flags) PORT_Assert(dbLock != NULL); PZ_Lock(dbLock); - ret = (* db->sync)(db, flags); - + ret = (*db->sync)(db, flags); + (void)PZ_Unlock(dbLock); - return(ret); + return (ret); } -#define DB_NOT_FOUND -30991 /* from DBM 3.2 */ +#define DB_NOT_FOUND -30991 /* from DBM 3.2 */ static int certdb_Del(DB *db, DBT *key, unsigned int flags) { @@ -278,31 +276,31 @@ certdb_Del(DB *db, DBT *key, unsigned int flags) PORT_Assert(dbLock != NULL); PZ_Lock(dbLock); - ret = (* db->del)(db, key, flags); - + ret = (*db->del)(db, key, flags); + (void)PZ_Unlock(dbLock); /* don't fail if the record is already deleted */ if (ret == DB_NOT_FOUND) { - ret = 0; + ret = 0; } - return(ret); + return (ret); } static int certdb_Seq(DB *db, DBT *key, DBT *data, unsigned int flags) { int ret; - + PORT_Assert(dbLock != NULL); PZ_Lock(dbLock); - - ret = (* db->seq)(db, key, data, flags); + + ret = (*db->seq)(db, key, data, flags); (void)PZ_Unlock(dbLock); - return(ret); + return (ret); } static void @@ -311,8 +309,8 @@ certdb_Close(DB *db) PORT_Assert(dbLock != NULL); SKIP_AFTER_FORK(PZ_Lock(dbLock)); - (* db->close)(db); - + (*db->close)(db); + SKIP_AFTER_FORK(PZ_Unlock(dbLock)); return; @@ -322,32 +320,32 @@ void pkcs11_freeNickname(char *nickname, char *space) { if (nickname && nickname != space) { - PORT_Free(nickname); + PORT_Free(nickname); } } char * -pkcs11_copyNickname(char *nickname,char *space, int spaceLen) +pkcs11_copyNickname(char *nickname, char *space, int spaceLen) { int len; char *copy = NULL; - len = PORT_Strlen(nickname)+1; + len = PORT_Strlen(nickname) + 1; if (len <= spaceLen) { - copy = space; - PORT_Memcpy(copy,nickname,len); + copy = space; + PORT_Memcpy(copy, nickname, len); } else { - copy = PORT_Strdup(nickname); + copy = PORT_Strdup(nickname); } return copy; } void -pkcs11_freeStaticData (unsigned char *data, unsigned char *space) +pkcs11_freeStaticData(unsigned char *data, unsigned char *space) { if (data && data != space) { - PORT_Free(data); + PORT_Free(data); } } @@ -357,21 +355,21 @@ pkcs11_allocStaticData(int len, unsigned char *space, int spaceLen) unsigned char *data = NULL; if (len <= spaceLen) { - data = space; + data = space; } else { - data = (unsigned char *) PORT_Alloc(len); + data = (unsigned char *)PORT_Alloc(len); } return data; } unsigned char * -pkcs11_copyStaticData(unsigned char *data, int len, - unsigned char *space, int spaceLen) +pkcs11_copyStaticData(unsigned char *data, int len, + unsigned char *space, int spaceLen) { unsigned char *copy = pkcs11_allocStaticData(len, space, spaceLen); if (copy) { - PORT_Memcpy(copy,data,len); + PORT_Memcpy(copy, data, len); } return copy; @@ -387,29 +385,28 @@ DestroyDBEntry(certDBEntry *entry) /* must be one of our certDBEntry from the free list */ if (arena == NULL) { - certDBEntryCert *certEntry; - if ( entry->common.type != certDBEntryTypeCert) { - return; - } - certEntry = (certDBEntryCert *)entry; - - pkcs11_freeStaticData(certEntry->derCert.data, certEntry->derCertSpace); - pkcs11_freeNickname(certEntry->nickname, certEntry->nicknameSpace); - - nsslowcert_LockFreeList(); - if (entryListCount > MAX_ENTRY_LIST_COUNT) { - PORT_Free(certEntry); - } else { - entryListCount++; - PORT_Memset(certEntry, 0, sizeof( *certEntry)); - certEntry->next = entryListHead; - entryListHead = certEntry; - } - nsslowcert_UnlockFreeList(); - return; + certDBEntryCert *certEntry; + if (entry->common.type != certDBEntryTypeCert) { + return; + } + certEntry = (certDBEntryCert *)entry; + + pkcs11_freeStaticData(certEntry->derCert.data, certEntry->derCertSpace); + pkcs11_freeNickname(certEntry->nickname, certEntry->nicknameSpace); + + nsslowcert_LockFreeList(); + if (entryListCount > MAX_ENTRY_LIST_COUNT) { + PORT_Free(certEntry); + } else { + entryListCount++; + PORT_Memset(certEntry, 0, sizeof(*certEntry)); + certEntry->next = entryListHead; + entryListHead = certEntry; + } + nsslowcert_UnlockFreeList(); + return; } - /* Zero out the entry struct, so that any further attempts to use it * will cause an exception (e.g. null pointer reference). */ PORT_Memset(&entry->common, 0, sizeof entry->common); @@ -430,96 +427,96 @@ DeleteDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryType type, SECItem *dbk /* init the database key */ key.data = dbkey->data; key.size = dbkey->len; - + dbkey->data[0] = (unsigned char)type; /* delete entry from database */ - ret = certdb_Del(handle->permCertDB, &key, 0 ); - if ( ret != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + ret = certdb_Del(handle->permCertDB, &key, 0); + if (ret != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } ret = certdb_Sync(handle->permCertDB, 0); - if ( ret ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (ret) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - return(SECSuccess); - + return (SECSuccess); + loser: - return(SECFailure); + return (SECFailure); } static SECStatus ReadDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCommon *entry, - SECItem *dbkey, SECItem *dbentry, PLArenaPool *arena) + SECItem *dbkey, SECItem *dbentry, PLArenaPool *arena) { DBT data, key; int ret; unsigned char *buf; - + /* init the database key */ key.data = dbkey->data; key.size = dbkey->len; - + dbkey->data[0] = (unsigned char)entry->type; /* read entry from database */ - ret = certdb_Get(handle->permCertDB, &key, &data, 0 ); - if ( ret != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + ret = certdb_Get(handle->permCertDB, &key, &data, 0); + if (ret != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + /* validate the entry */ - if ( data.size < SEC_DB_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (data.size < SEC_DB_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } buf = (unsigned char *)data.data; /* version 7 has the same schema, we may be using a v7 db if we openned * the databases readonly. */ - if (!((buf[0] == (unsigned char)CERT_DB_FILE_VERSION) - || (buf[0] == (unsigned char) CERT_DB_V7_FILE_VERSION))) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (!((buf[0] == (unsigned char)CERT_DB_FILE_VERSION) || + (buf[0] == (unsigned char)CERT_DB_V7_FILE_VERSION))) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - if ( buf[1] != (unsigned char)entry->type ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (buf[1] != (unsigned char)entry->type) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } /* copy out header information */ entry->version = (unsigned int)buf[0]; entry->type = (certDBEntryType)buf[1]; entry->flags = (unsigned int)buf[2]; - + /* format body of entry for return to caller */ dbentry->len = data.size - SEC_DB_ENTRY_HEADER_LEN; - if ( dbentry->len ) { - if (arena) { - dbentry->data = (unsigned char *) - PORT_ArenaAlloc(arena, dbentry->len); - if ( dbentry->data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - PORT_Memcpy(dbentry->data, &buf[SEC_DB_ENTRY_HEADER_LEN], - dbentry->len); - } else { - dbentry->data = &buf[SEC_DB_ENTRY_HEADER_LEN]; - } + if (dbentry->len) { + if (arena) { + dbentry->data = (unsigned char *) + PORT_ArenaAlloc(arena, dbentry->len); + if (dbentry->data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + + PORT_Memcpy(dbentry->data, &buf[SEC_DB_ENTRY_HEADER_LEN], + dbentry->len); + } else { + dbentry->data = &buf[SEC_DB_ENTRY_HEADER_LEN]; + } } else { - dbentry->data = NULL; + dbentry->data = NULL; } - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /** @@ -527,43 +524,43 @@ loser: **/ static SECStatus WriteDBEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCommon *entry, - SECItem *dbkey, SECItem *dbentry) + SECItem *dbkey, SECItem *dbentry) { int ret; DBT data, key; unsigned char *buf; - + data.data = dbentry->data; data.size = dbentry->len; - - buf = (unsigned char*)data.data; - + + buf = (unsigned char *)data.data; + buf[0] = (unsigned char)entry->version; buf[1] = (unsigned char)entry->type; buf[2] = (unsigned char)entry->flags; - + key.data = dbkey->data; key.size = dbkey->len; - + dbkey->data[0] = (unsigned char)entry->type; /* put the record into the database now */ ret = certdb_Put(handle->permCertDB, &key, &data, 0); - if ( ret != 0 ) { - goto loser; + if (ret != 0) { + goto loser; } - ret = certdb_Sync( handle->permCertDB, 0 ); - - if ( ret ) { - goto loser; + ret = certdb_Sync(handle->permCertDB, 0); + + if (ret) { + goto loser; } - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -576,50 +573,50 @@ EncodeDBCertEntry(certDBEntryCert *entry, PLArenaPool *arena, SECItem *dbitem) unsigned char *buf; char *nn; char zbuf = 0; - - if ( entry->nickname ) { - nn = entry->nickname; + + if (entry->nickname) { + nn = entry->nickname; } else { - nn = &zbuf; + nn = &zbuf; } nnlen = PORT_Strlen(nn) + 1; - + /* allocate space for encoded database record, including space * for low level header */ dbitem->len = entry->derCert.len + nnlen + DB_CERT_ENTRY_HEADER_LEN + - SEC_DB_ENTRY_HEADER_LEN; - + SEC_DB_ENTRY_HEADER_LEN; + dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (dbitem->data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + /* fill in database record */ buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = (PRUint8)( entry->trust.sslFlags >> 8 ); - buf[1] = (PRUint8)( entry->trust.sslFlags ); - buf[2] = (PRUint8)( entry->trust.emailFlags >> 8 ); - buf[3] = (PRUint8)( entry->trust.emailFlags ); - buf[4] = (PRUint8)( entry->trust.objectSigningFlags >> 8 ); - buf[5] = (PRUint8)( entry->trust.objectSigningFlags ); - buf[6] = (PRUint8)( entry->derCert.len >> 8 ); - buf[7] = (PRUint8)( entry->derCert.len ); - buf[8] = (PRUint8)( nnlen >> 8 ); - buf[9] = (PRUint8)( nnlen ); - + + buf[0] = (PRUint8)(entry->trust.sslFlags >> 8); + buf[1] = (PRUint8)(entry->trust.sslFlags); + buf[2] = (PRUint8)(entry->trust.emailFlags >> 8); + buf[3] = (PRUint8)(entry->trust.emailFlags); + buf[4] = (PRUint8)(entry->trust.objectSigningFlags >> 8); + buf[5] = (PRUint8)(entry->trust.objectSigningFlags); + buf[6] = (PRUint8)(entry->derCert.len >> 8); + buf[7] = (PRUint8)(entry->derCert.len); + buf[8] = (PRUint8)(nnlen >> 8); + buf[9] = (PRUint8)(nnlen); + PORT_Memcpy(&buf[DB_CERT_ENTRY_HEADER_LEN], entry->derCert.data, - entry->derCert.len); + entry->derCert.len); PORT_Memcpy(&buf[DB_CERT_ENTRY_HEADER_LEN + entry->derCert.len], - nn, nnlen); + nn, nnlen); - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -630,59 +627,58 @@ EncodeDBCertKey(const SECItem *certKey, PLArenaPool *arena, SECItem *dbkey) { unsigned int len = certKey->len + SEC_DB_KEY_HEADER_LEN; if (len > NSS_MAX_LEGACY_DB_KEY_SIZE) - goto loser; + goto loser; if (arena) { - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, len); + dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, len); } else { - if (dbkey->len < len) { - dbkey->data = (unsigned char *)PORT_Alloc(len); - } + if (dbkey->len < len) { + dbkey->data = (unsigned char *)PORT_Alloc(len); + } } dbkey->len = len; - if ( dbkey->data == NULL ) { - goto loser; + if (dbkey->data == NULL) { + goto loser; } PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], - certKey->data, certKey->len); + certKey->data, certKey->len); dbkey->data[0] = certDBEntryTypeCert; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus EncodeDBGenericKey(const SECItem *certKey, PLArenaPool *arena, SECItem *dbkey, - certDBEntryType entryType) + certDBEntryType entryType) { /* * we only allow _one_ KRL key! */ if (entryType == certDBEntryTypeKeyRevocation) { - dbkey->len = SEC_DB_KEY_HEADER_LEN; - dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; - } - dbkey->data[0] = (unsigned char) entryType; - return(SECSuccess); + dbkey->len = SEC_DB_KEY_HEADER_LEN; + dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); + if (dbkey->data == NULL) { + goto loser; + } + dbkey->data[0] = (unsigned char)entryType; + return (SECSuccess); } - dbkey->len = certKey->len + SEC_DB_KEY_HEADER_LEN; if (dbkey->len > NSS_MAX_LEGACY_DB_KEY_SIZE) - goto loser; + goto loser; dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; + if (dbkey->data == NULL) { + goto loser; } PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], - certKey->data, certKey->len); - dbkey->data[0] = (unsigned char) entryType; + certKey->data, certKey->len); + dbkey->data[0] = (unsigned char)entryType; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus @@ -693,153 +689,152 @@ DecodeDBCertEntry(certDBEntryCert *entry, SECItem *dbentry) int lenoff; /* allow updates of old versions of the database */ - switch ( entry->common.version ) { - case 5: - headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; - lenoff = 3; - break; - case 6: - /* should not get here */ - PORT_Assert(0); - headerlen = DB_CERT_V6_ENTRY_HEADER_LEN; - lenoff = 3; - break; - case 7: - case 8: - headerlen = DB_CERT_ENTRY_HEADER_LEN; - lenoff = 6; - break; - default: - /* better not get here */ - PORT_Assert(0); - headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; - lenoff = 3; - break; - } - + switch (entry->common.version) { + case 5: + headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; + lenoff = 3; + break; + case 6: + /* should not get here */ + PORT_Assert(0); + headerlen = DB_CERT_V6_ENTRY_HEADER_LEN; + lenoff = 3; + break; + case 7: + case 8: + headerlen = DB_CERT_ENTRY_HEADER_LEN; + lenoff = 6; + break; + default: + /* better not get here */ + PORT_Assert(0); + headerlen = DB_CERT_V5_ENTRY_HEADER_LEN; + lenoff = 3; + break; + } + /* is record long enough for header? */ - if ( dbentry->len < headerlen ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry->len < headerlen) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + /* is database entry correct length? */ - entry->derCert.len = ( ( dbentry->data[lenoff] << 8 ) | - dbentry->data[lenoff+1] ); - nnlen = ( ( dbentry->data[lenoff+2] << 8 ) | dbentry->data[lenoff+3] ); - lenoff = dbentry->len - ( entry->derCert.len + nnlen + headerlen ); - if ( lenoff ) { - if ( lenoff < 0 || (lenoff & 0xffff) != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - /* The cert size exceeded 64KB. Reconstruct the correct length. */ - entry->derCert.len += lenoff; - } - + entry->derCert.len = ((dbentry->data[lenoff] << 8) | + dbentry->data[lenoff + 1]); + nnlen = ((dbentry->data[lenoff + 2] << 8) | dbentry->data[lenoff + 3]); + lenoff = dbentry->len - (entry->derCert.len + nnlen + headerlen); + if (lenoff) { + if (lenoff < 0 || (lenoff & 0xffff) != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + /* The cert size exceeded 64KB. Reconstruct the correct length. */ + entry->derCert.len += lenoff; + } + /* copy the dercert */ entry->derCert.data = pkcs11_copyStaticData(&dbentry->data[headerlen], - entry->derCert.len,entry->derCertSpace,sizeof(entry->derCertSpace)); - if ( entry->derCert.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + entry->derCert.len, entry->derCertSpace, sizeof(entry->derCertSpace)); + if (entry->derCert.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } /* copy the nickname */ - if ( nnlen > 1 ) { - entry->nickname = (char *)pkcs11_copyStaticData( - &dbentry->data[headerlen+entry->derCert.len], nnlen, - (unsigned char *)entry->nicknameSpace, - sizeof(entry->nicknameSpace)); - if ( entry->nickname == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } + if (nnlen > 1) { + entry->nickname = (char *)pkcs11_copyStaticData( + &dbentry->data[headerlen + entry->derCert.len], nnlen, + (unsigned char *)entry->nicknameSpace, + sizeof(entry->nicknameSpace)); + if (entry->nickname == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } } else { - entry->nickname = NULL; - } - - if ( entry->common.version < 7 ) { - /* allow updates of v5 db */ - entry->trust.sslFlags = dbentry->data[0]; - entry->trust.emailFlags = dbentry->data[1]; - entry->trust.objectSigningFlags = dbentry->data[2]; + entry->nickname = NULL; + } + + if (entry->common.version < 7) { + /* allow updates of v5 db */ + entry->trust.sslFlags = dbentry->data[0]; + entry->trust.emailFlags = dbentry->data[1]; + entry->trust.objectSigningFlags = dbentry->data[2]; } else { - entry->trust.sslFlags = ( dbentry->data[0] << 8 ) | dbentry->data[1]; - entry->trust.emailFlags = ( dbentry->data[2] << 8 ) | dbentry->data[3]; - entry->trust.objectSigningFlags = - ( dbentry->data[4] << 8 ) | dbentry->data[5]; + entry->trust.sslFlags = (dbentry->data[0] << 8) | dbentry->data[1]; + entry->trust.emailFlags = (dbentry->data[2] << 8) | dbentry->data[3]; + entry->trust.objectSigningFlags = + (dbentry->data[4] << 8) | dbentry->data[5]; } - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } - /* * Create a new certDBEntryCert from existing data */ static certDBEntryCert * NewDBCertEntry(SECItem *derCert, char *nickname, - NSSLOWCERTCertTrust *trust, int flags) + NSSLOWCERTCertTrust *trust, int flags) { certDBEntryCert *entry; PLArenaPool *arena = NULL; int nnlen; - - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); - if ( !arena ) { - goto loser; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + + if (!arena) { + goto loser; } - + entry = PORT_ArenaZNew(arena, certDBEntryCert); - if ( entry == NULL ) { - goto loser; + if (entry == NULL) { + goto loser; } - + /* fill in the dbCert */ entry->common.arena = arena; entry->common.type = certDBEntryTypeCert; entry->common.version = CERT_DB_FILE_VERSION; entry->common.flags = flags; - - if ( trust ) { - entry->trust = *trust; + + if (trust) { + entry->trust = *trust; } entry->derCert.data = (unsigned char *)PORT_ArenaAlloc(arena, derCert->len); - if ( !entry->derCert.data ) { - goto loser; + if (!entry->derCert.data) { + goto loser; } entry->derCert.len = derCert->len; PORT_Memcpy(entry->derCert.data, derCert->data, derCert->len); - - nnlen = ( nickname ? strlen(nickname) + 1 : 0 ); - - if ( nnlen ) { - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( !entry->nickname ) { - goto loser; - } - PORT_Memcpy(entry->nickname, nickname, nnlen); - + + nnlen = (nickname ? strlen(nickname) + 1 : 0); + + if (nnlen) { + entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); + if (!entry->nickname) { + goto loser; + } + PORT_Memcpy(entry->nickname, nickname, nnlen); + } else { - entry->nickname = 0; + entry->nickname = 0; } - return(entry); + return (entry); loser: - + /* allocation error, free arena and return */ - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - + PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); + return (0); } /* @@ -853,36 +848,36 @@ DecodeV4DBCertEntry(unsigned char *buf, int len) int certlen; int nnlen; PLArenaPool *arena; - + /* make sure length is at least long enough for the header */ - if ( len < DBCERT_V4_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(0); + if (len < DBCERT_V4_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (0); } /* get other lengths */ certlen = buf[3] << 8 | buf[4]; nnlen = buf[5] << 8 | buf[6]; - + /* make sure DB entry is the right size */ - if ( ( certlen + nnlen + DBCERT_V4_HEADER_LEN ) != len ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(0); + if ((certlen + nnlen + DBCERT_V4_HEADER_LEN) != len) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + return (0); } /* allocate arena */ - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( !arena ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); + if (!arena) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return (0); } - + /* allocate structure and members */ - entry = (certDBEntryCert *) PORT_ArenaAlloc(arena, sizeof(certDBEntryCert)); + entry = (certDBEntryCert *)PORT_ArenaAlloc(arena, sizeof(certDBEntryCert)); - if ( !entry ) { - goto loser; + if (!entry) { + goto loser; } entry->common.arena = arena; @@ -894,19 +889,19 @@ DecodeV4DBCertEntry(unsigned char *buf, int len) entry->trust.objectSigningFlags = buf[2]; entry->derCert.data = (unsigned char *)PORT_ArenaAlloc(arena, certlen); - if ( !entry->derCert.data ) { - goto loser; + if (!entry->derCert.data) { + goto loser; } entry->derCert.len = certlen; PORT_Memcpy(entry->derCert.data, &buf[DBCERT_V4_HEADER_LEN], certlen); - if ( nnlen ) { - entry->nickname = (char *) PORT_ArenaAlloc(arena, nnlen); - if ( !entry->nickname ) { + if (nnlen) { + entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); + if (!entry->nickname) { goto loser; } PORT_Memcpy(entry->nickname, &buf[DBCERT_V4_HEADER_LEN + certlen], nnlen); - + if (PORT_Strcmp(entry->nickname, "Server-Cert") == 0) { entry->trust.sslFlags |= CERTDB_USER; } @@ -914,12 +909,12 @@ DecodeV4DBCertEntry(unsigned char *buf, int len) entry->nickname = 0; } - return(entry); - + return (entry); + loser: PORT_FreeArena(arena, PR_FALSE); PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); + return (0); } /* @@ -933,45 +928,44 @@ WriteDBCertEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry) PLArenaPool *tmparena = NULL; SECItem tmpitem; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } - + rv = EncodeDBCertEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* get the database key and format it */ rv = nsslowcert_KeyFromDERCert(tmparena, &entry->derCert, &tmpitem); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } rv = EncodeDBCertKey(&tmpitem, tmparena, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } - + /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); + return (SECFailure); } - /* * delete a certificate entry */ @@ -981,28 +975,28 @@ DeleteDBCertEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey) SECItem dbkey; SECStatus rv; - dbkey.data= NULL; + dbkey.data = NULL; dbkey.len = 0; rv = EncodeDBCertKey(certKey, NULL, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = DeleteDBEntry(handle, certDBEntryTypeCert, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } PORT_Free(dbkey.data); - return(SECSuccess); + return (SECSuccess); loser: if (dbkey.data) { - PORT_Free(dbkey.data); + PORT_Free(dbkey.data); } - return(SECFailure); + return (SECFailure); } static certDBEntryCert * @@ -1013,13 +1007,13 @@ CreateCertEntry(void) nsslowcert_LockFreeList(); entry = entryListHead; if (entry) { - entryListCount--; - entryListHead = entry->next; + entryListCount--; + entryListHead = entry->next; } PORT_Assert(entryListCount >= 0); nsslowcert_UnlockFreeList(); if (entry) { - return entry; + return entry; } return PORT_ZNew(certDBEntryCert); @@ -1032,9 +1026,9 @@ DestroyCertEntryFreeList(void) nsslowcert_LockFreeList(); while (NULL != (entry = entryListHead)) { - entryListCount--; - entryListHead = entry->next; - PORT_Free(entry); + entryListCount--; + entryListHead = entry->next; + PORT_Free(entry); } PORT_Assert(!entryListCount); entryListCount = 0; @@ -1057,40 +1051,40 @@ ReadDBCertEntry(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey) dbkey.len = sizeof(buf); entry = CreateCertEntry(); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = NULL; entry->common.type = certDBEntryTypeCert; rv = EncodeDBCertKey(certKey, NULL, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, NULL); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } rv = DecodeDBCertEntry(entry, &dbentry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - pkcs11_freeStaticData(dbkey.data,buf); + pkcs11_freeStaticData(dbkey.data, buf); dbkey.data = NULL; - return(entry); - + return (entry); + loser: - pkcs11_freeStaticData(dbkey.data,buf); + pkcs11_freeStaticData(dbkey.data, buf); dbkey.data = NULL; - if ( entry ) { + if (entry) { DestroyDBEntry((certDBEntry *)entry); } - - return(NULL); + + return (NULL); } /* @@ -1101,43 +1095,42 @@ EncodeDBCrlEntry(certDBEntryRevocation *entry, PLArenaPool *arena, SECItem *dbit { unsigned int nnlen = 0; unsigned char *buf; - - if (entry->url) { - nnlen = PORT_Strlen(entry->url) + 1; + + if (entry->url) { + nnlen = PORT_Strlen(entry->url) + 1; } - + /* allocate space for encoded database record, including space * for low level header */ - dbitem->len = entry->derCrl.len + nnlen - + SEC_DB_ENTRY_HEADER_LEN + DB_CRL_ENTRY_HEADER_LEN; - + dbitem->len = entry->derCrl.len + nnlen + SEC_DB_ENTRY_HEADER_LEN + DB_CRL_ENTRY_HEADER_LEN; + dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (dbitem->data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + /* fill in database record */ buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = (PRUint8)( entry->derCrl.len >> 8 ); - buf[1] = (PRUint8)( entry->derCrl.len ); - buf[2] = (PRUint8)( nnlen >> 8 ); - buf[3] = (PRUint8)( nnlen ); - + + buf[0] = (PRUint8)(entry->derCrl.len >> 8); + buf[1] = (PRUint8)(entry->derCrl.len); + buf[2] = (PRUint8)(nnlen >> 8); + buf[3] = (PRUint8)(nnlen); + PORT_Memcpy(&buf[DB_CRL_ENTRY_HEADER_LEN], entry->derCrl.data, - entry->derCrl.len); + entry->derCrl.len); if (nnlen != 0) { - PORT_Memcpy(&buf[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], - entry->url, nnlen); + PORT_Memcpy(&buf[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], + entry->url, nnlen); } - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus @@ -1147,189 +1140,186 @@ DecodeDBCrlEntry(certDBEntryRevocation *entry, SECItem *dbentry) int lenDiff; /* is record long enough for header? */ - if ( dbentry->len < DB_CRL_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry->len < DB_CRL_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + /* is database entry correct length? */ - entry->derCrl.len = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - urlLen = ( ( dbentry->data[2] << 8 ) | dbentry->data[3] ); - lenDiff = dbentry->len - - (entry->derCrl.len + urlLen + DB_CRL_ENTRY_HEADER_LEN); + entry->derCrl.len = ((dbentry->data[0] << 8) | dbentry->data[1]); + urlLen = ((dbentry->data[2] << 8) | dbentry->data[3]); + lenDiff = dbentry->len - + (entry->derCrl.len + urlLen + DB_CRL_ENTRY_HEADER_LEN); if (lenDiff) { - if (lenDiff < 0 || (lenDiff & 0xffff) != 0) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - /* CRL entry is greater than 64 K. Hack to make this continue to work */ - entry->derCrl.len += lenDiff; - } - + if (lenDiff < 0 || (lenDiff & 0xffff) != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + /* CRL entry is greater than 64 K. Hack to make this continue to work */ + entry->derCrl.len += lenDiff; + } + /* copy the der CRL */ entry->derCrl.data = (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->derCrl.len); - if ( entry->derCrl.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + entry->derCrl.len); + if (entry->derCrl.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } PORT_Memcpy(entry->derCrl.data, &dbentry->data[DB_CRL_ENTRY_HEADER_LEN], - entry->derCrl.len); + entry->derCrl.len); /* copy the url */ entry->url = NULL; if (urlLen != 0) { - entry->url = (char *)PORT_ArenaAlloc(entry->common.arena, urlLen); - if ( entry->url == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->url, - &dbentry->data[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], - urlLen); - } - - return(SECSuccess); + entry->url = (char *)PORT_ArenaAlloc(entry->common.arena, urlLen); + if (entry->url == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->url, + &dbentry->data[DB_CRL_ENTRY_HEADER_LEN + entry->derCrl.len], + urlLen); + } + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* * Create a new certDBEntryRevocation from existing data */ static certDBEntryRevocation * -NewDBCrlEntry(SECItem *derCrl, char * url, certDBEntryType crlType, int flags) +NewDBCrlEntry(SECItem *derCrl, char *url, certDBEntryType crlType, int flags) { certDBEntryRevocation *entry; PLArenaPool *arena = NULL; int nnlen; - - arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE ); - if ( !arena ) { - goto loser; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + + if (!arena) { + goto loser; } - + entry = PORT_ArenaZNew(arena, certDBEntryRevocation); - if ( entry == NULL ) { - goto loser; + if (entry == NULL) { + goto loser; } - + /* fill in the dbRevolcation */ entry->common.arena = arena; entry->common.type = crlType; entry->common.version = CERT_DB_FILE_VERSION; entry->common.flags = flags; - entry->derCrl.data = (unsigned char *)PORT_ArenaAlloc(arena, derCrl->len); - if ( !entry->derCrl.data ) { - goto loser; + if (!entry->derCrl.data) { + goto loser; } if (url) { - nnlen = PORT_Strlen(url) + 1; - entry->url = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( !entry->url ) { - goto loser; - } - PORT_Memcpy(entry->url, url, nnlen); + nnlen = PORT_Strlen(url) + 1; + entry->url = (char *)PORT_ArenaAlloc(arena, nnlen); + if (!entry->url) { + goto loser; + } + PORT_Memcpy(entry->url, url, nnlen); } else { - entry->url = NULL; + entry->url = NULL; } - entry->derCrl.len = derCrl->len; PORT_Memcpy(entry->derCrl.data, derCrl->data, derCrl->len); - return(entry); + return (entry); loser: - + /* allocation error, free arena and return */ - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - + PORT_SetError(SEC_ERROR_NO_MEMORY); - return(0); + return (0); } - static SECStatus WriteDBCrlEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryRevocation *entry, - SECItem *crlKey ) + SECItem *crlKey) { SECItem dbkey; PLArenaPool *tmparena = NULL; SECItem encodedEntry; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } rv = EncodeDBCrlEntry(entry, tmparena, &encodedEntry); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } rv = EncodeDBGenericKey(crlKey, tmparena, &dbkey, entry->common.type); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } - + /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &encodedEntry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); + return (SECFailure); } /* * delete a crl entry */ static SECStatus -DeleteDBCrlEntry(NSSLOWCERTCertDBHandle *handle, const SECItem *crlKey, - certDBEntryType crlType) +DeleteDBCrlEntry(NSSLOWCERTCertDBHandle *handle, const SECItem *crlKey, + certDBEntryType crlType) { SECItem dbkey; PLArenaPool *arena = NULL; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } rv = EncodeDBGenericKey(crlKey, arena, &dbkey, crlType); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = DeleteDBEntry(handle, crlType, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(SECFailure); + + return (SECFailure); } /* @@ -1337,7 +1327,7 @@ loser: */ static certDBEntryRevocation * ReadDBCrlEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey, - certDBEntryType crlType) + certDBEntryType crlType) { PLArenaPool *arena = NULL; PLArenaPool *tmparena = NULL; @@ -1345,55 +1335,55 @@ ReadDBCrlEntry(NSSLOWCERTCertDBHandle *handle, SECItem *certKey, SECItem dbkey; SECItem dbentry; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (tmparena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + entry = (certDBEntryRevocation *) - PORT_ArenaAlloc(arena, sizeof(certDBEntryRevocation)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + PORT_ArenaAlloc(arena, sizeof(certDBEntryRevocation)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = crlType; rv = EncodeDBGenericKey(certKey, tmparena, &dbkey, crlType); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, NULL); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } rv = DecodeDBCrlEntry(entry, &dbentry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - + return (entry); + loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } void @@ -1408,31 +1398,31 @@ nsslowcert_DestroyDBEntry(certDBEntry *entry) */ static SECStatus EncodeDBNicknameEntry(certDBEntryNickname *entry, PLArenaPool *arena, - SECItem *dbitem) + SECItem *dbitem) { unsigned char *buf; - + /* allocate space for encoded database record, including space * for low level header */ dbitem->len = entry->subjectName.len + DB_NICKNAME_ENTRY_HEADER_LEN + - SEC_DB_ENTRY_HEADER_LEN; + SEC_DB_ENTRY_HEADER_LEN; dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - goto loser; + if (dbitem->data == NULL) { + goto loser; } - + /* fill in database record */ buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - buf[0] = (PRUint8)( entry->subjectName.len >> 8 ); - buf[1] = (PRUint8)( entry->subjectName.len ); + buf[0] = (PRUint8)(entry->subjectName.len >> 8); + buf[1] = (PRUint8)(entry->subjectName.len); PORT_Memcpy(&buf[DB_NICKNAME_ENTRY_HEADER_LEN], entry->subjectName.data, - entry->subjectName.len); + entry->subjectName.len); - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1440,27 +1430,27 @@ loser: */ static SECStatus EncodeDBNicknameKey(char *nickname, PLArenaPool *arena, - SECItem *dbkey) + SECItem *dbkey) { unsigned int nnlen; - + nnlen = PORT_Strlen(nickname) + 1; /* includes null */ /* now get the database key and format it */ dbkey->len = nnlen + SEC_DB_KEY_HEADER_LEN; if (dbkey->len > NSS_MAX_LEGACY_DB_KEY_SIZE) - goto loser; + goto loser; dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; + if (dbkey->data == NULL) { + goto loser; } PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], nickname, nnlen); dbkey->data[0] = certDBEntryTypeNickname; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus @@ -1470,47 +1460,47 @@ DecodeDBNicknameEntry(certDBEntryNickname *entry, SECItem *dbentry, int lenDiff; /* is record long enough for header? */ - if ( dbentry->len < DB_NICKNAME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry->len < DB_NICKNAME_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + /* is database entry correct length? */ - entry->subjectName.len = ( ( dbentry->data[0] << 8 ) | dbentry->data[1] ); - lenDiff = dbentry->len - - (entry->subjectName.len + DB_NICKNAME_ENTRY_HEADER_LEN); + entry->subjectName.len = ((dbentry->data[0] << 8) | dbentry->data[1]); + lenDiff = dbentry->len - + (entry->subjectName.len + DB_NICKNAME_ENTRY_HEADER_LEN); if (lenDiff) { - if (lenDiff < 0 || (lenDiff & 0xffff) != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - /* The entry size exceeded 64KB. Reconstruct the correct length. */ - entry->subjectName.len += lenDiff; + if (lenDiff < 0 || (lenDiff & 0xffff) != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + /* The entry size exceeded 64KB. Reconstruct the correct length. */ + entry->subjectName.len += lenDiff; } /* copy the certkey */ entry->subjectName.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->subjectName.len); - if ( entry->subjectName.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + (unsigned char *)PORT_ArenaAlloc(entry->common.arena, + entry->subjectName.len); + if (entry->subjectName.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } PORT_Memcpy(entry->subjectName.data, - &dbentry->data[DB_NICKNAME_ENTRY_HEADER_LEN], - entry->subjectName.len); + &dbentry->data[DB_NICKNAME_ENTRY_HEADER_LEN], + entry->subjectName.len); entry->subjectName.type = siBuffer; - - entry->nickname = (char *)PORT_ArenaAlloc(entry->common.arena, - PORT_Strlen(nickname)+1); - if ( entry->nickname ) { - PORT_Strcpy(entry->nickname, nickname); + + entry->nickname = (char *)PORT_ArenaAlloc(entry->common.arena, + PORT_Strlen(nickname) + 1); + if (entry->nickname) { + PORT_Strcpy(entry->nickname, nickname); } - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1523,18 +1513,18 @@ NewDBNicknameEntry(char *nickname, SECItem *subjectName, unsigned int flags) certDBEntryNickname *entry; int nnlen; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry = (certDBEntryNickname *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryNickname)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntryNickname)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } /* init common fields */ @@ -1545,26 +1535,26 @@ NewDBNicknameEntry(char *nickname, SECItem *subjectName, unsigned int flags) /* copy the nickname */ nnlen = PORT_Strlen(nickname) + 1; - - entry->nickname = (char*)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - goto loser; + + entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); + if (entry->nickname == NULL) { + goto loser; } - + PORT_Memcpy(entry->nickname, nickname, nnlen); - + rv = SECITEM_CopyItem(arena, &entry->subjectName, subjectName); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - - return(entry); + + return (entry); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -1576,35 +1566,35 @@ DeleteDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, char *nickname) PLArenaPool *arena = NULL; SECStatus rv; SECItem dbkey; - - if ( nickname == NULL ) { - return(SECSuccess); + + if (nickname == NULL) { + return (SECSuccess); } - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } rv = EncodeDBNicknameKey(nickname, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = DeleteDBEntry(handle, certDBEntryTypeNickname, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(SECFailure); + + return (SECFailure); } /* @@ -1619,61 +1609,61 @@ ReadDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, char *nickname) SECItem dbkey; SECItem dbentry; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (tmparena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + entry = (certDBEntryNickname *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryNickname)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntryNickname)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = certDBEntryTypeNickname; rv = EncodeDBNicknameKey(nickname, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } /* is record long enough for header? */ - if ( dbentry.len < DB_NICKNAME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry.len < DB_NICKNAME_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } rv = DecodeDBNicknameEntry(entry, &dbentry, nickname); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - + return (entry); + loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -1686,88 +1676,87 @@ WriteDBNicknameEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryNickname *entry) SECItem dbitem, dbkey; PLArenaPool *tmparena = NULL; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } - + rv = EncodeDBNicknameEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = EncodeDBNicknameKey(entry->nickname, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); - + return (SECFailure); } static SECStatus EncodeDBSMimeEntry(certDBEntrySMime *entry, PLArenaPool *arena, - SECItem *dbitem) + SECItem *dbitem) { unsigned char *buf; - + /* allocate space for encoded database record, including space * for low level header */ dbitem->len = entry->subjectName.len + entry->smimeOptions.len + - entry->optionsDate.len + - DB_SMIME_ENTRY_HEADER_LEN + SEC_DB_ENTRY_HEADER_LEN; - + entry->optionsDate.len + + DB_SMIME_ENTRY_HEADER_LEN + SEC_DB_ENTRY_HEADER_LEN; + dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (dbitem->data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + /* fill in database record */ buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = (PRUint8)( entry->subjectName.len >> 8 ); - buf[1] = (PRUint8)( entry->subjectName.len ); - buf[2] = (PRUint8)( entry->smimeOptions.len >> 8 ); - buf[3] = (PRUint8)( entry->smimeOptions.len ); - buf[4] = (PRUint8)( entry->optionsDate.len >> 8 ); - buf[5] = (PRUint8)( entry->optionsDate.len ); + + buf[0] = (PRUint8)(entry->subjectName.len >> 8); + buf[1] = (PRUint8)(entry->subjectName.len); + buf[2] = (PRUint8)(entry->smimeOptions.len >> 8); + buf[3] = (PRUint8)(entry->smimeOptions.len); + buf[4] = (PRUint8)(entry->optionsDate.len >> 8); + buf[5] = (PRUint8)(entry->optionsDate.len); /* if no smime options, then there should not be an options date either */ - PORT_Assert( ! ( ( entry->smimeOptions.len == 0 ) && - ( entry->optionsDate.len != 0 ) ) ); - + PORT_Assert(!((entry->smimeOptions.len == 0) && + (entry->optionsDate.len != 0))); + PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN], entry->subjectName.data, - entry->subjectName.len); - if ( entry->smimeOptions.len ) { - PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN+entry->subjectName.len], - entry->smimeOptions.data, - entry->smimeOptions.len); - PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN + entry->subjectName.len + - entry->smimeOptions.len], - entry->optionsDate.data, - entry->optionsDate.len); + entry->subjectName.len); + if (entry->smimeOptions.len) { + PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN + entry->subjectName.len], + entry->smimeOptions.data, + entry->smimeOptions.len); + PORT_Memcpy(&buf[DB_SMIME_ENTRY_HEADER_LEN + entry->subjectName.len + + entry->smimeOptions.len], + entry->optionsDate.data, + entry->optionsDate.len); } - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1775,27 +1764,27 @@ loser: */ static SECStatus EncodeDBSMimeKey(char *emailAddr, PLArenaPool *arena, - SECItem *dbkey) + SECItem *dbkey) { unsigned int addrlen; - + addrlen = PORT_Strlen(emailAddr) + 1; /* includes null */ /* now get the database key and format it */ dbkey->len = addrlen + SEC_DB_KEY_HEADER_LEN; if (dbkey->len > NSS_MAX_LEGACY_DB_KEY_SIZE) - goto loser; + goto loser; dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; + if (dbkey->data == NULL) { + goto loser; } PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], emailAddr, addrlen); dbkey->data[0] = certDBEntryTypeSMimeProfile; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1807,87 +1796,87 @@ DecodeDBSMimeEntry(certDBEntrySMime *entry, SECItem *dbentry, char *emailAddr) int lenDiff; /* is record long enough for header? */ - if ( dbentry->len < DB_SMIME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry->len < DB_SMIME_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + /* is database entry correct length? */ - entry->subjectName.len = (( dbentry->data[0] << 8 ) | dbentry->data[1] ); - entry->smimeOptions.len = (( dbentry->data[2] << 8 ) | dbentry->data[3] ); - entry->optionsDate.len = (( dbentry->data[4] << 8 ) | dbentry->data[5] ); - lenDiff = dbentry->len - (entry->subjectName.len + - entry->smimeOptions.len + - entry->optionsDate.len + - DB_SMIME_ENTRY_HEADER_LEN); + entry->subjectName.len = ((dbentry->data[0] << 8) | dbentry->data[1]); + entry->smimeOptions.len = ((dbentry->data[2] << 8) | dbentry->data[3]); + entry->optionsDate.len = ((dbentry->data[4] << 8) | dbentry->data[5]); + lenDiff = dbentry->len - (entry->subjectName.len + + entry->smimeOptions.len + + entry->optionsDate.len + + DB_SMIME_ENTRY_HEADER_LEN); if (lenDiff) { - if (lenDiff < 0 || (lenDiff & 0xffff) != 0 ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - /* The entry size exceeded 64KB. Reconstruct the correct length. */ - entry->subjectName.len += lenDiff; + if (lenDiff < 0 || (lenDiff & 0xffff) != 0) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + /* The entry size exceeded 64KB. Reconstruct the correct length. */ + entry->subjectName.len += lenDiff; } /* copy the subject name */ entry->subjectName.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->subjectName.len); - if ( entry->subjectName.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + (unsigned char *)PORT_ArenaAlloc(entry->common.arena, + entry->subjectName.len); + if (entry->subjectName.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } PORT_Memcpy(entry->subjectName.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN], - entry->subjectName.len); + &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN], + entry->subjectName.len); /* copy the smime options */ - if ( entry->smimeOptions.len ) { - entry->smimeOptions.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->smimeOptions.len); - if ( entry->smimeOptions.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->smimeOptions.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + - entry->subjectName.len], - entry->smimeOptions.len); - } - if ( entry->optionsDate.len ) { - entry->optionsDate.data = - (unsigned char *)PORT_ArenaAlloc(entry->common.arena, - entry->optionsDate.len); - if ( entry->optionsDate.data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->optionsDate.data, - &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + - entry->subjectName.len + - entry->smimeOptions.len], - entry->optionsDate.len); + if (entry->smimeOptions.len) { + entry->smimeOptions.data = + (unsigned char *)PORT_ArenaAlloc(entry->common.arena, + entry->smimeOptions.len); + if (entry->smimeOptions.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->smimeOptions.data, + &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + + entry->subjectName.len], + entry->smimeOptions.len); + } + if (entry->optionsDate.len) { + entry->optionsDate.data = + (unsigned char *)PORT_ArenaAlloc(entry->common.arena, + entry->optionsDate.len); + if (entry->optionsDate.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->optionsDate.data, + &dbentry->data[DB_SMIME_ENTRY_HEADER_LEN + + entry->subjectName.len + + entry->smimeOptions.len], + entry->optionsDate.len); } /* both options and options date must either exist or not exist */ - if ( ( ( entry->optionsDate.len == 0 ) || - ( entry->smimeOptions.len == 0 ) ) && - entry->smimeOptions.len != entry->optionsDate.len ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (((entry->optionsDate.len == 0) || + (entry->smimeOptions.len == 0)) && + entry->smimeOptions.len != entry->optionsDate.len) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } entry->emailAddr = (char *)PORT_ArenaAlloc(entry->common.arena, - PORT_Strlen(emailAddr)+1); - if ( entry->emailAddr ) { - PORT_Strcpy(entry->emailAddr, emailAddr); + PORT_Strlen(emailAddr) + 1); + if (entry->emailAddr) { + PORT_Strcpy(entry->emailAddr, emailAddr); } - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -1895,24 +1884,24 @@ loser: */ static certDBEntrySMime * NewDBSMimeEntry(char *emailAddr, SECItem *subjectName, SECItem *smimeOptions, - SECItem *optionsDate, unsigned int flags) + SECItem *optionsDate, unsigned int flags) { PLArenaPool *arena = NULL; certDBEntrySMime *entry; int addrlen; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry = (certDBEntrySMime *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySMime)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntrySMime)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } /* init common fields */ @@ -1923,51 +1912,51 @@ NewDBSMimeEntry(char *emailAddr, SECItem *subjectName, SECItem *smimeOptions, /* copy the email addr */ addrlen = PORT_Strlen(emailAddr) + 1; - - entry->emailAddr = (char*)PORT_ArenaAlloc(arena, addrlen); - if ( entry->emailAddr == NULL ) { - goto loser; + + entry->emailAddr = (char *)PORT_ArenaAlloc(arena, addrlen); + if (entry->emailAddr == NULL) { + goto loser; } - + PORT_Memcpy(entry->emailAddr, emailAddr, addrlen); - + /* copy the subject name */ rv = SECITEM_CopyItem(arena, &entry->subjectName, subjectName); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* copy the smime options */ - if ( smimeOptions ) { - rv = SECITEM_CopyItem(arena, &entry->smimeOptions, smimeOptions); - if ( rv != SECSuccess ) { - goto loser; - } + if (smimeOptions) { + rv = SECITEM_CopyItem(arena, &entry->smimeOptions, smimeOptions); + if (rv != SECSuccess) { + goto loser; + } } else { - PORT_Assert(optionsDate == NULL); - entry->smimeOptions.data = NULL; - entry->smimeOptions.len = 0; + PORT_Assert(optionsDate == NULL); + entry->smimeOptions.data = NULL; + entry->smimeOptions.len = 0; } /* copy the options date */ - if ( optionsDate ) { - rv = SECITEM_CopyItem(arena, &entry->optionsDate, optionsDate); - if ( rv != SECSuccess ) { - goto loser; - } + if (optionsDate) { + rv = SECITEM_CopyItem(arena, &entry->optionsDate, optionsDate); + if (rv != SECSuccess) { + goto loser; + } } else { - PORT_Assert(smimeOptions == NULL); - entry->optionsDate.data = NULL; - entry->optionsDate.len = 0; + PORT_Assert(smimeOptions == NULL); + entry->optionsDate.data = NULL; + entry->optionsDate.len = 0; } - - return(entry); + + return (entry); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -1979,31 +1968,31 @@ DeleteDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, char *emailAddr) PLArenaPool *arena = NULL; SECStatus rv; SECItem dbkey; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } rv = EncodeDBSMimeKey(emailAddr, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = DeleteDBEntry(handle, certDBEntryTypeSMimeProfile, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(SECFailure); + + return (SECFailure); } /* @@ -2018,61 +2007,61 @@ nsslowcert_ReadDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, char *emailAddr) SECItem dbkey; SECItem dbentry; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (tmparena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + entry = (certDBEntrySMime *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySMime)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntrySMime)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = certDBEntryTypeSMimeProfile; rv = EncodeDBSMimeKey(emailAddr, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } /* is record long enough for header? */ - if ( dbentry.len < DB_SMIME_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry.len < DB_SMIME_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } rv = DecodeDBSMimeEntry(entry, &dbentry, emailAddr); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - + return (entry); + loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -2085,37 +2074,36 @@ WriteDBSMimeEntry(NSSLOWCERTCertDBHandle *handle, certDBEntrySMime *entry) SECItem dbitem, dbkey; PLArenaPool *tmparena = NULL; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } - + rv = EncodeDBSMimeEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = EncodeDBSMimeKey(entry->emailAddr, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); - + return (SECFailure); } /* @@ -2123,7 +2111,7 @@ loser: */ static SECStatus EncodeDBSubjectEntry(certDBEntrySubject *entry, PLArenaPool *arena, - SECItem *dbitem) + SECItem *dbitem) { unsigned char *buf; int len; @@ -2134,97 +2122,104 @@ EncodeDBSubjectEntry(certDBEntrySubject *entry, PLArenaPool *arena, unsigned int eaddrslen = 0; int keyidoff; SECItem *certKeys = entry->certKeys; - SECItem *keyIDs = entry->keyIDs;; - - if ( entry->nickname ) { - nnlen = PORT_Strlen(entry->nickname) + 1; + SECItem *keyIDs = entry->keyIDs; + ; + + if (entry->nickname) { + nnlen = PORT_Strlen(entry->nickname) + 1; } - if ( entry->emailAddrs ) { - eaddrslen = 2; - for (i=0; i < entry->nemailAddrs; i++) { - eaddrslen += PORT_Strlen(entry->emailAddrs[i]) + 1 + 2; - } + if (entry->emailAddrs) { + eaddrslen = 2; + for (i = 0; i < entry->nemailAddrs; i++) { + eaddrslen += PORT_Strlen(entry->emailAddrs[i]) + 1 + 2; + } } ncerts = entry->ncerts; - + /* compute the length of the entry */ - keyidoff = DB_SUBJECT_ENTRY_HEADER_LEN + nnlen ; + keyidoff = DB_SUBJECT_ENTRY_HEADER_LEN + nnlen; len = keyidoff + (4 * ncerts) + eaddrslen; - for ( i = 0; i < ncerts; i++ ) { - if (keyIDs[i].len > 0xffff || - (certKeys[i].len > 0xffff)) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - goto loser; - } - len += certKeys[i].len; - len += keyIDs[i].len; - } - + for (i = 0; i < ncerts; i++) { + if (keyIDs[i].len > 0xffff || + (certKeys[i].len > 0xffff)) { + PORT_SetError(SEC_ERROR_INPUT_LEN); + goto loser; + } + len += certKeys[i].len; + len += keyIDs[i].len; + } + /* allocate space for encoded database record, including space * for low level header */ dbitem->len = len + SEC_DB_ENTRY_HEADER_LEN; - + dbitem->data = (unsigned char *)PORT_ArenaAlloc(arena, dbitem->len); - if ( dbitem->data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (dbitem->data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + /* fill in database record */ buf = &dbitem->data[SEC_DB_ENTRY_HEADER_LEN]; - - buf[0] = (PRUint8)( ncerts >> 8 ); - buf[1] = (PRUint8)( ncerts ); - buf[2] = (PRUint8)( nnlen >> 8 ); - buf[3] = (PRUint8)( nnlen ); + + buf[0] = (PRUint8)(ncerts >> 8); + buf[1] = (PRUint8)(ncerts); + buf[2] = (PRUint8)(nnlen >> 8); + buf[3] = (PRUint8)(nnlen); /* v7 email field is NULL in v8 */ buf[4] = 0; buf[5] = 0; - PORT_Memcpy(&buf[DB_SUBJECT_ENTRY_HEADER_LEN], entry->nickname, nnlen); - tmpbuf = &buf[keyidoff]; - for ( i = 0; i < ncerts; i++ ) { - tmpbuf[0] = (PRUint8)( certKeys[i].len >> 8 ); - tmpbuf[1] = (PRUint8)( certKeys[i].len ); - tmpbuf += 2; + PORT_Assert(DB_SUBJECT_ENTRY_HEADER_LEN == 6); + + if (entry->nickname) { + PORT_Memcpy(&buf[DB_SUBJECT_ENTRY_HEADER_LEN], entry->nickname, nnlen); + } + tmpbuf = &buf[keyidoff]; + for (i = 0; i < ncerts; i++) { + tmpbuf[0] = (PRUint8)(certKeys[i].len >> 8); + tmpbuf[1] = (PRUint8)(certKeys[i].len); + tmpbuf += 2; } - for ( i = 0; i < ncerts; i++ ) { - tmpbuf[0] = (PRUint8)( keyIDs[i].len >> 8 ); - tmpbuf[1] = (PRUint8)( keyIDs[i].len ); - tmpbuf += 2; + for (i = 0; i < ncerts; i++) { + tmpbuf[0] = (PRUint8)(keyIDs[i].len >> 8); + tmpbuf[1] = (PRUint8)(keyIDs[i].len); + tmpbuf += 2; } - - for ( i = 0; i < ncerts; i++ ) { - PORT_Memcpy(tmpbuf, certKeys[i].data, certKeys[i].len); - tmpbuf += certKeys[i].len; + + for (i = 0; i < ncerts; i++) { + PORT_Memcpy(tmpbuf, certKeys[i].data, certKeys[i].len); + tmpbuf += certKeys[i].len; } - for ( i = 0; i < ncerts; i++ ) { - PORT_Memcpy(tmpbuf, keyIDs[i].data, keyIDs[i].len); - tmpbuf += keyIDs[i].len; + for (i = 0; i < ncerts; i++) { + if (keyIDs[i].len) { + PORT_Memcpy(tmpbuf, keyIDs[i].data, keyIDs[i].len); + tmpbuf += keyIDs[i].len; + } } if (entry->emailAddrs) { - tmpbuf[0] = (PRUint8)( entry->nemailAddrs >> 8 ); - tmpbuf[1] = (PRUint8)( entry->nemailAddrs ); - tmpbuf += 2; - for (i=0; i < entry->nemailAddrs; i++) { - int nameLen = PORT_Strlen(entry->emailAddrs[i]) + 1; - tmpbuf[0] = (PRUint8)( nameLen >> 8 ); - tmpbuf[1] = (PRUint8)( nameLen ); - tmpbuf += 2; - PORT_Memcpy(tmpbuf,entry->emailAddrs[i],nameLen); - tmpbuf +=nameLen; - } + tmpbuf[0] = (PRUint8)(entry->nemailAddrs >> 8); + tmpbuf[1] = (PRUint8)(entry->nemailAddrs); + tmpbuf += 2; + for (i = 0; i < entry->nemailAddrs; i++) { + int nameLen = PORT_Strlen(entry->emailAddrs[i]) + 1; + tmpbuf[0] = (PRUint8)(nameLen >> 8); + tmpbuf[1] = (PRUint8)(nameLen); + tmpbuf += 2; + PORT_Memcpy(tmpbuf, entry->emailAddrs[i], nameLen); + tmpbuf += nameLen; + } } PORT_Assert(tmpbuf == &buf[len]); - - return(SECSuccess); + + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } /* @@ -2232,186 +2227,186 @@ loser: */ static SECStatus EncodeDBSubjectKey(SECItem *derSubject, PLArenaPool *arena, - SECItem *dbkey) + SECItem *dbkey) { dbkey->len = derSubject->len + SEC_DB_KEY_HEADER_LEN; if (dbkey->len > NSS_MAX_LEGACY_DB_KEY_SIZE) - goto loser; + goto loser; dbkey->data = (unsigned char *)PORT_ArenaAlloc(arena, dbkey->len); - if ( dbkey->data == NULL ) { - goto loser; + if (dbkey->data == NULL) { + goto loser; } PORT_Memcpy(&dbkey->data[SEC_DB_KEY_HEADER_LEN], derSubject->data, - derSubject->len); + derSubject->len); dbkey->data[0] = certDBEntryTypeSubject; - return(SECSuccess); + return (SECSuccess); loser: - return(SECFailure); + return (SECFailure); } static SECStatus DecodeDBSubjectEntry(certDBEntrySubject *entry, SECItem *dbentry, - const SECItem *derSubject) + const SECItem *derSubject) { - PLArenaPool *arena = entry->common.arena; + PLArenaPool *arena = entry->common.arena; unsigned char *tmpbuf; unsigned char *end; - void *mark = PORT_ArenaMark(arena); + void *mark = PORT_ArenaMark(arena); unsigned int eaddrlen; unsigned int i; unsigned int keyidoff; unsigned int len; - unsigned int ncerts = 0; + unsigned int ncerts = 0; unsigned int nnlen; SECStatus rv; rv = SECITEM_CopyItem(arena, &entry->derSubject, derSubject); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* is record long enough for header? */ - if ( dbentry->len < DB_SUBJECT_ENTRY_HEADER_LEN ) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - entry->ncerts = ncerts = (( dbentry->data[0] << 8 ) | dbentry->data[1] ); - nnlen = (( dbentry->data[2] << 8 ) | dbentry->data[3] ); - eaddrlen = (( dbentry->data[4] << 8 ) | dbentry->data[5] ); + if (dbentry->len < DB_SUBJECT_ENTRY_HEADER_LEN) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + + entry->ncerts = ncerts = ((dbentry->data[0] << 8) | dbentry->data[1]); + nnlen = ((dbentry->data[2] << 8) | dbentry->data[3]); + eaddrlen = ((dbentry->data[4] << 8) | dbentry->data[5]); keyidoff = DB_SUBJECT_ENTRY_HEADER_LEN + nnlen + eaddrlen; len = keyidoff + (4 * ncerts); - if ( dbentry->len < len) { - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; + if (dbentry->len < len) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; } - + entry->certKeys = PORT_ArenaNewArray(arena, SECItem, ncerts); - entry->keyIDs = PORT_ArenaNewArray(arena, SECItem, ncerts); - if ( ( entry->certKeys == NULL ) || ( entry->keyIDs == NULL ) ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - - if ( nnlen > 1 ) { /* null terminator is stored */ - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->nickname, - &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN], - nnlen); + entry->keyIDs = PORT_ArenaNewArray(arena, SECItem, ncerts); + if ((entry->certKeys == NULL) || (entry->keyIDs == NULL)) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + + if (nnlen > 1) { /* null terminator is stored */ + entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); + if (entry->nickname == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->nickname, + &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN], + nnlen); } else { - entry->nickname = NULL; + entry->nickname = NULL; } - /* if we have an old style email entry, there is only one */ + /* if we have an old style email entry, there is only one */ entry->nemailAddrs = 0; - if ( eaddrlen > 1 ) { /* null terminator is stored */ - entry->emailAddrs = PORT_ArenaNewArray(arena, char *, 2); - if ( entry->emailAddrs == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - entry->emailAddrs[0] = (char *)PORT_ArenaAlloc(arena, eaddrlen); - if ( entry->emailAddrs[0] == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->emailAddrs[0], - &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN+nnlen], - eaddrlen); - entry->nemailAddrs = 1; + if (eaddrlen > 1) { /* null terminator is stored */ + entry->emailAddrs = PORT_ArenaNewArray(arena, char *, 2); + if (entry->emailAddrs == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + entry->emailAddrs[0] = (char *)PORT_ArenaAlloc(arena, eaddrlen); + if (entry->emailAddrs[0] == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->emailAddrs[0], + &dbentry->data[DB_SUBJECT_ENTRY_HEADER_LEN + nnlen], + eaddrlen); + entry->nemailAddrs = 1; } else { - entry->emailAddrs = NULL; + entry->emailAddrs = NULL; } - + /* collect the lengths of the certKeys and keyIDs, and total the * overall length. */ tmpbuf = &dbentry->data[keyidoff]; - for ( i = 0; i < ncerts; i++ ) { - unsigned int itemlen = ( tmpbuf[0] << 8 ) | tmpbuf[1]; + for (i = 0; i < ncerts; i++) { + unsigned int itemlen = (tmpbuf[0] << 8) | tmpbuf[1]; entry->certKeys[i].len = itemlen; len += itemlen; tmpbuf += 2; } - for ( i = 0; i < ncerts; i++ ) { - unsigned int itemlen = ( tmpbuf[0] << 8 ) | tmpbuf[1] ; + for (i = 0; i < ncerts; i++) { + unsigned int itemlen = (tmpbuf[0] << 8) | tmpbuf[1]; entry->keyIDs[i].len = itemlen; len += itemlen; tmpbuf += 2; } /* is encoded entry large enough ? */ - if ( len > dbentry->len ){ - PORT_SetError(SEC_ERROR_BAD_DATABASE); - goto loser; - } - - for ( i = 0; i < ncerts; i++ ) { - unsigned int kLen = entry->certKeys[i].len; - entry->certKeys[i].data = (unsigned char *)PORT_ArenaAlloc(arena, kLen); - if ( entry->certKeys[i].data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->certKeys[i].data, tmpbuf, kLen); - tmpbuf += kLen; - } - for ( i = 0; i < ncerts; i++ ) { - unsigned int iLen = entry->keyIDs[i].len; - entry->keyIDs[i].data = (unsigned char *)PORT_ArenaAlloc(arena, iLen); - if ( entry->keyIDs[i].data == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->keyIDs[i].data, tmpbuf, iLen); - tmpbuf += iLen; + if (len > dbentry->len) { + PORT_SetError(SEC_ERROR_BAD_DATABASE); + goto loser; + } + + for (i = 0; i < ncerts; i++) { + unsigned int kLen = entry->certKeys[i].len; + entry->certKeys[i].data = (unsigned char *)PORT_ArenaAlloc(arena, kLen); + if (entry->certKeys[i].data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->certKeys[i].data, tmpbuf, kLen); + tmpbuf += kLen; + } + for (i = 0; i < ncerts; i++) { + unsigned int iLen = entry->keyIDs[i].len; + entry->keyIDs[i].data = (unsigned char *)PORT_ArenaAlloc(arena, iLen); + if (entry->keyIDs[i].data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->keyIDs[i].data, tmpbuf, iLen); + tmpbuf += iLen; } end = dbentry->data + dbentry->len; if ((eaddrlen == 0) && (end - tmpbuf > 1)) { - /* read in the additional email addresses */ - entry->nemailAddrs = (((unsigned int)tmpbuf[0]) << 8) | tmpbuf[1]; - tmpbuf += 2; - if (end - tmpbuf < 2 * (int)entry->nemailAddrs) - goto loser; - entry->emailAddrs = PORT_ArenaNewArray(arena, char *, entry->nemailAddrs); - if (entry->emailAddrs == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - for (i=0; i < entry->nemailAddrs; i++) { - int nameLen; - if (end - tmpbuf < 2) { - goto loser; - } - nameLen = (((int)tmpbuf[0]) << 8) | tmpbuf[1]; - tmpbuf += 2; - if (end - tmpbuf < nameLen) { - goto loser; - } - entry->emailAddrs[i] = PORT_ArenaAlloc(arena,nameLen); - if (entry->emailAddrs == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - PORT_Memcpy(entry->emailAddrs[i], tmpbuf, nameLen); - tmpbuf += nameLen; - } - if (tmpbuf != end) - goto loser; + /* read in the additional email addresses */ + entry->nemailAddrs = (((unsigned int)tmpbuf[0]) << 8) | tmpbuf[1]; + tmpbuf += 2; + if (end - tmpbuf < 2 * (int)entry->nemailAddrs) + goto loser; + entry->emailAddrs = PORT_ArenaNewArray(arena, char *, entry->nemailAddrs); + if (entry->emailAddrs == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + for (i = 0; i < entry->nemailAddrs; i++) { + int nameLen; + if (end - tmpbuf < 2) { + goto loser; + } + nameLen = (((int)tmpbuf[0]) << 8) | tmpbuf[1]; + tmpbuf += 2; + if (end - tmpbuf < nameLen) { + goto loser; + } + entry->emailAddrs[i] = PORT_ArenaAlloc(arena, nameLen); + if (entry->emailAddrs == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PORT_Memcpy(entry->emailAddrs[i], tmpbuf, nameLen); + tmpbuf += nameLen; + } + if (tmpbuf != end) + goto loser; } PORT_ArenaUnmark(arena, mark); - return(SECSuccess); + return (SECSuccess); loser: PORT_ArenaRelease(arena, mark); /* discard above allocations */ - return(SECFailure); + return (SECFailure); } /* @@ -2419,25 +2414,25 @@ loser: */ static certDBEntrySubject * NewDBSubjectEntry(SECItem *derSubject, SECItem *certKey, - SECItem *keyID, char *nickname, char *emailAddr, - unsigned int flags) + SECItem *keyID, char *nickname, char *emailAddr, + unsigned int flags) { PLArenaPool *arena = NULL; certDBEntrySubject *entry; SECStatus rv; unsigned int nnlen; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry = (certDBEntrySubject *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySubject)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntrySubject)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } /* init common fields */ @@ -2448,72 +2443,72 @@ NewDBSubjectEntry(SECItem *derSubject, SECItem *certKey, /* copy the subject */ rv = SECITEM_CopyItem(arena, &entry->derSubject, derSubject); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + entry->ncerts = 1; entry->nemailAddrs = 0; /* copy nickname */ - if ( nickname && ( *nickname != '\0' ) ) { - nnlen = PORT_Strlen(nickname) + 1; - entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); - if ( entry->nickname == NULL ) { - goto loser; - } - - PORT_Memcpy(entry->nickname, nickname, nnlen); + if (nickname && (*nickname != '\0')) { + nnlen = PORT_Strlen(nickname) + 1; + entry->nickname = (char *)PORT_ArenaAlloc(arena, nnlen); + if (entry->nickname == NULL) { + goto loser; + } + + PORT_Memcpy(entry->nickname, nickname, nnlen); } else { - entry->nickname = NULL; + entry->nickname = NULL; } - + /* copy email addr */ - if ( emailAddr && ( *emailAddr != '\0' ) ) { - emailAddr = nsslowcert_FixupEmailAddr(emailAddr); - if ( emailAddr == NULL ) { - entry->emailAddrs = NULL; - goto loser; - } - - entry->emailAddrs = (char **)PORT_ArenaAlloc(arena, sizeof(char *)); - if ( entry->emailAddrs == NULL ) { - PORT_Free(emailAddr); - goto loser; - } - entry->emailAddrs[0] = PORT_ArenaStrdup(arena,emailAddr); - if (entry->emailAddrs[0]) { - entry->nemailAddrs = 1; - } - - PORT_Free(emailAddr); + if (emailAddr && (*emailAddr != '\0')) { + emailAddr = nsslowcert_FixupEmailAddr(emailAddr); + if (emailAddr == NULL) { + entry->emailAddrs = NULL; + goto loser; + } + + entry->emailAddrs = (char **)PORT_ArenaAlloc(arena, sizeof(char *)); + if (entry->emailAddrs == NULL) { + PORT_Free(emailAddr); + goto loser; + } + entry->emailAddrs[0] = PORT_ArenaStrdup(arena, emailAddr); + if (entry->emailAddrs[0]) { + entry->nemailAddrs = 1; + } + + PORT_Free(emailAddr); } else { - entry->emailAddrs = NULL; + entry->emailAddrs = NULL; } - + /* allocate space for certKeys and keyIDs */ entry->certKeys = (SECItem *)PORT_ArenaAlloc(arena, sizeof(SECItem)); entry->keyIDs = (SECItem *)PORT_ArenaAlloc(arena, sizeof(SECItem)); - if ( ( entry->certKeys == NULL ) || ( entry->keyIDs == NULL ) ) { - goto loser; + if ((entry->certKeys == NULL) || (entry->keyIDs == NULL)) { + goto loser; } /* copy the certKey and keyID */ rv = SECITEM_CopyItem(arena, &entry->certKeys[0], certKey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } rv = SECITEM_CopyItem(arena, &entry->keyIDs[0], keyID); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - - return(entry); + + return (entry); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -2525,31 +2520,31 @@ DeleteDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, SECItem *derSubject) SECItem dbkey; PLArenaPool *arena = NULL; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } - + rv = EncodeDBSubjectKey(derSubject, arena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = DeleteDBEntry(handle, certDBEntryTypeSubject, &dbkey); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } PORT_FreeArena(arena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(SECFailure); + + return (SECFailure); } /* @@ -2558,61 +2553,57 @@ loser: static certDBEntrySubject * ReadDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, SECItem *derSubject) { + /* |arena| isn't function-bounded, so cannot be a PORTCheapArenaPool. */ PLArenaPool *arena = NULL; - PLArenaPool *tmparena = NULL; + PORTCheapArenaPool tmpArena; + certDBEntrySubject *entry; SECItem dbkey; SECItem dbentry; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; - } - + PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE); + entry = (certDBEntrySubject *)PORT_ArenaAlloc(arena, - sizeof(certDBEntrySubject)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntrySubject)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = certDBEntryTypeSubject; - rv = EncodeDBSubjectKey(derSubject, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + rv = EncodeDBSubjectKey(derSubject, &tmpArena.arena, &dbkey); + if (rv != SECSuccess) { + goto loser; } - - rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); - if ( rv == SECFailure ) { - goto loser; + + rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, &tmpArena.arena); + if (rv == SECFailure) { + goto loser; } rv = DecodeDBSubjectEntry(entry, &dbentry, derSubject); - if ( rv == SECFailure ) { - goto loser; + if (rv == SECFailure) { + goto loser; } - - PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - + + PORT_DestroyCheapArena(&tmpArena); + return (entry); + loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); - } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + PORT_DestroyCheapArena(&tmpArena); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -2625,114 +2616,116 @@ WriteDBSubjectEntry(NSSLOWCERTCertDBHandle *handle, certDBEntrySubject *entry) SECItem dbitem, dbkey; PLArenaPool *tmparena = NULL; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } - + rv = EncodeDBSubjectEntry(entry, tmparena, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + rv = EncodeDBSubjectKey(&entry->derSubject, tmparena, &dbkey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); - + return (SECFailure); } -typedef enum { nsslowcert_remove, nsslowcert_add } nsslowcertUpdateType; +typedef enum { nsslowcert_remove, + nsslowcert_add } nsslowcertUpdateType; static SECStatus -nsslowcert_UpdateSubjectEmailAddr(NSSLOWCERTCertDBHandle *dbhandle, - SECItem *derSubject, char *emailAddr, nsslowcertUpdateType updateType) +nsslowcert_UpdateSubjectEmailAddr(NSSLOWCERTCertDBHandle *dbhandle, + SECItem *derSubject, char *emailAddr, nsslowcertUpdateType updateType) { certDBEntrySubject *entry = NULL; int index = -1, i; SECStatus rv; - - if (emailAddr) { - emailAddr = nsslowcert_FixupEmailAddr(emailAddr); - if (emailAddr == NULL) { - return SECFailure; - } + + if (emailAddr) { + emailAddr = nsslowcert_FixupEmailAddr(emailAddr); + if (emailAddr == NULL) { + return SECFailure; + } } else { - return SECSuccess; + return SECSuccess; } - entry = ReadDBSubjectEntry(dbhandle,derSubject); + entry = ReadDBSubjectEntry(dbhandle, derSubject); if (entry == NULL) { - rv = SECFailure; - goto done; - } + rv = SECFailure; + goto done; + } - for (i=0; i < (int)(entry->nemailAddrs); i++) { - if (PORT_Strcmp(entry->emailAddrs[i],emailAddr) == 0) { - index = i; - } + for (i = 0; i < (int)(entry->nemailAddrs); i++) { + if (PORT_Strcmp(entry->emailAddrs[i], emailAddr) == 0) { + index = i; + } } if (updateType == nsslowcert_remove) { - if (index == -1) { - rv = SECSuccess; - goto done; - } - entry->nemailAddrs--; - for (i=index; i < (int)(entry->nemailAddrs); i++) { - entry->emailAddrs[i] = entry->emailAddrs[i+1]; - } + if (index == -1) { + rv = SECSuccess; + goto done; + } + entry->nemailAddrs--; + for (i = index; i < (int)(entry->nemailAddrs); i++) { + entry->emailAddrs[i] = entry->emailAddrs[i + 1]; + } } else { - char **newAddrs = NULL; - - if (index != -1) { - rv = SECSuccess; - goto done; - } - newAddrs = (char **)PORT_ArenaAlloc(entry->common.arena, - (entry->nemailAddrs+1)* sizeof(char *)); - if (!newAddrs) { - rv = SECFailure; - goto done; - } - for (i=0; i < (int)(entry->nemailAddrs); i++) { - newAddrs[i] = entry->emailAddrs[i]; - } - newAddrs[entry->nemailAddrs] = - PORT_ArenaStrdup(entry->common.arena,emailAddr); - if (!newAddrs[entry->nemailAddrs]) { - rv = SECFailure; - goto done; - } - entry->emailAddrs = newAddrs; - entry->nemailAddrs++; - } - + char **newAddrs = NULL; + + if (index != -1) { + rv = SECSuccess; + goto done; + } + newAddrs = (char **)PORT_ArenaAlloc(entry->common.arena, + (entry->nemailAddrs + 1) * sizeof(char *)); + if (!newAddrs) { + rv = SECFailure; + goto done; + } + for (i = 0; i < (int)(entry->nemailAddrs); i++) { + newAddrs[i] = entry->emailAddrs[i]; + } + newAddrs[entry->nemailAddrs] = + PORT_ArenaStrdup(entry->common.arena, emailAddr); + if (!newAddrs[entry->nemailAddrs]) { + rv = SECFailure; + goto done; + } + entry->emailAddrs = newAddrs; + entry->nemailAddrs++; + } + /* delete the subject entry */ DeleteDBSubjectEntry(dbhandle, derSubject); /* write the new one */ rv = WriteDBSubjectEntry(dbhandle, entry); - done: - if (entry) DestroyDBEntry((certDBEntry *)entry); - if (emailAddr) PORT_Free(emailAddr); +done: + if (entry) + DestroyDBEntry((certDBEntry *)entry); + if (emailAddr) + PORT_Free(emailAddr); return rv; } @@ -2742,45 +2735,47 @@ nsslowcert_UpdateSubjectEmailAddr(NSSLOWCERTCertDBHandle *dbhandle, */ static SECStatus AddNicknameToSubject(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) + NSSLOWCERTCertificate *cert, char *nickname) { certDBEntrySubject *entry; SECStatus rv; - - if ( nickname == NULL ) { - return(SECFailure); + + if (nickname == NULL) { + return (SECFailure); } - - entry = ReadDBSubjectEntry(dbhandle,&cert->derSubject); + + entry = ReadDBSubjectEntry(dbhandle, &cert->derSubject); PORT_Assert(entry != NULL); - if ( entry == NULL ) { - goto loser; + if (entry == NULL) { + goto loser; } - + PORT_Assert(entry->nickname == NULL); - if ( entry->nickname != NULL ) { - goto loser; + if (entry->nickname != NULL) { + goto loser; } - + entry->nickname = PORT_ArenaStrdup(entry->common.arena, nickname); - - if ( entry->nickname == NULL ) { - goto loser; + + if (entry->nickname == NULL) { + goto loser; } - + /* delete the subject entry */ DeleteDBSubjectEntry(dbhandle, &cert->derSubject); /* write the new one */ rv = WriteDBSubjectEntry(dbhandle, entry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - return(SECSuccess); + DestroyDBEntry((certDBEntry *)entry); + return (SECSuccess); loser: - return(SECFailure); + DestroyDBEntry((certDBEntry *)entry); + return (SECFailure); } /* @@ -2791,31 +2786,31 @@ NewDBVersionEntry(unsigned int flags) { PLArenaPool *arena = NULL; certDBEntryVersion *entry; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry = (certDBEntryVersion *)PORT_ArenaAlloc(arena, - sizeof(certDBEntryVersion)); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + sizeof(certDBEntryVersion)); + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = certDBEntryTypeVersion; entry->common.version = CERT_DB_FILE_VERSION; entry->common.flags = flags; - return(entry); + return (entry); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); + + return (NULL); } /* @@ -2830,23 +2825,23 @@ ReadDBVersionEntry(NSSLOWCERTCertDBHandle *handle) SECItem dbkey; SECItem dbentry; SECStatus rv; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (arena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (tmparena == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + entry = PORT_ArenaZNew(arena, certDBEntryVersion); - if ( entry == NULL ) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (entry == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } entry->common.arena = arena; entry->common.type = certDBEntryTypeVersion; @@ -2854,31 +2849,30 @@ ReadDBVersionEntry(NSSLOWCERTCertDBHandle *handle) /* now get the database key and format it */ dbkey.len = SEC_DB_VERSION_KEY_LEN + SEC_DB_KEY_HEADER_LEN; dbkey.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbkey.len); - if ( dbkey.data == NULL ) { - goto loser; + if (dbkey.data == NULL) { + goto loser; } PORT_Memcpy(&dbkey.data[SEC_DB_KEY_HEADER_LEN], SEC_DB_VERSION_KEY, - SEC_DB_VERSION_KEY_LEN); + SEC_DB_VERSION_KEY_LEN); rv = ReadDBEntry(handle, &entry->common, &dbkey, &dbentry, tmparena); if (rv != SECSuccess) { - goto loser; + goto loser; } PORT_FreeArena(tmparena, PR_FALSE); - return(entry); - + return (entry); + loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(NULL); -} + return (NULL); +} /* * Encode a version entry into byte stream suitable for @@ -2890,46 +2884,46 @@ WriteDBVersionEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryVersion *entry) SECItem dbitem, dbkey; PLArenaPool *tmparena = NULL; SECStatus rv; - + tmparena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( tmparena == NULL ) { - goto loser; + if (tmparena == NULL) { + goto loser; } - + /* allocate space for encoded database record, including space * for low level header */ dbitem.len = SEC_DB_ENTRY_HEADER_LEN; - + dbitem.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbitem.len); - if ( dbitem.data == NULL) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - goto loser; + if (dbitem.data == NULL) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; } - + /* now get the database key and format it */ dbkey.len = SEC_DB_VERSION_KEY_LEN + SEC_DB_KEY_HEADER_LEN; dbkey.data = (unsigned char *)PORT_ArenaAlloc(tmparena, dbkey.len); - if ( dbkey.data == NULL ) { - goto loser; + if (dbkey.data == NULL) { + goto loser; } PORT_Memcpy(&dbkey.data[SEC_DB_KEY_HEADER_LEN], SEC_DB_VERSION_KEY, - SEC_DB_VERSION_KEY_LEN); + SEC_DB_VERSION_KEY_LEN); /* now write it to the database */ rv = WriteDBEntry(handle, &entry->common, &dbkey, &dbitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + PORT_FreeArena(tmparena, PR_FALSE); - return(SECSuccess); + return (SECSuccess); loser: - if ( tmparena ) { - PORT_FreeArena(tmparena, PR_FALSE); + if (tmparena) { + PORT_FreeArena(tmparena, PR_FALSE); } - return(SECFailure); + return (SECFailure); } /* @@ -2941,243 +2935,242 @@ RemovePermSubjectNode(NSSLOWCERTCertificate *cert) certDBEntrySubject *entry; unsigned int i; SECStatus rv; - - entry = ReadDBSubjectEntry(cert->dbhandle,&cert->derSubject); - if ( entry == NULL ) { - return(SECFailure); + + entry = ReadDBSubjectEntry(cert->dbhandle, &cert->derSubject); + if (entry == NULL) { + return (SECFailure); } PORT_Assert(entry->ncerts); rv = SECFailure; - - if ( entry->ncerts > 1 ) { - for ( i = 0; i < entry->ncerts; i++ ) { - if ( SECITEM_CompareItem(&entry->certKeys[i], &cert->certKey) == - SECEqual ) { - /* copy rest of list forward one entry */ - for ( i = i + 1; i < entry->ncerts; i++ ) { - entry->certKeys[i-1] = entry->certKeys[i]; - entry->keyIDs[i-1] = entry->keyIDs[i]; - } - entry->ncerts--; - DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); - rv = WriteDBSubjectEntry(cert->dbhandle, entry); - break; - } - } + + if (entry->ncerts > 1) { + for (i = 0; i < entry->ncerts; i++) { + if (SECITEM_CompareItem(&entry->certKeys[i], &cert->certKey) == + SECEqual) { + /* copy rest of list forward one entry */ + for (i = i + 1; i < entry->ncerts; i++) { + entry->certKeys[i - 1] = entry->certKeys[i]; + entry->keyIDs[i - 1] = entry->keyIDs[i]; + } + entry->ncerts--; + DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); + rv = WriteDBSubjectEntry(cert->dbhandle, entry); + break; + } + } } else { - /* no entries left, delete the perm entry in the DB */ - if ( entry->emailAddrs ) { - /* if the subject had an email record, then delete it too */ - for (i=0; i < entry->nemailAddrs; i++) { - DeleteDBSMimeEntry(cert->dbhandle, entry->emailAddrs[i]); - } - } - if ( entry->nickname ) { - DeleteDBNicknameEntry(cert->dbhandle, entry->nickname); - } - - DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); + /* no entries left, delete the perm entry in the DB */ + if (entry->emailAddrs) { + /* if the subject had an email record, then delete it too */ + for (i = 0; i < entry->nemailAddrs; i++) { + DeleteDBSMimeEntry(cert->dbhandle, entry->emailAddrs[i]); + } + } + if (entry->nickname) { + DeleteDBNicknameEntry(cert->dbhandle, entry->nickname); + } + + DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); } DestroyDBEntry((certDBEntry *)entry); - return(rv); + return (rv); } /* * add a cert to the perm subject list */ static SECStatus -AddPermSubjectNode(certDBEntrySubject *entry, NSSLOWCERTCertificate *cert, - char *nickname) +AddPermSubjectNode(certDBEntrySubject *entry, NSSLOWCERTCertificate *cert, + char *nickname) { SECItem *newCertKeys, *newKeyIDs; unsigned int i, new_i; SECStatus rv; unsigned int ncerts; - PORT_Assert(entry); + PORT_Assert(entry); ncerts = entry->ncerts; - - if ( nickname && entry->nickname ) { - /* nicknames must be the same */ - PORT_Assert(PORT_Strcmp(nickname, entry->nickname) == 0); + + if (nickname && entry->nickname) { + /* nicknames must be the same */ + PORT_Assert(PORT_Strcmp(nickname, entry->nickname) == 0); } - if ( ( entry->nickname == NULL ) && ( nickname != NULL ) ) { - /* copy nickname into the entry */ - entry->nickname = PORT_ArenaStrdup(entry->common.arena, nickname); - if ( entry->nickname == NULL ) { - return(SECFailure); - } + if ((entry->nickname == NULL) && (nickname != NULL)) { + /* copy nickname into the entry */ + entry->nickname = PORT_ArenaStrdup(entry->common.arena, nickname); + if (entry->nickname == NULL) { + return (SECFailure); + } } - + /* a DB entry already exists, so add this cert */ newCertKeys = PORT_ArenaZNewArray(entry->common.arena, SECItem, ncerts + 1); - newKeyIDs = PORT_ArenaZNewArray(entry->common.arena, SECItem, ncerts + 1); + newKeyIDs = PORT_ArenaZNewArray(entry->common.arena, SECItem, ncerts + 1); - if ( ( newCertKeys == NULL ) || ( newKeyIDs == NULL ) ) { - return(SECFailure); + if ((newCertKeys == NULL) || (newKeyIDs == NULL)) { + return (SECFailure); } /* Step 1: copy certs older than "cert" into new entry. */ - for ( i = 0, new_i=0; i < ncerts; i++ ) { - NSSLOWCERTCertificate *cmpcert; - PRBool isNewer; - cmpcert = nsslowcert_FindCertByKey(cert->dbhandle, - &entry->certKeys[i]); - /* The entry has been corrupted, remove it from the list */ - if (!cmpcert) { - continue; - } - - isNewer = nsslowcert_IsNewer(cert, cmpcert); - nsslowcert_DestroyCertificate(cmpcert); - if ( isNewer ) - break; - /* copy this cert entry */ - newCertKeys[new_i] = entry->certKeys[i]; - newKeyIDs[new_i] = entry->keyIDs[i]; - new_i++; + for (i = 0, new_i = 0; i < ncerts; i++) { + NSSLOWCERTCertificate *cmpcert; + PRBool isNewer; + cmpcert = nsslowcert_FindCertByKey(cert->dbhandle, + &entry->certKeys[i]); + /* The entry has been corrupted, remove it from the list */ + if (!cmpcert) { + continue; + } + + isNewer = nsslowcert_IsNewer(cert, cmpcert); + nsslowcert_DestroyCertificate(cmpcert); + if (isNewer) + break; + /* copy this cert entry */ + newCertKeys[new_i] = entry->certKeys[i]; + newKeyIDs[new_i] = entry->keyIDs[i]; + new_i++; } /* Step 2: Add "cert" to the entry. */ rv = SECITEM_CopyItem(entry->common.arena, &newCertKeys[new_i], - &cert->certKey); - if ( rv != SECSuccess ) { - return(SECFailure); + &cert->certKey); + if (rv != SECSuccess) { + return (SECFailure); } rv = SECITEM_CopyItem(entry->common.arena, &newKeyIDs[new_i], - &cert->subjectKeyID); - if ( rv != SECSuccess ) { - return(SECFailure); + &cert->subjectKeyID); + if (rv != SECSuccess) { + return (SECFailure); } new_i++; /* Step 3: copy remaining certs (if any) from old entry to new. */ - for ( ; i < ncerts; i++ ,new_i++) { - newCertKeys[new_i] = entry->certKeys[i]; - newKeyIDs[new_i] = entry->keyIDs[i]; + for (; i < ncerts; i++, new_i++) { + newCertKeys[new_i] = entry->certKeys[i]; + newKeyIDs[new_i] = entry->keyIDs[i]; } /* update certKeys and keyIDs */ entry->certKeys = newCertKeys; - entry->keyIDs = newKeyIDs; + entry->keyIDs = newKeyIDs; /* set new count value */ entry->ncerts = new_i; DeleteDBSubjectEntry(cert->dbhandle, &cert->derSubject); rv = WriteDBSubjectEntry(cert->dbhandle, entry); - return(rv); + return (rv); } - SECStatus nsslowcert_TraversePermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject, - NSSLOWCERTCertCallback cb, void *cbarg) + SECItem *derSubject, + NSSLOWCERTCertCallback cb, void *cbarg) { certDBEntrySubject *entry; unsigned int i; NSSLOWCERTCertificate *cert; SECStatus rv = SECSuccess; - + entry = ReadDBSubjectEntry(handle, derSubject); - if ( entry == NULL ) { - return(SECFailure); + if (entry == NULL) { + return (SECFailure); } - - for( i = 0; i < entry->ncerts; i++ ) { - cert = nsslowcert_FindCertByKey(handle, &entry->certKeys[i]); - if (!cert) { - continue; - } - rv = (* cb)(cert, cbarg); - nsslowcert_DestroyCertificate(cert); - if ( rv == SECFailure ) { - break; - } + + for (i = 0; i < entry->ncerts; i++) { + cert = nsslowcert_FindCertByKey(handle, &entry->certKeys[i]); + if (!cert) { + continue; + } + rv = (*cb)(cert, cbarg); + nsslowcert_DestroyCertificate(cert); + if (rv == SECFailure) { + break; + } } DestroyDBEntry((certDBEntry *)entry); - return(rv); + return (rv); } int nsslowcert_NumPermCertsForSubject(NSSLOWCERTCertDBHandle *handle, - SECItem *derSubject) + SECItem *derSubject) { certDBEntrySubject *entry; int ret; - + entry = ReadDBSubjectEntry(handle, derSubject); - if ( entry == NULL ) { - return(SECFailure); + if (entry == NULL) { + return (SECFailure); } ret = entry->ncerts; - + DestroyDBEntry((certDBEntry *)entry); - - return(ret); + + return (ret); } SECStatus nsslowcert_TraversePermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname, NSSLOWCERTCertCallback cb, void *cbarg) + char *nickname, NSSLOWCERTCertCallback cb, void *cbarg) { certDBEntryNickname *nnentry = NULL; certDBEntrySMime *smentry = NULL; SECStatus rv; SECItem *derSubject = NULL; - + nnentry = ReadDBNicknameEntry(handle, nickname); - if ( nnentry ) { - derSubject = &nnentry->subjectName; + if (nnentry) { + derSubject = &nnentry->subjectName; } else { - smentry = nsslowcert_ReadDBSMimeEntry(handle, nickname); - if ( smentry ) { - derSubject = &smentry->subjectName; - } - } - - if ( derSubject ) { - rv = nsslowcert_TraversePermCertsForSubject(handle, derSubject, - cb, cbarg); + smentry = nsslowcert_ReadDBSMimeEntry(handle, nickname); + if (smentry) { + derSubject = &smentry->subjectName; + } + } + + if (derSubject) { + rv = nsslowcert_TraversePermCertsForSubject(handle, derSubject, + cb, cbarg); } else { - rv = SECFailure; + rv = SECFailure; } - if ( nnentry ) { - DestroyDBEntry((certDBEntry *)nnentry); + if (nnentry) { + DestroyDBEntry((certDBEntry *)nnentry); } - if ( smentry ) { - DestroyDBEntry((certDBEntry *)smentry); + if (smentry) { + DestroyDBEntry((certDBEntry *)smentry); } - - return(rv); + + return (rv); } int -nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, - char *nickname) +nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, + char *nickname) { certDBEntryNickname *entry; int ret; - + entry = ReadDBNicknameEntry(handle, nickname); - - if ( entry ) { - ret = nsslowcert_NumPermCertsForSubject(handle, &entry->subjectName); - DestroyDBEntry((certDBEntry *)entry); + + if (entry) { + ret = nsslowcert_NumPermCertsForSubject(handle, &entry->subjectName); + DestroyDBEntry((certDBEntry *)entry); } else { - ret = 0; + ret = 0; } - return(ret); + return (ret); } /* @@ -3185,36 +3178,36 @@ nsslowcert_NumPermCertsForNickname(NSSLOWCERTCertDBHandle *handle, */ static SECStatus AddNicknameToPermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) + NSSLOWCERTCertificate *cert, char *nickname) { certDBEntryCert *entry; int rv; entry = cert->dbEntry; PORT_Assert(entry != NULL); - if ( entry == NULL ) { - goto loser; + if (entry == NULL) { + goto loser; } - pkcs11_freeNickname(entry->nickname,entry->nicknameSpace); + pkcs11_freeNickname(entry->nickname, entry->nicknameSpace); entry->nickname = NULL; - entry->nickname = pkcs11_copyNickname(nickname,entry->nicknameSpace, - sizeof(entry->nicknameSpace)); + entry->nickname = pkcs11_copyNickname(nickname, entry->nicknameSpace, + sizeof(entry->nicknameSpace)); rv = WriteDBCertEntry(dbhandle, entry); - if ( rv ) { - goto loser; + if (rv) { + goto loser; } - pkcs11_freeNickname(cert->nickname,cert->nicknameSpace); + pkcs11_freeNickname(cert->nickname, cert->nicknameSpace); cert->nickname = NULL; - cert->nickname = pkcs11_copyNickname(nickname,cert->nicknameSpace, - sizeof(cert->nicknameSpace)); + cert->nickname = pkcs11_copyNickname(nickname, cert->nicknameSpace, + sizeof(cert->nicknameSpace)); + + return (SECSuccess); - return(SECSuccess); - loser: - return(SECFailure); + return (SECFailure); } /* @@ -3223,75 +3216,76 @@ loser: */ SECStatus nsslowcert_AddPermNickname(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname) + NSSLOWCERTCertificate *cert, char *nickname) { SECStatus rv = SECFailure; certDBEntrySubject *entry = NULL; certDBEntryNickname *nicknameEntry = NULL; - + nsslowcert_LockDB(dbhandle); entry = ReadDBSubjectEntry(dbhandle, &cert->derSubject); - if (entry == NULL) goto loser; - - if ( entry->nickname == NULL ) { - - /* no nickname for subject */ - rv = AddNicknameToSubject(dbhandle, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - rv = AddNicknameToPermCert(dbhandle, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } - nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } - - rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } + if (entry == NULL) + goto loser; + + if (entry->nickname == NULL) { + + /* no nickname for subject */ + rv = AddNicknameToSubject(dbhandle, cert, nickname); + if (rv != SECSuccess) { + goto loser; + } + rv = AddNicknameToPermCert(dbhandle, cert, nickname); + if (rv != SECSuccess) { + goto loser; + } + nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); + if (nicknameEntry == NULL) { + goto loser; + } + + rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); + if (rv != SECSuccess) { + goto loser; + } } else { - /* subject already has a nickname */ - rv = AddNicknameToPermCert(dbhandle, cert, entry->nickname); - if ( rv != SECSuccess ) { - goto loser; - } - /* make sure nickname entry exists. If the database was corrupted, - * we may have lost the nickname entry. Add it back now */ - nicknameEntry = ReadDBNicknameEntry(dbhandle, entry->nickname); - if (nicknameEntry == NULL ) { - nicknameEntry = NewDBNicknameEntry(entry->nickname, - &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } - - rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } + /* subject already has a nickname */ + rv = AddNicknameToPermCert(dbhandle, cert, entry->nickname); + if (rv != SECSuccess) { + goto loser; + } + /* make sure nickname entry exists. If the database was corrupted, + * we may have lost the nickname entry. Add it back now */ + nicknameEntry = ReadDBNicknameEntry(dbhandle, entry->nickname); + if (nicknameEntry == NULL) { + nicknameEntry = NewDBNicknameEntry(entry->nickname, + &cert->derSubject, 0); + if (nicknameEntry == NULL) { + goto loser; + } + + rv = WriteDBNicknameEntry(dbhandle, nicknameEntry); + if (rv != SECSuccess) { + goto loser; + } + } } rv = SECSuccess; loser: if (entry) { - DestroyDBEntry((certDBEntry *)entry); + DestroyDBEntry((certDBEntry *)entry); } if (nicknameEntry) { - DestroyDBEntry((certDBEntry *)nicknameEntry); + DestroyDBEntry((certDBEntry *)nicknameEntry); } nsslowcert_UnlockDB(dbhandle); - return(rv); + return (rv); } static certDBEntryCert * AddCertToPermDB(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTCertificate *cert, - char *nickname, NSSLOWCERTCertTrust *trust) + char *nickname, NSSLOWCERTCertTrust *trust) { certDBEntryCert *certEntry = NULL; certDBEntryNickname *nicknameEntry = NULL; @@ -3300,103 +3294,103 @@ AddCertToPermDB(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTCertificate *cert, SECStatus rv; PRBool donnentry = PR_FALSE; - if ( nickname ) { - donnentry = PR_TRUE; + if (nickname) { + donnentry = PR_TRUE; } subjectEntry = ReadDBSubjectEntry(handle, &cert->derSubject); - - if ( subjectEntry && subjectEntry->nickname ) { - donnentry = PR_FALSE; - nickname = subjectEntry->nickname; + + if (subjectEntry && subjectEntry->nickname) { + donnentry = PR_FALSE; + nickname = subjectEntry->nickname; } - + certEntry = NewDBCertEntry(&cert->derCert, nickname, trust, 0); - if ( certEntry == NULL ) { - goto loser; + if (certEntry == NULL) { + goto loser; } - - if ( donnentry ) { - nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); - if ( nicknameEntry == NULL ) { - goto loser; - } + + if (donnentry) { + nicknameEntry = NewDBNicknameEntry(nickname, &cert->derSubject, 0); + if (nicknameEntry == NULL) { + goto loser; + } } - + rv = WriteDBCertEntry(handle, certEntry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } state = 1; - - if ( nicknameEntry ) { - rv = WriteDBNicknameEntry(handle, nicknameEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } - + + if (nicknameEntry) { + rv = WriteDBNicknameEntry(handle, nicknameEntry); + if (rv != SECSuccess) { + goto loser; + } + } + state = 2; /* "Change" handles if necessary */ cert->dbhandle = handle; - + /* add to or create new subject entry */ - if ( subjectEntry ) { - /* REWRITE BASED ON SUBJECT ENTRY */ - rv = AddPermSubjectNode(subjectEntry, cert, nickname); - if ( rv != SECSuccess ) { - goto loser; - } + if (subjectEntry) { + /* REWRITE BASED ON SUBJECT ENTRY */ + rv = AddPermSubjectNode(subjectEntry, cert, nickname); + if (rv != SECSuccess) { + goto loser; + } } else { - /* make a new subject entry - this case is only used when updating - * an old version of the database. This is OK because the oldnickname - * db format didn't allow multiple certs with the same subject. - */ - /* where does subjectKeyID and certKey come from? */ - subjectEntry = NewDBSubjectEntry(&cert->derSubject, &cert->certKey, - &cert->subjectKeyID, nickname, - NULL, 0); - if ( subjectEntry == NULL ) { - goto loser; - } - rv = WriteDBSubjectEntry(handle, subjectEntry); - if ( rv != SECSuccess ) { - goto loser; - } - } - + /* make a new subject entry - this case is only used when updating + * an old version of the database. This is OK because the oldnickname + * db format didn't allow multiple certs with the same subject. + */ + /* where does subjectKeyID and certKey come from? */ + subjectEntry = NewDBSubjectEntry(&cert->derSubject, &cert->certKey, + &cert->subjectKeyID, nickname, + NULL, 0); + if (subjectEntry == NULL) { + goto loser; + } + rv = WriteDBSubjectEntry(handle, subjectEntry); + if (rv != SECSuccess) { + goto loser; + } + } + state = 3; - - if ( nicknameEntry ) { - DestroyDBEntry((certDBEntry *)nicknameEntry); + + if (nicknameEntry) { + DestroyDBEntry((certDBEntry *)nicknameEntry); } - - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); + + if (subjectEntry) { + DestroyDBEntry((certDBEntry *)subjectEntry); } - return(certEntry); + return (certEntry); loser: /* don't leave partial entry in the database */ - if ( state > 0 ) { - DeleteDBCertEntry(handle, &cert->certKey); + if (state > 0) { + DeleteDBCertEntry(handle, &cert->certKey); } - if ( ( state > 1 ) && donnentry ) { - DeleteDBNicknameEntry(handle, nickname); + if ((state > 1) && donnentry) { + DeleteDBNicknameEntry(handle, nickname); } - if ( certEntry ) { - DestroyDBEntry((certDBEntry *)certEntry); + if (certEntry) { + DestroyDBEntry((certDBEntry *)certEntry); } - if ( nicknameEntry ) { - DestroyDBEntry((certDBEntry *)nicknameEntry); + if (nicknameEntry) { + DestroyDBEntry((certDBEntry *)nicknameEntry); } - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); + if (subjectEntry) { + DestroyDBEntry((certDBEntry *)subjectEntry); } - return(NULL); + return (NULL); } /* forward declaration */ @@ -3413,10 +3407,9 @@ UpdateV7DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb); static SECStatus UpdateV8DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) { - return UpdateV7DB(handle,updatedb); + return UpdateV7DB(handle, updatedb); } - /* * we could just blindly sequence through reading key data pairs and writing * them back out, but some cert.db's have gotten quite large and may have some @@ -3437,128 +3430,128 @@ UpdateV7DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) certDBEntrySMime smimeEntry; SECStatus rv; - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); + ret = (*updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + if (ret) { + return (SECFailure); } - + do { - unsigned char *dataBuf = (unsigned char *)data.data; - unsigned char *keyBuf = (unsigned char *)key.data; - dbEntry.data = &dataBuf[SEC_DB_ENTRY_HEADER_LEN]; - dbEntry.len = data.size - SEC_DB_ENTRY_HEADER_LEN; - entryType = (certDBEntryType) keyBuf[0]; - dbKey.data = &keyBuf[SEC_DB_KEY_HEADER_LEN]; - dbKey.len = key.size - SEC_DB_KEY_HEADER_LEN; - if ((dbEntry.len <= 0) || (dbKey.len <= 0)) { - continue; - } - - switch (entryType) { - /* these entries will get regenerated as we read the - * rest of the data from the database */ - case certDBEntryTypeVersion: - case certDBEntryTypeSubject: - case certDBEntryTypeContentVersion: - case certDBEntryTypeNickname: - /* smime profiles need entries created after the certs have - * been imported, loop over them in a second run */ - case certDBEntryTypeSMimeProfile: - break; - - case certDBEntryTypeCert: - /* decode Entry */ - certEntry.common.version = (unsigned int)dataBuf[0]; - certEntry.common.type = entryType; - certEntry.common.flags = (unsigned int)dataBuf[2]; - rv = DecodeDBCertEntry(&certEntry,&dbEntry); - if (rv != SECSuccess) { - break; - } - /* should we check for existing duplicates? */ - cert = nsslowcert_DecodeDERCertificate(&certEntry.derCert, - certEntry.nickname); - if (cert) { - nsslowcert_UpdatePermCert(handle, cert, certEntry.nickname, - &certEntry.trust); - nsslowcert_DestroyCertificate(cert); - } - /* free any data the decode may have allocated. */ - pkcs11_freeStaticData(certEntry.derCert.data, - certEntry.derCertSpace); - pkcs11_freeNickname(certEntry.nickname, certEntry.nicknameSpace); - break; - - case certDBEntryTypeKeyRevocation: - isKRL = PR_TRUE; - /* fall through */ - case certDBEntryTypeRevocation: - crlEntry.common.version = (unsigned int)dataBuf[0]; - crlEntry.common.type = entryType; - crlEntry.common.flags = (unsigned int)dataBuf[2]; - crlEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (crlEntry.common.arena == NULL) { - break; - } - rv = DecodeDBCrlEntry(&crlEntry,&dbEntry); - if (rv != SECSuccess) { - break; - } - nsslowcert_UpdateCrl(handle, &crlEntry.derCrl, &dbKey, - crlEntry.url, isKRL); - /* free data allocated by the decode */ - PORT_FreeArena(crlEntry.common.arena, PR_FALSE); - crlEntry.common.arena = NULL; - break; - - default: - break; - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); + unsigned char *dataBuf = (unsigned char *)data.data; + unsigned char *keyBuf = (unsigned char *)key.data; + dbEntry.data = &dataBuf[SEC_DB_ENTRY_HEADER_LEN]; + dbEntry.len = data.size - SEC_DB_ENTRY_HEADER_LEN; + entryType = (certDBEntryType)keyBuf[0]; + dbKey.data = &keyBuf[SEC_DB_KEY_HEADER_LEN]; + dbKey.len = key.size - SEC_DB_KEY_HEADER_LEN; + if ((dbEntry.len <= 0) || (dbKey.len <= 0)) { + continue; + } + + switch (entryType) { + /* these entries will get regenerated as we read the + * rest of the data from the database */ + case certDBEntryTypeVersion: + case certDBEntryTypeSubject: + case certDBEntryTypeContentVersion: + case certDBEntryTypeNickname: + /* smime profiles need entries created after the certs have + * been imported, loop over them in a second run */ + case certDBEntryTypeSMimeProfile: + break; + + case certDBEntryTypeCert: + /* decode Entry */ + certEntry.common.version = (unsigned int)dataBuf[0]; + certEntry.common.type = entryType; + certEntry.common.flags = (unsigned int)dataBuf[2]; + rv = DecodeDBCertEntry(&certEntry, &dbEntry); + if (rv != SECSuccess) { + break; + } + /* should we check for existing duplicates? */ + cert = nsslowcert_DecodeDERCertificate(&certEntry.derCert, + certEntry.nickname); + if (cert) { + nsslowcert_UpdatePermCert(handle, cert, certEntry.nickname, + &certEntry.trust); + nsslowcert_DestroyCertificate(cert); + } + /* free any data the decode may have allocated. */ + pkcs11_freeStaticData(certEntry.derCert.data, + certEntry.derCertSpace); + pkcs11_freeNickname(certEntry.nickname, certEntry.nicknameSpace); + break; + + case certDBEntryTypeKeyRevocation: + isKRL = PR_TRUE; + /* fall through */ + case certDBEntryTypeRevocation: + crlEntry.common.version = (unsigned int)dataBuf[0]; + crlEntry.common.type = entryType; + crlEntry.common.flags = (unsigned int)dataBuf[2]; + crlEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (crlEntry.common.arena == NULL) { + break; + } + rv = DecodeDBCrlEntry(&crlEntry, &dbEntry); + if (rv != SECSuccess) { + break; + } + nsslowcert_UpdateCrl(handle, &crlEntry.derCrl, &dbKey, + crlEntry.url, isKRL); + /* free data allocated by the decode */ + PORT_FreeArena(crlEntry.common.arena, PR_FALSE); + crlEntry.common.arena = NULL; + break; + + default: + break; + } + } while ((*updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0); /* now loop again updating just the SMimeProfile. */ - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); + ret = (*updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + if (ret) { + return (SECFailure); } - + do { - unsigned char *dataBuf = (unsigned char *)data.data; - unsigned char *keyBuf = (unsigned char *)key.data; - dbEntry.data = &dataBuf[SEC_DB_ENTRY_HEADER_LEN]; - dbEntry.len = data.size - SEC_DB_ENTRY_HEADER_LEN; - entryType = (certDBEntryType) keyBuf[0]; - if (entryType != certDBEntryTypeSMimeProfile) { - continue; - } - dbKey.data = &keyBuf[SEC_DB_KEY_HEADER_LEN]; - dbKey.len = key.size - SEC_DB_KEY_HEADER_LEN; - if ((dbEntry.len <= 0) || (dbKey.len <= 0)) { - continue; - } + unsigned char *dataBuf = (unsigned char *)data.data; + unsigned char *keyBuf = (unsigned char *)key.data; + dbEntry.data = &dataBuf[SEC_DB_ENTRY_HEADER_LEN]; + dbEntry.len = data.size - SEC_DB_ENTRY_HEADER_LEN; + entryType = (certDBEntryType)keyBuf[0]; + if (entryType != certDBEntryTypeSMimeProfile) { + continue; + } + dbKey.data = &keyBuf[SEC_DB_KEY_HEADER_LEN]; + dbKey.len = key.size - SEC_DB_KEY_HEADER_LEN; + if ((dbEntry.len <= 0) || (dbKey.len <= 0)) { + continue; + } smimeEntry.common.version = (unsigned int)dataBuf[0]; - smimeEntry.common.type = entryType; - smimeEntry.common.flags = (unsigned int)dataBuf[2]; - smimeEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - /* decode entry */ - rv = DecodeDBSMimeEntry(&smimeEntry,&dbEntry,(char *)dbKey.data); - if (rv == SECSuccess) { - nsslowcert_UpdateSMimeProfile(handle, smimeEntry.emailAddr, - &smimeEntry.subjectName, &smimeEntry.smimeOptions, - &smimeEntry.optionsDate); - } - PORT_FreeArena(smimeEntry.common.arena, PR_FALSE); - smimeEntry.common.arena = NULL; - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); - - (* updatedb->close)(updatedb); + smimeEntry.common.type = entryType; + smimeEntry.common.flags = (unsigned int)dataBuf[2]; + smimeEntry.common.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + /* decode entry */ + rv = DecodeDBSMimeEntry(&smimeEntry, &dbEntry, (char *)dbKey.data); + if (rv == SECSuccess) { + nsslowcert_UpdateSMimeProfile(handle, smimeEntry.emailAddr, + &smimeEntry.subjectName, &smimeEntry.smimeOptions, + &smimeEntry.optionsDate); + } + PORT_FreeArena(smimeEntry.common.arena, PR_FALSE); + smimeEntry.common.arena = NULL; + } while ((*updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0); + + (*updatedb->close)(updatedb); /* a database update is a good time to go back and verify the integrity of * the keys and certs */ - handle->dbVerify = PR_TRUE; - return(SECSuccess); + handle->dbVerify = PR_TRUE; + return (SECSuccess); } /* @@ -3577,228 +3570,236 @@ UpdateV6DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) certDBEntrySMime *emailEntry = NULL; char *nickname; char *emailAddr; - + /* * Sequence through the old database and copy all of the entries * to the new database. Subject name entries will have the new * fields inserted into them (with zero length). */ - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + ret = (*updatedb->seq)(updatedb, &key, &data, R_FIRST); + if (ret) { + return (SECFailure); } do { - buf = (unsigned char *)data.data; - - if ( data.size >= 3 ) { - if ( buf[0] == 6 ) { /* version number */ - type = (certDBEntryType)buf[1]; - if ( type == certDBEntryTypeSubject ) { - /* expando subjecto entrieo */ - tmpbuf = (unsigned char *)PORT_Alloc(data.size + 4); - if ( tmpbuf ) { - /* copy header stuff */ - PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN + 2); - /* insert 4 more bytes of zero'd header */ - PORT_Memset(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 2], - 0, 4); - /* copy rest of the data */ - PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], - &buf[SEC_DB_ENTRY_HEADER_LEN + 2], - data.size - (SEC_DB_ENTRY_HEADER_LEN + 2)); - - data.data = (void *)tmpbuf; - data.size += 4; - buf = tmpbuf; - } - } else if ( type == certDBEntryTypeCert ) { - /* expando certo entrieo */ - tmpbuf = (unsigned char *)PORT_Alloc(data.size + 3); - if ( tmpbuf ) { - /* copy header stuff */ - PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN); - - /* copy trust flage, setting msb's to 0 */ - tmpbuf[SEC_DB_ENTRY_HEADER_LEN] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+1] = - buf[SEC_DB_ENTRY_HEADER_LEN]; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+2] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+3] = - buf[SEC_DB_ENTRY_HEADER_LEN+1]; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+4] = 0; - tmpbuf[SEC_DB_ENTRY_HEADER_LEN+5] = - buf[SEC_DB_ENTRY_HEADER_LEN+2]; - - /* copy rest of the data */ - PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], - &buf[SEC_DB_ENTRY_HEADER_LEN + 3], - data.size - (SEC_DB_ENTRY_HEADER_LEN + 3)); - - data.data = (void *)tmpbuf; - data.size += 3; - buf = tmpbuf; - } - - } - - /* update the record version number */ - buf[0] = CERT_DB_FILE_VERSION; - - /* copy to the new database */ - ret = certdb_Put(handle->permCertDB, &key, &data, 0); - if ( tmpbuf ) { - PORT_Free(tmpbuf); - tmpbuf = NULL; - } - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); + buf = (unsigned char *)data.data; + + if (data.size >= 3) { + if (buf[0] == 6) { /* version number */ + type = (certDBEntryType)buf[1]; + if (type == certDBEntryTypeSubject) { + /* expando subjecto entrieo */ + tmpbuf = (unsigned char *)PORT_Alloc(data.size + 4); + if (tmpbuf) { + /* copy header stuff */ + PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN + 2); + /* insert 4 more bytes of zero'd header */ + PORT_Memset(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 2], + 0, 4); + /* copy rest of the data */ + PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], + &buf[SEC_DB_ENTRY_HEADER_LEN + 2], + data.size - (SEC_DB_ENTRY_HEADER_LEN + 2)); + + data.data = (void *)tmpbuf; + data.size += 4; + buf = tmpbuf; + } + } else if (type == certDBEntryTypeCert) { + /* expando certo entrieo */ + tmpbuf = (unsigned char *)PORT_Alloc(data.size + 3); + if (tmpbuf) { + /* copy header stuff */ + PORT_Memcpy(tmpbuf, buf, SEC_DB_ENTRY_HEADER_LEN); + + /* copy trust flage, setting msb's to 0 */ + tmpbuf[SEC_DB_ENTRY_HEADER_LEN] = 0; + tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 1] = + buf[SEC_DB_ENTRY_HEADER_LEN]; + tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 2] = 0; + tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 3] = + buf[SEC_DB_ENTRY_HEADER_LEN + 1]; + tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 4] = 0; + tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 5] = + buf[SEC_DB_ENTRY_HEADER_LEN + 2]; + + /* copy rest of the data */ + PORT_Memcpy(&tmpbuf[SEC_DB_ENTRY_HEADER_LEN + 6], + &buf[SEC_DB_ENTRY_HEADER_LEN + 3], + data.size - (SEC_DB_ENTRY_HEADER_LEN + 3)); + + data.data = (void *)tmpbuf; + data.size += 3; + buf = tmpbuf; + } + } + + /* update the record version number */ + buf[0] = CERT_DB_FILE_VERSION; + + /* copy to the new database */ + ret = certdb_Put(handle->permCertDB, &key, &data, 0); + if (tmpbuf) { + PORT_Free(tmpbuf); + tmpbuf = NULL; + } + if (ret) { + return SECFailure; + } + } + } + } while ((*updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0); ret = certdb_Sync(handle->permCertDB, 0); + if (ret) { + return SECFailure; + } - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + ret = (*updatedb->seq)(updatedb, &key, &data, R_FIRST); + if (ret) { + return (SECFailure); } do { - buf = (unsigned char *)data.data; - - if ( data.size >= 3 ) { - if ( buf[0] == CERT_DB_FILE_VERSION ) { /* version number */ - type = (certDBEntryType)buf[1]; - if ( type == certDBEntryTypeNickname ) { - nickname = &((char *)key.data)[1]; - - /* get the matching nickname entry in the new DB */ - nnEntry = ReadDBNicknameEntry(handle, nickname); - if ( nnEntry == NULL ) { - goto endloop; - } - - /* find the subject entry pointed to by nickname */ - subjectEntry = ReadDBSubjectEntry(handle, - &nnEntry->subjectName); - if ( subjectEntry == NULL ) { - goto endloop; - } - - subjectEntry->nickname = - (char *)PORT_ArenaAlloc(subjectEntry->common.arena, - key.size - 1); - if ( subjectEntry->nickname ) { - PORT_Memcpy(subjectEntry->nickname, nickname, - key.size - 1); - (void)WriteDBSubjectEntry(handle, subjectEntry); - } - } else if ( type == certDBEntryTypeSMimeProfile ) { - emailAddr = &((char *)key.data)[1]; - - /* get the matching smime entry in the new DB */ - emailEntry = nsslowcert_ReadDBSMimeEntry(handle, emailAddr); - if ( emailEntry == NULL ) { - goto endloop; - } - - /* find the subject entry pointed to by nickname */ - subjectEntry = ReadDBSubjectEntry(handle, - &emailEntry->subjectName); - if ( subjectEntry == NULL ) { - goto endloop; - } - - subjectEntry->emailAddrs = (char **) - PORT_ArenaAlloc(subjectEntry->common.arena, - sizeof(char *)); - if ( subjectEntry->emailAddrs ) { - subjectEntry->emailAddrs[0] = - (char *)PORT_ArenaAlloc(subjectEntry->common.arena, - key.size - 1); - if ( subjectEntry->emailAddrs[0] ) { - PORT_Memcpy(subjectEntry->emailAddrs[0], emailAddr, - key.size - 1); - subjectEntry->nemailAddrs = 1; - (void)WriteDBSubjectEntry(handle, subjectEntry); - } - } - } - -endloop: - if ( subjectEntry ) { - DestroyDBEntry((certDBEntry *)subjectEntry); - subjectEntry = NULL; - } - if ( nnEntry ) { - DestroyDBEntry((certDBEntry *)nnEntry); - nnEntry = NULL; - } - if ( emailEntry ) { - DestroyDBEntry((certDBEntry *)emailEntry); - emailEntry = NULL; - } - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); + buf = (unsigned char *)data.data; + + if (data.size >= 3) { + if (buf[0] == CERT_DB_FILE_VERSION) { /* version number */ + type = (certDBEntryType)buf[1]; + if (type == certDBEntryTypeNickname) { + nickname = &((char *)key.data)[1]; + + /* get the matching nickname entry in the new DB */ + nnEntry = ReadDBNicknameEntry(handle, nickname); + if (nnEntry == NULL) { + goto endloop; + } + + /* find the subject entry pointed to by nickname */ + subjectEntry = ReadDBSubjectEntry(handle, + &nnEntry->subjectName); + if (subjectEntry == NULL) { + goto endloop; + } + + subjectEntry->nickname = + (char *)PORT_ArenaAlloc(subjectEntry->common.arena, + key.size - 1); + if (subjectEntry->nickname) { + PORT_Memcpy(subjectEntry->nickname, nickname, + key.size - 1); + (void)WriteDBSubjectEntry(handle, subjectEntry); + } + } else if (type == certDBEntryTypeSMimeProfile) { + emailAddr = &((char *)key.data)[1]; + + /* get the matching smime entry in the new DB */ + emailEntry = nsslowcert_ReadDBSMimeEntry(handle, emailAddr); + if (emailEntry == NULL) { + goto endloop; + } + + /* find the subject entry pointed to by nickname */ + subjectEntry = ReadDBSubjectEntry(handle, + &emailEntry->subjectName); + if (subjectEntry == NULL) { + goto endloop; + } + + subjectEntry->emailAddrs = (char **) + PORT_ArenaAlloc(subjectEntry->common.arena, + sizeof(char *)); + if (subjectEntry->emailAddrs) { + subjectEntry->emailAddrs[0] = + (char *)PORT_ArenaAlloc(subjectEntry->common.arena, + key.size - 1); + if (subjectEntry->emailAddrs[0]) { + PORT_Memcpy(subjectEntry->emailAddrs[0], emailAddr, + key.size - 1); + subjectEntry->nemailAddrs = 1; + (void)WriteDBSubjectEntry(handle, subjectEntry); + } + } + } + + endloop: + if (subjectEntry) { + DestroyDBEntry((certDBEntry *)subjectEntry); + subjectEntry = NULL; + } + if (nnEntry) { + DestroyDBEntry((certDBEntry *)nnEntry); + nnEntry = NULL; + } + if (emailEntry) { + DestroyDBEntry((certDBEntry *)emailEntry); + emailEntry = NULL; + } + } + } + } while ((*updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0); ret = certdb_Sync(handle->permCertDB, 0); + if (ret) { + return SECFailure; + } - (* updatedb->close)(updatedb); - return(SECSuccess); + (*updatedb->close)(updatedb); + return (SECSuccess); } - static SECStatus updateV5Callback(NSSLOWCERTCertificate *cert, SECItem *k, void *pdata) { NSSLOWCERTCertDBHandle *handle; certDBEntryCert *entry; NSSLOWCERTCertTrust *trust; - + handle = (NSSLOWCERTCertDBHandle *)pdata; trust = &cert->dbEntry->trust; /* SSL user certs can be used for email if they have an email addr */ - if ( cert->emailAddr && ( trust->sslFlags & CERTDB_USER ) && - ( trust->emailFlags == 0 ) ) { - trust->emailFlags = CERTDB_USER; + if (cert->emailAddr && (trust->sslFlags & CERTDB_USER) && + (trust->emailFlags == 0)) { + trust->emailFlags = CERTDB_USER; } /* servers didn't set the user flags on the server cert.. */ - if (PORT_Strcmp(cert->dbEntry->nickname,"Server-Cert") == 0) { - trust->sslFlags |= CERTDB_USER; + if (PORT_Strcmp(cert->dbEntry->nickname, "Server-Cert") == 0) { + trust->sslFlags |= CERTDB_USER; } - + entry = AddCertToPermDB(handle, cert, cert->dbEntry->nickname, - &cert->dbEntry->trust); - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); + &cert->dbEntry->trust); + if (entry) { + DestroyDBEntry((certDBEntry *)entry); } - - return(SECSuccess); + + return (SECSuccess); } static SECStatus UpdateV5DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) { NSSLOWCERTCertDBHandle updatehandle; - + updatehandle.permCertDB = updatedb; updatehandle.dbMon = PZ_NewMonitor(nssILockCertDB); updatehandle.dbVerify = 0; - updatehandle.ref = 1; /* prevent premature close */ - + updatehandle.ref = 1; /* prevent premature close */ + (void)nsslowcert_TraversePermCerts(&updatehandle, updateV5Callback, - (void *)handle); - + (void *)handle); + PZ_DestroyMonitor(updatehandle.dbMon); - (* updatedb->close)(updatedb); - return(SECSuccess); + (*updatedb->close)(updatedb); + return (SECSuccess); } static PRBool -isV4DB(DB *db) { - DBT key,data; +isV4DB(DB *db) +{ + DBT key, data; int ret; key.data = "Version"; @@ -3806,11 +3807,11 @@ isV4DB(DB *db) { ret = (*db->get)(db, &key, &data, 0); if (ret) { - return PR_FALSE; + return PR_FALSE; } - if ((data.size == 1) && (*(unsigned char *)data.data <= 4)) { - return PR_TRUE; + if ((data.size == 1) && (*(unsigned char *)data.data <= 4)) { + return PR_TRUE; } return PR_FALSE; @@ -3822,52 +3823,44 @@ UpdateV4DB(NSSLOWCERTCertDBHandle *handle, DB *updatedb) DBT key, data; certDBEntryCert *entry, *entry2; int ret; - PLArenaPool *arena = NULL; NSSLOWCERTCertificate *cert; - ret = (* updatedb->seq)(updatedb, &key, &data, R_FIRST); + ret = (*updatedb->seq)(updatedb, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + if (ret) { + return (SECFailure); } - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - return(SECFailure); - } - do { - if ( data.size != 1 ) { /* skip version number */ - - /* decode the old DB entry */ - entry = (certDBEntryCert *) - DecodeV4DBCertEntry((unsigned char*)data.data, data.size); - - if ( entry ) { - cert = nsslowcert_DecodeDERCertificate(&entry->derCert, - entry->nickname); - - if ( cert != NULL ) { - /* add to new database */ - entry2 = AddCertToPermDB(handle, cert, entry->nickname, - &entry->trust); - - nsslowcert_DestroyCertificate(cert); - if ( entry2 ) { - DestroyDBEntry((certDBEntry *)entry2); - } - } - DestroyDBEntry((certDBEntry *)entry); - } - } - } while ( (* updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0 ); + if (data.size != 1) { /* skip version number */ + + /* decode the old DB entry */ + entry = (certDBEntryCert *) + DecodeV4DBCertEntry((unsigned char *)data.data, data.size); + + if (entry) { + cert = nsslowcert_DecodeDERCertificate(&entry->derCert, + entry->nickname); + + if (cert != NULL) { + /* add to new database */ + entry2 = AddCertToPermDB(handle, cert, entry->nickname, + &entry->trust); + + nsslowcert_DestroyCertificate(cert); + if (entry2) { + DestroyDBEntry((certDBEntry *)entry2); + } + } + DestroyDBEntry((certDBEntry *)entry); + } + } + } while ((*updatedb->seq)(updatedb, &key, &data, R_NEXT) == 0); - PORT_FreeArena(arena, PR_FALSE); - (* updatedb->close)(updatedb); - return(SECSuccess); + (*updatedb->close)(updatedb); + return (SECSuccess); } - /* * return true if a database key conflict exists */ @@ -3881,40 +3874,40 @@ nsslowcert_CertDBKeyConflict(SECItem *derCert, NSSLOWCERTCertDBHandle *handle) SECItem keyitem; PLArenaPool *arena = NULL; SECItem derKey; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } /* get the db key of the cert */ rv = nsslowcert_KeyFromDERCert(arena, derCert, &derKey); - if ( rv != SECSuccess ) { + if (rv != SECSuccess) { goto loser; } rv = EncodeDBCertKey(&derKey, arena, &keyitem); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + namekey.data = keyitem.data; namekey.size = keyitem.len; - + ret = certdb_Get(handle->permCertDB, &namekey, &tmpdata, 0); - if ( ret == 0 ) { - goto loser; + if (ret == 0) { + goto loser; } PORT_FreeArena(arena, PR_FALSE); - - return(PR_FALSE); + + return (PR_FALSE); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - - return(PR_TRUE); + + return (PR_TRUE); } /* @@ -3924,40 +3917,40 @@ loser: */ static PRBool nsslowcert_CertNicknameConflict(char *nickname, SECItem *derSubject, - NSSLOWCERTCertDBHandle *handle) + NSSLOWCERTCertDBHandle *handle) { PRBool rv; certDBEntryNickname *entry; - - if ( nickname == NULL ) { - return(PR_FALSE); + + if (nickname == NULL) { + return (PR_FALSE); } - + entry = ReadDBNicknameEntry(handle, nickname); - if ( entry == NULL ) { - /* no entry for this nickname, so no conflict */ - return(PR_FALSE); + if (entry == NULL) { + /* no entry for this nickname, so no conflict */ + return (PR_FALSE); } rv = PR_TRUE; - if ( SECITEM_CompareItem(derSubject, &entry->subjectName) == SECEqual ) { - /* if subject names are the same, then no conflict */ - rv = PR_FALSE; + if (SECITEM_CompareItem(derSubject, &entry->subjectName) == SECEqual) { + /* if subject names are the same, then no conflict */ + rv = PR_FALSE; } DestroyDBEntry((certDBEntry *)entry); - return(rv); + return (rv); } #ifdef DBM_USING_NSPR -#define NO_RDONLY PR_RDONLY -#define NO_RDWR PR_RDWR -#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) +#define NO_RDONLY PR_RDONLY +#define NO_RDWR PR_RDWR +#define NO_CREATE (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE) #else -#define NO_RDONLY O_RDONLY -#define NO_RDWR O_RDWR -#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) +#define NO_RDONLY O_RDONLY +#define NO_RDWR O_RDWR +#define NO_CREATE (O_RDWR | O_CREAT | O_TRUNC) #endif /* @@ -3966,20 +3959,20 @@ nsslowcert_CertNicknameConflict(char *nickname, SECItem *derSubject, static DB * nsslowcert_openolddb(NSSLOWCERTDBNameFunc namecb, void *cbarg, int version) { - char * tmpname; + char *tmpname; DB *updatedb = NULL; - tmpname = (* namecb)(cbarg, version); /* get v6 db name */ - if ( tmpname ) { - updatedb = dbopen( tmpname, NO_RDONLY, 0600, DB_HASH, 0 ); - PORT_Free(tmpname); + tmpname = (*namecb)(cbarg, version); /* get v6 db name */ + if (tmpname) { + updatedb = dbopen(tmpname, NO_RDONLY, 0600, DB_HASH, 0); + PORT_Free(tmpname); } return updatedb; } static SECStatus -openNewCertDB(const char *appName, const char *prefix, const char *certdbname, - NSSLOWCERTCertDBHandle *handle, NSSLOWCERTDBNameFunc namecb, void *cbarg) +openNewCertDB(const char *appName, const char *prefix, const char *certdbname, + NSSLOWCERTCertDBHandle *handle, NSSLOWCERTDBNameFunc namecb, void *cbarg) { SECStatus rv; certDBEntryVersion *versionEntry = NULL; @@ -3987,66 +3980,65 @@ openNewCertDB(const char *appName, const char *prefix, const char *certdbname, int status = RDB_FAIL; if (appName) { - handle->permCertDB=rdbopen( appName, prefix, "cert", NO_CREATE, &status); + handle->permCertDB = rdbopen(appName, prefix, "cert", NO_CREATE, &status); } else { - handle->permCertDB=dbsopen(certdbname, NO_CREATE, 0600, DB_HASH, 0); + handle->permCertDB = dbsopen(certdbname, NO_CREATE, 0600, DB_HASH, 0); } /* if create fails then we lose */ - if ( handle->permCertDB == 0 ) { - return status == RDB_RETRY ? SECWouldBlock : SECFailure; + if (handle->permCertDB == 0) { + return status == RDB_RETRY ? SECWouldBlock : SECFailure; } /* Verify version number; */ versionEntry = NewDBVersionEntry(0); - if ( versionEntry == NULL ) { - rv = SECFailure; - goto loser; + if (versionEntry == NULL) { + rv = SECFailure; + goto loser; } - + rv = WriteDBVersionEntry(handle, versionEntry); DestroyDBEntry((certDBEntry *)versionEntry); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* rv must already be Success here because of previous if statement */ /* try to upgrade old db here */ if (appName && - (updatedb = dbsopen(certdbname, NO_RDONLY, 0600, DB_HASH, 0)) != NULL) { - rv = UpdateV8DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,7)) != NULL) { - rv = UpdateV7DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,6)) != NULL) { - rv = UpdateV6DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,5)) != NULL) { - rv = UpdateV5DB(handle, updatedb); - } else if ((updatedb = nsslowcert_openolddb(namecb,cbarg,4)) != NULL) { - /* NES has v5 format db's with v4 db names! */ - if (isV4DB(updatedb)) { - rv = UpdateV4DB(handle,updatedb); - } else { - rv = UpdateV5DB(handle,updatedb); - } + (updatedb = dbsopen(certdbname, NO_RDONLY, 0600, DB_HASH, 0)) != NULL) { + rv = UpdateV8DB(handle, updatedb); + } else if ((updatedb = nsslowcert_openolddb(namecb, cbarg, 7)) != NULL) { + rv = UpdateV7DB(handle, updatedb); + } else if ((updatedb = nsslowcert_openolddb(namecb, cbarg, 6)) != NULL) { + rv = UpdateV6DB(handle, updatedb); + } else if ((updatedb = nsslowcert_openolddb(namecb, cbarg, 5)) != NULL) { + rv = UpdateV5DB(handle, updatedb); + } else if ((updatedb = nsslowcert_openolddb(namecb, cbarg, 4)) != NULL) { + /* NES has v5 format db's with v4 db names! */ + if (isV4DB(updatedb)) { + rv = UpdateV4DB(handle, updatedb); + } else { + rv = UpdateV5DB(handle, updatedb); + } } - loser: db_InitComplete(handle->permCertDB); return rv; } static int -nsslowcert_GetVersionNumber( NSSLOWCERTCertDBHandle *handle) +nsslowcert_GetVersionNumber(NSSLOWCERTCertDBHandle *handle) { certDBEntryVersion *versionEntry = NULL; int version = 0; - versionEntry = ReadDBVersionEntry(handle); - if ( versionEntry == NULL ) { - return 0; + versionEntry = ReadDBVersionEntry(handle); + if (versionEntry == NULL) { + return 0; } version = versionEntry->common.version; DestroyDBEntry((certDBEntry *)versionEntry); @@ -4059,17 +4051,17 @@ nsslowcert_GetVersionNumber( NSSLOWCERTCertDBHandle *handle) */ static SECStatus nsslowcert_OpenPermCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *appName, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg) + const char *appName, const char *prefix, + NSSLOWCERTDBNameFunc namecb, void *cbarg) { SECStatus rv; int openflags; char *certdbname; int version = 0; - - certdbname = (* namecb)(cbarg, CERT_DB_FILE_VERSION); - if ( certdbname == NULL ) { - return(SECFailure); + + certdbname = (*namecb)(cbarg, CERT_DB_FILE_VERSION); + if (certdbname == NULL) { + return (SECFailure); } openflags = readOnly ? NO_RDONLY : NO_RDWR; @@ -4078,66 +4070,66 @@ nsslowcert_OpenPermCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, * first open the permanent file based database. */ if (appName) { - handle->permCertDB = rdbopen( appName, prefix, "cert", openflags, NULL); + handle->permCertDB = rdbopen(appName, prefix, "cert", openflags, NULL); } else { - handle->permCertDB = dbsopen( certdbname, openflags, 0600, DB_HASH, 0 ); + handle->permCertDB = dbsopen(certdbname, openflags, 0600, DB_HASH, 0); } /* check for correct version number */ - if ( handle->permCertDB ) { - version = nsslowcert_GetVersionNumber(handle); - if ((version != CERT_DB_FILE_VERSION) && - !(appName && version == CERT_DB_V7_FILE_VERSION)) { - goto loser; - } - } else if ( readOnly ) { - /* don't create if readonly */ - /* Try openning a version 7 database */ - handle->permCertDB = nsslowcert_openolddb(namecb,cbarg, 7); - if (!handle->permCertDB) { - goto loser; - } - if (nsslowcert_GetVersionNumber(handle) != 7) { - goto loser; - } + if (handle->permCertDB) { + version = nsslowcert_GetVersionNumber(handle); + if ((version != CERT_DB_FILE_VERSION) && + !(appName && version == CERT_DB_V7_FILE_VERSION)) { + goto loser; + } + } else if (readOnly) { + /* don't create if readonly */ + /* Try openning a version 7 database */ + handle->permCertDB = nsslowcert_openolddb(namecb, cbarg, 7); + if (!handle->permCertDB) { + goto loser; + } + if (nsslowcert_GetVersionNumber(handle) != 7) { + goto loser; + } } else { /* if first open fails, try to create a new DB */ - rv = openNewCertDB(appName,prefix,certdbname,handle,namecb,cbarg); - if (rv == SECWouldBlock) { - /* only the rdb version can fail with wouldblock */ - handle->permCertDB = - rdbopen( appName, prefix, "cert", openflags, NULL); - - /* check for correct version number */ - if ( !handle->permCertDB ) { - goto loser; - } - version = nsslowcert_GetVersionNumber(handle); - if ((version != CERT_DB_FILE_VERSION) && - !(appName && version == CERT_DB_V7_FILE_VERSION)) { - goto loser; - } - } else if (rv != SECSuccess) { - goto loser; - } + rv = openNewCertDB(appName, prefix, certdbname, handle, namecb, cbarg); + if (rv == SECWouldBlock) { + /* only the rdb version can fail with wouldblock */ + handle->permCertDB = + rdbopen(appName, prefix, "cert", openflags, NULL); + + /* check for correct version number */ + if (!handle->permCertDB) { + goto loser; + } + version = nsslowcert_GetVersionNumber(handle); + if ((version != CERT_DB_FILE_VERSION) && + !(appName && version == CERT_DB_V7_FILE_VERSION)) { + goto loser; + } + } else if (rv != SECSuccess) { + goto loser; + } } PORT_Free(certdbname); - + return (SECSuccess); - + loser: PORT_SetError(SEC_ERROR_BAD_DATABASE); - - if ( handle->permCertDB ) { - certdb_Close(handle->permCertDB); - handle->permCertDB = 0; + + if (handle->permCertDB) { + certdb_Close(handle->permCertDB); + handle->permCertDB = 0; } PORT_Free(certdbname); - return(SECFailure); + return (SECFailure); } /* @@ -4150,16 +4142,15 @@ DeletePermCert(NSSLOWCERTCertificate *cert) SECStatus ret; ret = SECSuccess; - + rv = DeleteDBCertEntry(cert->dbhandle, &cert->certKey); - if ( rv != SECSuccess ) { - ret = SECFailure; + if (rv != SECSuccess) { + ret = SECFailure; } - - rv = RemovePermSubjectNode(cert); + rv = RemovePermSubjectNode(cert); - return(ret); + return (ret); } /* @@ -4169,7 +4160,7 @@ SECStatus nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert) { SECStatus rv; - + nsslowcert_LockDB(cert->dbhandle); /* delete the records from the permanent database */ @@ -4179,9 +4170,9 @@ nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert) DestroyDBEntry((certDBEntry *)cert->dbEntry); cert->dbEntry = NULL; cert->trust = NULL; - + nsslowcert_UnlockDB(cert->dbhandle); - return(rv); + return (rv); } /* @@ -4190,10 +4181,10 @@ nsslowcert_DeletePermCertificate(NSSLOWCERTCertificate *cert) */ SECStatus nsslowcert_TraverseDBEntries(NSSLOWCERTCertDBHandle *handle, - certDBEntryType type, - SECStatus (* callback)(SECItem *data, SECItem *key, - certDBEntryType type, void *pdata), - void *udata ) + certDBEntryType type, + SECStatus (*callback)(SECItem *data, SECItem *key, + certDBEntryType type, void *pdata), + void *udata) { DBT data; DBT key; @@ -4203,34 +4194,34 @@ nsslowcert_TraverseDBEntries(NSSLOWCERTCertDBHandle *handle, SECItem keyitem; unsigned char *buf; unsigned char *keybuf; - + ret = certdb_Seq(handle->permCertDB, &key, &data, R_FIRST); - if ( ret ) { - return(SECFailure); + if (ret) { + return (SECFailure); } - /* here, ret is zero and rv is SECSuccess. + /* here, ret is zero and rv is SECSuccess. * Below here, ret is a count of successful calls to the callback function. */ do { - buf = (unsigned char *)data.data; - - if ( buf[1] == (unsigned char)type ) { - dataitem.len = data.size; - dataitem.data = buf; + buf = (unsigned char *)data.data; + + if (buf[1] == (unsigned char)type) { + dataitem.len = data.size; + dataitem.data = buf; dataitem.type = siBuffer; - keyitem.len = key.size - SEC_DB_KEY_HEADER_LEN; - keybuf = (unsigned char *)key.data; - keyitem.data = &keybuf[SEC_DB_KEY_HEADER_LEN]; + keyitem.len = key.size - SEC_DB_KEY_HEADER_LEN; + keybuf = (unsigned char *)key.data; + keyitem.data = &keybuf[SEC_DB_KEY_HEADER_LEN]; keyitem.type = siBuffer; - /* type should equal keybuf[0]. */ - - rv = (* callback)(&dataitem, &keyitem, type, udata); - if ( rv == SECSuccess ) { - ++ret; - } - } - } while ( certdb_Seq(handle->permCertDB, &key, &data, R_NEXT) == 0 ); - /* If any callbacks succeeded, or no calls to callbacks were made, + /* type should equal keybuf[0]. */ + + rv = (*callback)(&dataitem, &keyitem, type, udata); + if (rv == SECSuccess) { + ++ret; + } + } + } while (certdb_Seq(handle->permCertDB, &key, &data, R_NEXT) == 0); + /* If any callbacks succeeded, or no calls to callbacks were made, * then report success. Otherwise, report failure. */ return (ret ? SECSuccess : rv); @@ -4245,21 +4236,21 @@ static NSSLOWCERTCertificate * DecodeACert(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry) { NSSLOWCERTCertificate *cert = NULL; - - cert = nsslowcert_DecodeDERCertificate(&entry->derCert, entry->nickname ); - - if ( cert == NULL ) { - goto loser; + + cert = nsslowcert_DecodeDERCertificate(&entry->derCert, entry->nickname); + + if (cert == NULL) { + goto loser; } cert->dbhandle = handle; cert->dbEntry = entry; cert->trust = &entry->trust; - return(cert); + return (cert); loser: - return(0); + return (0); } static NSSLOWCERTTrust * @@ -4270,13 +4261,13 @@ CreateTrust(void) nsslowcert_LockFreeList(); trust = trustListHead; if (trust) { - trustListCount--; - trustListHead = trust->next; + trustListCount--; + trustListHead = trust->next; } PORT_Assert(trustListCount >= 0); nsslowcert_UnlockFreeList(); if (trust) { - return trust; + return trust; } return PORT_ZNew(NSSLOWCERTTrust); @@ -4289,37 +4280,37 @@ DestroyTrustFreeList(void) nsslowcert_LockFreeList(); while (NULL != (trust = trustListHead)) { - trustListCount--; - trustListHead = trust->next; - PORT_Free(trust); + trustListCount--; + trustListHead = trust->next; + PORT_Free(trust); } PORT_Assert(!trustListCount); trustListCount = 0; nsslowcert_UnlockFreeList(); } -static NSSLOWCERTTrust * -DecodeTrustEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry, +static NSSLOWCERTTrust * +DecodeTrustEntry(NSSLOWCERTCertDBHandle *handle, certDBEntryCert *entry, const SECItem *dbKey) { NSSLOWCERTTrust *trust = CreateTrust(); if (trust == NULL) { - return trust; + return trust; } trust->dbhandle = handle; trust->dbEntry = entry; - trust->dbKey.data = pkcs11_copyStaticData(dbKey->data,dbKey->len, - trust->dbKeySpace, sizeof(trust->dbKeySpace)); + trust->dbKey.data = pkcs11_copyStaticData(dbKey->data, dbKey->len, + trust->dbKeySpace, sizeof(trust->dbKeySpace)); if (!trust->dbKey.data) { - PORT_Free(trust); - return NULL; + PORT_Free(trust); + return NULL; } trust->dbKey.len = dbKey->len; - + trust->trust = &entry->trust; trust->derCert = &entry->derCert; - return(trust); + return (trust); } typedef struct { @@ -4340,43 +4331,47 @@ certcallback(SECItem *dbdata, SECItem *dbkey, certDBEntryType type, void *data) SECItem entryitem; NSSLOWCERTCertificate *cert; PLArenaPool *arena = NULL; - + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } - + entry = (certDBEntryCert *)PORT_ArenaAlloc(arena, sizeof(certDBEntryCert)); + if (!entry) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } mystate = (PermCertCallbackState *)data; entry->common.version = (unsigned int)dbdata->data[0]; entry->common.type = (certDBEntryType)dbdata->data[1]; entry->common.flags = (unsigned int)dbdata->data[2]; entry->common.arena = arena; - + entryitem.len = dbdata->len - SEC_DB_ENTRY_HEADER_LEN; entryitem.data = &dbdata->data[SEC_DB_ENTRY_HEADER_LEN]; - + rv = DecodeDBCertEntry(entry, &entryitem); - if (rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } entry->derCert.type = siBuffer; - + /* note: Entry is 'inheritted'. */ cert = DecodeACert(mystate->handle, entry); - rv = (* mystate->certfunc)(cert, dbkey, mystate->data); + rv = (*mystate->certfunc)(cert, dbkey, mystate->data); /* arena stored in entry destroyed by nsslowcert_DestroyCertificate */ nsslowcert_DestroyCertificateNoLocking(cert); - return(rv); + return (rv); loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - return(SECFailure); + return (SECFailure); } /* @@ -4385,10 +4380,10 @@ loser: */ static SECStatus TraversePermCertsNoLocking(NSSLOWCERTCertDBHandle *handle, - SECStatus (* certfunc)(NSSLOWCERTCertificate *cert, - SECItem *k, - void *pdata), - void *udata ) + SECStatus (*certfunc)(NSSLOWCERTCertificate *cert, + SECItem *k, + void *pdata), + void *udata) { SECStatus rv; PermCertCallbackState mystate; @@ -4397,9 +4392,9 @@ TraversePermCertsNoLocking(NSSLOWCERTCertDBHandle *handle, mystate.handle = handle; mystate.data = udata; rv = nsslowcert_TraverseDBEntries(handle, certDBEntryTypeCert, certcallback, - (void *)&mystate); - - return(rv); + (void *)&mystate); + + return (rv); } /* @@ -4408,20 +4403,18 @@ TraversePermCertsNoLocking(NSSLOWCERTCertDBHandle *handle, */ SECStatus nsslowcert_TraversePermCerts(NSSLOWCERTCertDBHandle *handle, - SECStatus (* certfunc)(NSSLOWCERTCertificate *cert, SECItem *k, - void *pdata), - void *udata ) + SECStatus (*certfunc)(NSSLOWCERTCertificate *cert, SECItem *k, + void *pdata), + void *udata) { SECStatus rv; nsslowcert_LockDB(handle); rv = TraversePermCertsNoLocking(handle, certfunc, udata); nsslowcert_UnlockDB(handle); - - return(rv); -} - + return (rv); +} /* * Close the database @@ -4429,16 +4422,16 @@ nsslowcert_TraversePermCerts(NSSLOWCERTCertDBHandle *handle, void nsslowcert_ClosePermCertDB(NSSLOWCERTCertDBHandle *handle) { - if ( handle ) { - if ( handle->permCertDB ) { - certdb_Close( handle->permCertDB ); - handle->permCertDB = NULL; - } - if (handle->dbMon) { - PZ_DestroyMonitor(handle->dbMon); - handle->dbMon = NULL; - } - PORT_Free(handle); + if (handle) { + if (handle->permCertDB) { + certdb_Close(handle->permCertDB); + handle->permCertDB = NULL; + } + if (handle->dbMon) { + PZ_DestroyMonitor(handle->dbMon); + handle->dbMon = NULL; + } + PORT_Free(handle); } return; } @@ -4450,18 +4443,18 @@ SECStatus nsslowcert_GetCertTrust(NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) { SECStatus rv; - + nsslowcert_LockCertTrust(cert); - - if ( cert->trust == NULL ) { - rv = SECFailure; + + if (cert->trust == NULL) { + rv = SECFailure; } else { - *trust = *cert->trust; - rv = SECSuccess; + *trust = *cert->trust; + rv = SECSuccess; } - + nsslowcert_UnlockCertTrust(cert); - return(rv); + return (rv); } /* @@ -4469,48 +4462,47 @@ nsslowcert_GetCertTrust(NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) * in the database. */ SECStatus -nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) +nsslowcert_ChangeCertTrust(NSSLOWCERTCertDBHandle *handle, + NSSLOWCERTCertificate *cert, NSSLOWCERTCertTrust *trust) { certDBEntryCert *entry; int rv; SECStatus ret; - + nsslowcert_LockDB(handle); nsslowcert_LockCertTrust(cert); /* only set the trust on permanent certs */ - if ( cert->trust == NULL ) { - ret = SECFailure; - goto done; + if (cert->trust == NULL) { + ret = SECFailure; + goto done; } *cert->trust = *trust; - if ( cert->dbEntry == NULL ) { - ret = SECSuccess; /* not in permanent database */ - goto done; + if (cert->dbEntry == NULL) { + ret = SECSuccess; /* not in permanent database */ + goto done; } - + entry = cert->dbEntry; entry->trust = *trust; - + rv = WriteDBCertEntry(handle, entry); - if ( rv ) { - ret = SECFailure; - goto done; + if (rv) { + ret = SECFailure; + goto done; } ret = SECSuccess; - + done: nsslowcert_UnlockCertTrust(cert); nsslowcert_UnlockDB(handle); - return(ret); + return (ret); } - static SECStatus nsslowcert_UpdatePermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) + NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) { char *oldnn; certDBEntryCert *entry; @@ -4521,46 +4513,47 @@ nsslowcert_UpdatePermCert(NSSLOWCERTCertDBHandle *dbhandle, /* don't add a conflicting nickname */ conflict = nsslowcert_CertNicknameConflict(nickname, &cert->derSubject, - dbhandle); - if ( conflict ) { - ret = SECFailure; - goto done; + dbhandle); + if (conflict) { + ret = SECFailure; + goto done; } - + /* save old nickname so that we can delete it */ oldnn = cert->nickname; entry = AddCertToPermDB(dbhandle, cert, nickname, trust); - - if ( entry == NULL ) { - ret = SECFailure; - goto done; + + if (entry == NULL) { + ret = SECFailure; + goto done; } - pkcs11_freeNickname(oldnn,cert->nicknameSpace); - + pkcs11_freeNickname(oldnn, cert->nicknameSpace); + cert->nickname = (entry->nickname) ? pkcs11_copyNickname(entry->nickname, - cert->nicknameSpace, sizeof(cert->nicknameSpace)) : NULL; + cert->nicknameSpace, sizeof(cert->nicknameSpace)) + : NULL; cert->trust = &entry->trust; cert->dbEntry = entry; - + ret = SECSuccess; done: - return(ret); + return (ret); } SECStatus nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *dbhandle, - NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) + NSSLOWCERTCertificate *cert, char *nickname, NSSLOWCERTCertTrust *trust) { SECStatus ret; nsslowcert_LockDB(dbhandle); ret = nsslowcert_UpdatePermCert(dbhandle, cert, nickname, trust); - + nsslowcert_UnlockDB(dbhandle); - return(ret); + return (ret); } /* @@ -4569,21 +4562,21 @@ nsslowcert_AddPermCert(NSSLOWCERTCertDBHandle *dbhandle, */ SECStatus nsslowcert_OpenCertDB(NSSLOWCERTCertDBHandle *handle, PRBool readOnly, - const char *appName, const char *prefix, - NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile) + const char *appName, const char *prefix, + NSSLOWCERTDBNameFunc namecb, void *cbarg, PRBool openVolatile) { int rv; certdb_InitDBLock(handle); - + handle->dbMon = PZ_NewMonitor(nssILockCertDB); PORT_Assert(handle->dbMon != NULL); handle->dbVerify = PR_FALSE; - rv = nsslowcert_OpenPermCertDB(handle, readOnly, appName, prefix, - namecb, cbarg); - if ( rv ) { - goto loser; + rv = nsslowcert_OpenPermCertDB(handle, readOnly, appName, prefix, + namecb, cbarg); + if (rv) { + goto loser; } return (SECSuccess); @@ -4594,13 +4587,14 @@ loser: handle->dbMon = NULL; } PORT_SetError(SEC_ERROR_BAD_DATABASE); - return(SECFailure); + return (SECFailure); } PRBool nsslowcert_needDBVerify(NSSLOWCERTCertDBHandle *handle) { - if (!handle) return PR_FALSE; + if (!handle) + return PR_FALSE; return handle->dbVerify; } @@ -4610,7 +4604,6 @@ nsslowcert_setDBVerify(NSSLOWCERTCertDBHandle *handle, PRBool value) handle->dbVerify = value; } - /* * Lookup a certificate in the databases. */ @@ -4620,34 +4613,34 @@ FindCertByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey, PRBool loc NSSLOWCERTCertificate *cert = NULL; certDBEntryCert *entry; PRBool locked = PR_FALSE; - - if ( lockdb ) { - locked = PR_TRUE; - nsslowcert_LockDB(handle); + + if (lockdb) { + locked = PR_TRUE; + nsslowcert_LockDB(handle); } - + /* find in perm database */ entry = ReadDBCertEntry(handle, certKey); - - if ( entry == NULL ) { - goto loser; + + if (entry == NULL) { + goto loser; } - - /* inherit entry */ + + /* inherit entry */ cert = DecodeACert(handle, entry); loser: if (cert == NULL) { - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } + if (entry) { + DestroyDBEntry((certDBEntry *)entry); + } } - if ( locked ) { - nsslowcert_UnlockDB(handle); + if (locked) { + nsslowcert_UnlockDB(handle); } - - return(cert); + + return (cert); } /* @@ -4659,38 +4652,38 @@ FindTrustByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey, PRBool lo NSSLOWCERTTrust *trust = NULL; certDBEntryCert *entry; PRBool locked = PR_FALSE; - - if ( lockdb ) { - locked = PR_TRUE; - nsslowcert_LockDB(handle); + + if (lockdb) { + locked = PR_TRUE; + nsslowcert_LockDB(handle); } - + /* find in perm database */ entry = ReadDBCertEntry(handle, certKey); - - if ( entry == NULL ) { - goto loser; + + if (entry == NULL) { + goto loser; } if (!nsslowcert_hasTrust(&entry->trust)) { - goto loser; + goto loser; } - - /* inherit entry */ + + /* inherit entry */ trust = DecodeTrustEntry(handle, entry, certKey); loser: if (trust == NULL) { - if (entry) { - DestroyDBEntry((certDBEntry *)entry); - } + if (entry) { + DestroyDBEntry((certDBEntry *)entry); + } } - if ( locked ) { - nsslowcert_UnlockDB(handle); + if (locked) { + nsslowcert_UnlockDB(handle); } - - return(trust); + + return (trust); } /* @@ -4699,7 +4692,7 @@ loser: NSSLOWCERTCertificate * nsslowcert_FindCertByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey) { - return(FindCertByKey(handle, certKey, PR_FALSE)); + return (FindCertByKey(handle, certKey, PR_FALSE)); } /* @@ -4708,7 +4701,7 @@ nsslowcert_FindCertByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey) NSSLOWCERTTrust * nsslowcert_FindTrustByKey(NSSLOWCERTCertDBHandle *handle, const SECItem *certKey) { - return(FindTrustByKey(handle, certKey, PR_FALSE)); + return (FindTrustByKey(handle, certKey, PR_FALSE)); } /* @@ -4726,43 +4719,43 @@ nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssue int index = 0; /* automatically detect DER encoded serial numbers and remove the der - * encoding since the database expects unencoded data. + * encoding since the database expects unencoded data. * if it's DER encoded, there must be at least 3 bytes, tag, len, data */ if ((sn->len >= 3) && (sn->data[0] == 0x2)) { - /* remove the der encoding of the serial number before generating the - * key.. */ - int data_left = sn->len-2; - data_len = sn->data[1]; - index = 2; - - /* extended length ? (not very likely for a serial number) */ - if (data_len & 0x80) { - int len_count = data_len & 0x7f; - - data_len = 0; - data_left -= len_count; - if (data_left > 0) { - while (len_count --) { - data_len = (data_len << 8) | sn->data[index++]; - } - } - } - /* XXX leaving any leading zeros on the serial number for backwards - * compatibility - */ - /* not a valid der, must be just an unlucky serial number value */ - if (data_len != data_left) { - data_len = sn->len; - index = 0; - } + /* remove the der encoding of the serial number before generating the + * key.. */ + int data_left = sn->len - 2; + data_len = sn->data[1]; + index = 2; + + /* extended length ? (not very likely for a serial number) */ + if (data_len & 0x80) { + int len_count = data_len & 0x7f; + + data_len = 0; + data_left -= len_count; + if (data_left > 0) { + while (len_count--) { + data_len = (data_len << 8) | sn->data[index++]; + } + } + } + /* XXX leaving any leading zeros on the serial number for backwards + * compatibility + */ + /* not a valid der, must be just an unlucky serial number value */ + if (data_len != data_left) { + data_len = sn->len; + index = 0; + } } certKey.type = 0; - certKey.data = (unsigned char*)PORT_Alloc(sn->len + issuer->len); + certKey.data = (unsigned char *)PORT_Alloc(sn->len + issuer->len); certKey.len = data_len + issuer->len; - - if ( certKey.data == NULL ) { - return(0); + + if (certKey.data == NULL) { + return (0); } /* first try the serial number as hand-decoded above*/ @@ -4770,12 +4763,12 @@ nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssue PORT_Memcpy(certKey.data, &sn->data[index], data_len); /* copy the issuer */ - PORT_Memcpy( &certKey.data[data_len],issuer->data,issuer->len); + PORT_Memcpy(&certKey.data[data_len], issuer->data, issuer->len); cert = nsslowcert_FindCertByKey(handle, &certKey); if (cert) { - PORT_Free(certKey.data); - return (cert); + PORT_Free(certKey.data); + return (cert); } /* didn't find it, try by der encoded serial number */ @@ -4783,14 +4776,14 @@ nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssue PORT_Memcpy(certKey.data, sn->data, sn->len); /* copy the issuer */ - PORT_Memcpy( &certKey.data[sn->len], issuer->data, issuer->len); + PORT_Memcpy(&certKey.data[sn->len], issuer->data, issuer->len); certKey.len = sn->len + issuer->len; cert = nsslowcert_FindCertByKey(handle, &certKey); - + PORT_Free(certKey.data); - - return(cert); + + return (cert); } /* @@ -4798,8 +4791,8 @@ nsslowcert_FindCertByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, NSSLOWCERTIssue * associated cert in the database. */ NSSLOWCERTTrust * -nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, - NSSLOWCERTIssuerAndSN *issuerAndSN) +nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, + NSSLOWCERTIssuerAndSN *issuerAndSN) { SECItem certKey; SECItem *sn = &issuerAndSN->serialNumber; @@ -4811,48 +4804,48 @@ nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, int len; /* automatically detect DER encoded serial numbers and remove the der - * encoding since the database expects unencoded data. + * encoding since the database expects unencoded data. * if it's DER encoded, there must be at least 3 bytes, tag, len, data */ if ((sn->len >= 3) && (sn->data[0] == 0x2)) { - /* remove the der encoding of the serial number before generating the - * key.. */ - int data_left = sn->len-2; - data_len = sn->data[1]; - index = 2; - - /* extended length ? (not very likely for a serial number) */ - if (data_len & 0x80) { - int len_count = data_len & 0x7f; - - data_len = 0; - data_left -= len_count; - if (data_left > 0) { - while (len_count --) { - data_len = (data_len << 8) | sn->data[index++]; - } - } - } - /* XXX leaving any leading zeros on the serial number for backwards - * compatibility - */ - /* not a valid der, must be just an unlucky serial number value */ - if (data_len != data_left) { - data_len = sn->len; - index = 0; - } + /* remove the der encoding of the serial number before generating the + * key.. */ + int data_left = sn->len - 2; + data_len = sn->data[1]; + index = 2; + + /* extended length ? (not very likely for a serial number) */ + if (data_len & 0x80) { + int len_count = data_len & 0x7f; + + data_len = 0; + data_left -= len_count; + if (data_left > 0) { + while (len_count--) { + data_len = (data_len << 8) | sn->data[index++]; + } + } + } + /* XXX leaving any leading zeros on the serial number for backwards + * compatibility + */ + /* not a valid der, must be just an unlucky serial number value */ + if (data_len != data_left) { + data_len = sn->len; + index = 0; + } } certKey.type = 0; certKey.len = data_len + issuer->len; len = sn->len + issuer->len; - if (len > sizeof (keyBuf)) { - certKey.data = (unsigned char*)PORT_Alloc(len); + if (len > sizeof(keyBuf)) { + certKey.data = (unsigned char *)PORT_Alloc(len); } else { - certKey.data = keyBuf; + certKey.data = keyBuf; } - - if ( certKey.data == NULL ) { - return(0); + + if (certKey.data == NULL) { + return (0); } /* first try the serial number as hand-decoded above*/ @@ -4860,17 +4853,17 @@ nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, PORT_Memcpy(certKey.data, &sn->data[index], data_len); /* copy the issuer */ - PORT_Memcpy( &certKey.data[data_len],issuer->data,issuer->len); + PORT_Memcpy(&certKey.data[data_len], issuer->data, issuer->len); trust = nsslowcert_FindTrustByKey(handle, &certKey); if (trust) { - pkcs11_freeStaticData(certKey.data, keyBuf); - return (trust); + pkcs11_freeStaticData(certKey.data, keyBuf); + return (trust); } if (index == 0) { - pkcs11_freeStaticData(certKey.data, keyBuf); - return NULL; + pkcs11_freeStaticData(certKey.data, keyBuf); + return NULL; } /* didn't find it, try by der encoded serial number */ @@ -4878,14 +4871,14 @@ nsslowcert_FindTrustByIssuerAndSN(NSSLOWCERTCertDBHandle *handle, PORT_Memcpy(certKey.data, sn->data, sn->len); /* copy the issuer */ - PORT_Memcpy( &certKey.data[sn->len], issuer->data, issuer->len); + PORT_Memcpy(&certKey.data[sn->len], issuer->data, issuer->len); certKey.len = sn->len + issuer->len; trust = nsslowcert_FindTrustByKey(handle, &certKey); - + pkcs11_freeStaticData(certKey.data, keyBuf); - - return(trust); + + return (trust); } /* @@ -4898,25 +4891,25 @@ nsslowcert_FindCertByDERCert(NSSLOWCERTCertDBHandle *handle, SECItem *derCert) SECItem certKey; SECStatus rv; NSSLOWCERTCertificate *cert = NULL; - + /* create a scratch arena */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - return(NULL); + if (arena == NULL) { + return (NULL); } - + /* extract the database key from the cert */ rv = nsslowcert_KeyFromDERCert(arena, derCert, &certKey); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } /* find the certificate */ cert = nsslowcert_FindCertByKey(handle, &certKey); - + loser: PORT_FreeArena(arena, PR_FALSE); - return(cert); + return (cert); } static void @@ -4924,56 +4917,56 @@ DestroyCertificate(NSSLOWCERTCertificate *cert, PRBool lockdb) { int refCount; NSSLOWCERTCertDBHandle *handle; - - if ( cert ) { - handle = cert->dbhandle; + if (cert) { + + handle = cert->dbhandle; - /* - * handle may be NULL, for example if the cert was created with - * nsslowcert_DecodeDERCertificate. - */ - if ( lockdb && handle ) { - nsslowcert_LockDB(handle); - } + /* + * handle may be NULL, for example if the cert was created with + * nsslowcert_DecodeDERCertificate. + */ + if (lockdb && handle) { + nsslowcert_LockDB(handle); + } nsslowcert_LockCertRefCount(cert); - PORT_Assert(cert->referenceCount > 0); - refCount = --cert->referenceCount; + PORT_Assert(cert->referenceCount > 0); + refCount = --cert->referenceCount; nsslowcert_UnlockCertRefCount(cert); - if ( refCount == 0 ) { - certDBEntryCert *entry = cert->dbEntry; + if (refCount == 0) { + certDBEntryCert *entry = cert->dbEntry; - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); + if (entry) { + DestroyDBEntry((certDBEntry *)entry); } - pkcs11_freeNickname(cert->nickname,cert->nicknameSpace); - pkcs11_freeNickname(cert->emailAddr,cert->emailAddrSpace); - pkcs11_freeStaticData(cert->certKey.data,cert->certKeySpace); - cert->certKey.data = NULL; - cert->nickname = NULL; - - /* zero cert before freeing. Any stale references to this cert - * after this point will probably cause an exception. */ - PORT_Memset(cert, 0, sizeof *cert); - - /* use reflock to protect the free list */ - nsslowcert_LockFreeList(); - if (certListCount > MAX_CERT_LIST_COUNT) { - PORT_Free(cert); - } else { - certListCount++; - cert->next = certListHead; - certListHead = cert; - } - nsslowcert_UnlockFreeList(); - cert = NULL; + pkcs11_freeNickname(cert->nickname, cert->nicknameSpace); + pkcs11_freeNickname(cert->emailAddr, cert->emailAddrSpace); + pkcs11_freeStaticData(cert->certKey.data, cert->certKeySpace); + cert->certKey.data = NULL; + cert->nickname = NULL; + + /* zero cert before freeing. Any stale references to this cert + * after this point will probably cause an exception. */ + PORT_Memset(cert, 0, sizeof *cert); + + /* use reflock to protect the free list */ + nsslowcert_LockFreeList(); + if (certListCount > MAX_CERT_LIST_COUNT) { + PORT_Free(cert); + } else { + certListCount++; + cert->next = certListHead; + certListHead = cert; + } + nsslowcert_UnlockFreeList(); + cert = NULL; + } + if (lockdb && handle) { + nsslowcert_UnlockDB(handle); } - if ( lockdb && handle ) { - nsslowcert_UnlockDB(handle); - } } return; @@ -4986,13 +4979,13 @@ nsslowcert_CreateCert(void) nsslowcert_LockFreeList(); cert = certListHead; if (cert) { - certListHead = cert->next; - certListCount--; + certListHead = cert->next; + certListCount--; } PORT_Assert(certListCount >= 0); nsslowcert_UnlockFreeList(); if (cert) { - return cert; + return cert; } return PORT_ZNew(NSSLOWCERTCertificate); } @@ -5004,9 +4997,9 @@ DestroyCertFreeList(void) nsslowcert_LockFreeList(); while (NULL != (cert = certListHead)) { - certListCount--; - certListHead = cert->next; - PORT_Free(cert); + certListCount--; + certListHead = cert->next; + PORT_Free(cert); } PORT_Assert(!certListCount); certListCount = 0; @@ -5016,21 +5009,21 @@ DestroyCertFreeList(void) void nsslowcert_DestroyTrust(NSSLOWCERTTrust *trust) { - certDBEntryCert *entry = trust->dbEntry; + certDBEntryCert *entry = trust->dbEntry; - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); + if (entry) { + DestroyDBEntry((certDBEntry *)entry); } - pkcs11_freeStaticData(trust->dbKey.data,trust->dbKeySpace); + pkcs11_freeStaticData(trust->dbKey.data, trust->dbKeySpace); PORT_Memset(trust, 0, sizeof(*trust)); nsslowcert_LockFreeList(); if (trustListCount > MAX_TRUST_LIST_COUNT) { - PORT_Free(trust); + PORT_Free(trust); } else { - trustListCount++; - trust->next = trustListHead; - trustListHead = trust; + trustListCount++; + trust->next = trustListHead; + trustListHead = trust; } nsslowcert_UnlockFreeList(); @@ -5056,38 +5049,38 @@ nsslowcert_DestroyCertificateNoLocking(NSSLOWCERTCertificate *cert) * caching stuff used by certificates....? */ certDBEntryRevocation * -nsslowcert_FindCrlByKey(NSSLOWCERTCertDBHandle *handle, - SECItem *crlKey, PRBool isKRL) +nsslowcert_FindCrlByKey(NSSLOWCERTCertDBHandle *handle, + SECItem *crlKey, PRBool isKRL) { SECItem keyitem; SECStatus rv; PLArenaPool *arena = NULL; certDBEntryRevocation *entry = NULL; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; - + certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation + : certDBEntryTypeRevocation; + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if ( arena == NULL ) { - goto loser; + if (arena == NULL) { + goto loser; } - + rv = EncodeDBGenericKey(crlKey, arena, &keyitem, crlType); - if ( rv != SECSuccess ) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - + /* find in perm database */ entry = ReadDBCrlEntry(handle, crlKey, crlType); - - if ( entry == NULL ) { - goto loser; + + if (entry == NULL) { + goto loser; } loser: - if ( arena ) { - PORT_FreeArena(arena, PR_FALSE); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); } - + return entry; } @@ -5095,32 +5088,34 @@ loser: * replace the existing URL in the data base with a new one */ static SECStatus -nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL) +nsslowcert_UpdateCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, + SECItem *crlKey, char *url, PRBool isKRL) { SECStatus rv = SECFailure; certDBEntryRevocation *entry = NULL; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; + certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation + : certDBEntryTypeRevocation; DeleteDBCrlEntry(handle, crlKey, crlType); /* Write the new entry into the data base */ entry = NewDBCrlEntry(derCrl, url, crlType, 0); - if (entry == NULL) goto done; + if (entry == NULL) + goto done; rv = WriteDBCrlEntry(handle, entry, crlKey); - if (rv != SECSuccess) goto done; + if (rv != SECSuccess) + goto done; done: if (entry) { - DestroyDBEntry((certDBEntry *)entry); + DestroyDBEntry((certDBEntry *)entry); } return rv; } SECStatus -nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, - SECItem *crlKey, char *url, PRBool isKRL) +nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, + SECItem *crlKey, char *url, PRBool isKRL) { SECStatus rv; @@ -5131,29 +5126,29 @@ nsslowcert_AddCrl(NSSLOWCERTCertDBHandle *handle, SECItem *derCrl, SECStatus nsslowcert_DeletePermCRL(NSSLOWCERTCertDBHandle *handle, const SECItem *derName, - PRBool isKRL) + PRBool isKRL) { SECStatus rv; - certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation - : certDBEntryTypeRevocation; - + certDBEntryType crlType = isKRL ? certDBEntryTypeKeyRevocation + : certDBEntryTypeRevocation; + rv = DeleteDBCrlEntry(handle, derName, crlType); - if (rv != SECSuccess) goto done; - + if (rv != SECSuccess) + goto done; + done: return rv; } - PRBool nsslowcert_hasTrust(NSSLOWCERTCertTrust *trust) { if (trust == NULL) { - return PR_FALSE; + return PR_FALSE; } - return !((trust->sslFlags & CERTDB_TRUSTED_UNKNOWN) && - (trust->emailFlags & CERTDB_TRUSTED_UNKNOWN) && - (trust->objectSigningFlags & CERTDB_TRUSTED_UNKNOWN)); + return !((trust->sslFlags & CERTDB_TRUSTED_UNKNOWN) && + (trust->emailFlags & CERTDB_TRUSTED_UNKNOWN) && + (trust->objectSigningFlags & CERTDB_TRUSTED_UNKNOWN)); } /* @@ -5162,33 +5157,33 @@ nsslowcert_hasTrust(NSSLOWCERTCertTrust *trust) * the case when there is no profile. */ static SECStatus -nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, - char *emailAddr, SECItem *derSubject, SECItem *emailProfile, - SECItem *profileTime) +nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, + char *emailAddr, SECItem *derSubject, SECItem *emailProfile, + SECItem *profileTime) { certDBEntrySMime *entry = NULL; - SECStatus rv = SECFailure;; - + SECStatus rv = SECFailure; + ; /* find our existing entry */ entry = nsslowcert_ReadDBSMimeEntry(dbhandle, emailAddr); - if ( entry ) { - /* keep our old db entry consistant for old applications. */ - if (!SECITEM_ItemsAreEqual(derSubject, &entry->subjectName)) { - nsslowcert_UpdateSubjectEmailAddr(dbhandle, &entry->subjectName, - emailAddr, nsslowcert_remove); - } - DestroyDBEntry((certDBEntry *)entry); - entry = NULL; + if (entry) { + /* keep our old db entry consistant for old applications. */ + if (!SECITEM_ItemsAreEqual(derSubject, &entry->subjectName)) { + nsslowcert_UpdateSubjectEmailAddr(dbhandle, &entry->subjectName, + emailAddr, nsslowcert_remove); + } + DestroyDBEntry((certDBEntry *)entry); + entry = NULL; } /* now save the entry */ entry = NewDBSMimeEntry(emailAddr, derSubject, emailProfile, - profileTime, 0); - if ( entry == NULL ) { - rv = SECFailure; - goto loser; + profileTime, 0); + if (entry == NULL) { + rv = SECFailure; + goto loser; } nsslowcert_LockDB(dbhandle); @@ -5198,47 +5193,47 @@ nsslowcert_UpdateSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, /* link subject entry back here */ rv = nsslowcert_UpdateSubjectEmailAddr(dbhandle, derSubject, emailAddr, - nsslowcert_add); - if ( rv != SECSuccess ) { - nsslowcert_UnlockDB(dbhandle); - goto loser; + nsslowcert_add); + if (rv != SECSuccess) { + nsslowcert_UnlockDB(dbhandle); + goto loser; } - + rv = WriteDBSMimeEntry(dbhandle, entry); - if ( rv != SECSuccess ) { - nsslowcert_UnlockDB(dbhandle); - goto loser; + if (rv != SECSuccess) { + nsslowcert_UnlockDB(dbhandle); + goto loser; } nsslowcert_UnlockDB(dbhandle); rv = SECSuccess; - + loser: - if ( entry ) { - DestroyDBEntry((certDBEntry *)entry); + if (entry) { + DestroyDBEntry((certDBEntry *)entry); } - return(rv); + return (rv); } SECStatus -nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, - SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime) +nsslowcert_SaveSMimeProfile(NSSLOWCERTCertDBHandle *dbhandle, char *emailAddr, + SECItem *derSubject, SECItem *emailProfile, SECItem *profileTime) { - SECStatus rv = SECFailure;; + SECStatus rv = SECFailure; + ; + rv = nsslowcert_UpdateSMimeProfile(dbhandle, emailAddr, + derSubject, emailProfile, profileTime); - rv = nsslowcert_UpdateSMimeProfile(dbhandle, emailAddr, - derSubject, emailProfile, profileTime); - - return(rv); + return (rv); } void nsslowcert_DestroyFreeLists(void) { if (freeListLock == NULL) { - return; + return; } DestroyCertEntryFreeList(); DestroyTrustFreeList(); @@ -5251,90 +5246,88 @@ void nsslowcert_DestroyGlobalLocks(void) { if (dbLock) { - SKIP_AFTER_FORK(PZ_DestroyLock(dbLock)); - dbLock = NULL; + SKIP_AFTER_FORK(PZ_DestroyLock(dbLock)); + dbLock = NULL; } if (certRefCountLock) { - SKIP_AFTER_FORK(PZ_DestroyLock(certRefCountLock)); - certRefCountLock = NULL; + SKIP_AFTER_FORK(PZ_DestroyLock(certRefCountLock)); + certRefCountLock = NULL; } if (certTrustLock) { - SKIP_AFTER_FORK(PZ_DestroyLock(certTrustLock)); - certTrustLock = NULL; + SKIP_AFTER_FORK(PZ_DestroyLock(certTrustLock)); + certTrustLock = NULL; } } certDBEntry * -nsslowcert_DecodeAnyDBEntry(SECItem *dbData, const SECItem *dbKey, - certDBEntryType entryType, void *pdata) +nsslowcert_DecodeAnyDBEntry(SECItem *dbData, const SECItem *dbKey, + certDBEntryType entryType, void *pdata) { PLArenaPool *arena = NULL; certDBEntry *entry; SECStatus rv; SECItem dbEntry; - if ((dbData->len < SEC_DB_ENTRY_HEADER_LEN) || (dbKey->len == 0)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; } dbEntry.data = &dbData->data[SEC_DB_ENTRY_HEADER_LEN]; - dbEntry.len = dbData->len - SEC_DB_ENTRY_HEADER_LEN; + dbEntry.len = dbData->len - SEC_DB_ENTRY_HEADER_LEN; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto loser; + goto loser; } entry = PORT_ArenaZNew(arena, certDBEntry); if (!entry) - goto loser; + goto loser; entry->common.version = (unsigned int)dbData->data[0]; - entry->common.flags = (unsigned int)dbData->data[2]; - entry->common.type = entryType; - entry->common.arena = arena; + entry->common.flags = (unsigned int)dbData->data[2]; + entry->common.type = entryType; + entry->common.arena = arena; switch (entryType) { - case certDBEntryTypeContentVersion: /* This type appears to be unused */ - case certDBEntryTypeVersion: /* This type has only the common hdr */ - rv = SECSuccess; - break; + case certDBEntryTypeContentVersion: /* This type appears to be unused */ + case certDBEntryTypeVersion: /* This type has only the common hdr */ + rv = SECSuccess; + break; - case certDBEntryTypeSubject: - rv = DecodeDBSubjectEntry(&entry->subject, &dbEntry, dbKey); - break; + case certDBEntryTypeSubject: + rv = DecodeDBSubjectEntry(&entry->subject, &dbEntry, dbKey); + break; - case certDBEntryTypeNickname: - rv = DecodeDBNicknameEntry(&entry->nickname, &dbEntry, - (char *)dbKey->data); - break; + case certDBEntryTypeNickname: + rv = DecodeDBNicknameEntry(&entry->nickname, &dbEntry, + (char *)dbKey->data); + break; - /* smime profiles need entries created after the certs have - * been imported, loop over them in a second run */ - case certDBEntryTypeSMimeProfile: - rv = DecodeDBSMimeEntry(&entry->smime, &dbEntry, (char *)dbKey->data); - break; + /* smime profiles need entries created after the certs have + * been imported, loop over them in a second run */ + case certDBEntryTypeSMimeProfile: + rv = DecodeDBSMimeEntry(&entry->smime, &dbEntry, (char *)dbKey->data); + break; - case certDBEntryTypeCert: - rv = DecodeDBCertEntry(&entry->cert, &dbEntry); - break; + case certDBEntryTypeCert: + rv = DecodeDBCertEntry(&entry->cert, &dbEntry); + break; - case certDBEntryTypeKeyRevocation: - case certDBEntryTypeRevocation: - rv = DecodeDBCrlEntry(&entry->revocation, &dbEntry); - break; + case certDBEntryTypeKeyRevocation: + case certDBEntryTypeRevocation: + rv = DecodeDBCrlEntry(&entry->revocation, &dbEntry); + break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } if (rv == SECSuccess) - return entry; + return entry; loser: if (arena) - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } - diff --git a/nss/lib/softoken/legacydb/pcertt.h b/nss/lib/softoken/legacydb/pcertt.h index fd5e17c..7eaa82d 100644 --- a/nss/lib/softoken/legacydb/pcertt.h +++ b/nss/lib/softoken/legacydb/pcertt.h @@ -18,17 +18,17 @@ #include "prmon.h" /* Non-opaque objects */ -typedef struct NSSLOWCERTCertDBHandleStr NSSLOWCERTCertDBHandle; -typedef struct NSSLOWCERTCertKeyStr NSSLOWCERTCertKey; - -typedef struct NSSLOWCERTTrustStr NSSLOWCERTTrust; -typedef struct NSSLOWCERTCertTrustStr NSSLOWCERTCertTrust; -typedef struct NSSLOWCERTCertificateStr NSSLOWCERTCertificate; -typedef struct NSSLOWCERTCertificateListStr NSSLOWCERTCertificateList; -typedef struct NSSLOWCERTIssuerAndSNStr NSSLOWCERTIssuerAndSN; -typedef struct NSSLOWCERTSignedDataStr NSSLOWCERTSignedData; -typedef struct NSSLOWCERTSubjectPublicKeyInfoStr NSSLOWCERTSubjectPublicKeyInfo; -typedef struct NSSLOWCERTValidityStr NSSLOWCERTValidity; +typedef struct NSSLOWCERTCertDBHandleStr NSSLOWCERTCertDBHandle; +typedef struct NSSLOWCERTCertKeyStr NSSLOWCERTCertKey; + +typedef struct NSSLOWCERTTrustStr NSSLOWCERTTrust; +typedef struct NSSLOWCERTCertTrustStr NSSLOWCERTCertTrust; +typedef struct NSSLOWCERTCertificateStr NSSLOWCERTCertificate; +typedef struct NSSLOWCERTCertificateListStr NSSLOWCERTCertificateList; +typedef struct NSSLOWCERTIssuerAndSNStr NSSLOWCERTIssuerAndSN; +typedef struct NSSLOWCERTSignedDataStr NSSLOWCERTSignedData; +typedef struct NSSLOWCERTSubjectPublicKeyInfoStr NSSLOWCERTSubjectPublicKeyInfo; +typedef struct NSSLOWCERTValidityStr NSSLOWCERTValidity; /* ** An X.509 validity object @@ -81,10 +81,10 @@ struct NSSLOWCERTCertTrustStr { struct NSSLOWCERTTrustStr { NSSLOWCERTTrust *next; NSSLOWCERTCertDBHandle *dbhandle; - SECItem dbKey; /* database key for this cert */ - certDBEntryCert *dbEntry; /* database entry struct */ + SECItem dbKey; /* database key for this cert */ + certDBEntryCert *dbEntry; /* database entry struct */ NSSLOWCERTCertTrust *trust; - SECItem *derCert; /* original DER for the cert */ + SECItem *derCert; /* original DER for the cert */ unsigned char dbKeySpace[512]; }; @@ -101,17 +101,17 @@ struct NSSLOWCERTCertificateStr { NSSLOWCERTCertificate *next; NSSLOWCERTCertDBHandle *dbhandle; - SECItem derCert; /* original DER for the cert */ - SECItem derIssuer; /* DER for issuer name */ + SECItem derCert; /* original DER for the cert */ + SECItem derIssuer; /* DER for issuer name */ SECItem derSN; SECItem serialNumber; - SECItem derSubject; /* DER for subject name */ + SECItem derSubject; /* DER for subject name */ SECItem derSubjKeyInfo; NSSLOWCERTSubjectPublicKeyInfo *subjectPublicKeyInfo; - SECItem certKey; /* database key for this cert */ + SECItem certKey; /* database key for this cert */ SECItem validity; - certDBEntryCert *dbEntry; /* database entry struct */ - SECItem subjectKeyID; /* x509v3 subject key identifier */ + certDBEntryCert *dbEntry; /* database entry struct */ + SECItem subjectKeyID; /* x509v3 subject key identifier */ SECItem extensions; char *nickname; char *emailAddr; @@ -127,12 +127,12 @@ struct NSSLOWCERTCertificateStr { unsigned char certKeySpace[512]; }; -#define SEC_CERTIFICATE_VERSION_1 0 /* default created */ -#define SEC_CERTIFICATE_VERSION_2 1 /* v2 */ -#define SEC_CERTIFICATE_VERSION_3 2 /* v3 extensions */ +#define SEC_CERTIFICATE_VERSION_1 0 /* default created */ +#define SEC_CERTIFICATE_VERSION_2 1 /* v2 */ +#define SEC_CERTIFICATE_VERSION_3 2 /* v3 extensions */ -#define SEC_CRL_VERSION_1 0 /* default */ -#define SEC_CRL_VERSION_2 1 /* v2 extensions */ +#define SEC_CRL_VERSION_1 0 /* default */ +#define SEC_CRL_VERSION_2 1 /* v2 extensions */ #define NSS_MAX_LEGACY_DB_KEY_SIZE (60 * 1024) @@ -141,36 +141,36 @@ struct NSSLOWCERTIssuerAndSNStr { SECItem serialNumber; }; -typedef SECStatus (* NSSLOWCERTCertCallback)(NSSLOWCERTCertificate *cert, void *arg); +typedef SECStatus (*NSSLOWCERTCertCallback)(NSSLOWCERTCertificate *cert, void *arg); /* This is the typedef for the callback passed to nsslowcert_OpenCertDB() */ /* callback to return database name based on version number */ -typedef char * (*NSSLOWCERTDBNameFunc)(void *arg, int dbVersion); +typedef char *(*NSSLOWCERTDBNameFunc)(void *arg, int dbVersion); /* XXX Lisa thinks the template declarations belong in cert.h, not here? */ -#include "secasn1t.h" /* way down here because I expect template stuff to - * move out of here anyway */ +#include "secasn1t.h" /* way down here because I expect template stuff to + * move out of here anyway */ /* * Certificate Database related definitions and data structures */ /* version number of certificate database */ -#define CERT_DB_FILE_VERSION 8 -#define CERT_DB_V7_FILE_VERSION 7 -#define CERT_DB_CONTENT_VERSION 2 +#define CERT_DB_FILE_VERSION 8 +#define CERT_DB_V7_FILE_VERSION 7 +#define CERT_DB_CONTENT_VERSION 2 -#define SEC_DB_ENTRY_HEADER_LEN 3 -#define SEC_DB_KEY_HEADER_LEN 1 +#define SEC_DB_ENTRY_HEADER_LEN 3 +#define SEC_DB_KEY_HEADER_LEN 1 /* All database entries have this form: - * - * byte offset field - * ----------- ----- - * 0 version - * 1 type - * 2 flags + * + * byte offset field + * ----------- ----- + * 0 version + * 1 type + * 2 flags */ /* database entry types */ @@ -196,26 +196,26 @@ typedef struct { /* * Certificate entry: * - * byte offset field - * ----------- ----- - * 0 sslFlags-msb - * 1 sslFlags-lsb - * 2 emailFlags-msb - * 3 emailFlags-lsb - * 4 objectSigningFlags-msb - * 5 objectSigningFlags-lsb - * 6 derCert-len-msb - * 7 derCert-len-lsb - * 8 nickname-len-msb - * 9 nickname-len-lsb - * ... derCert - * ... nickname + * byte offset field + * ----------- ----- + * 0 sslFlags-msb + * 1 sslFlags-lsb + * 2 emailFlags-msb + * 3 emailFlags-lsb + * 4 objectSigningFlags-msb + * 5 objectSigningFlags-lsb + * 6 derCert-len-msb + * 7 derCert-len-lsb + * 8 nickname-len-msb + * 9 nickname-len-lsb + * ... derCert + * ... nickname * * NOTE: the nickname string as stored in the database is null terminated, - * in other words, the last byte of the db entry is always 0 - * if a nickname is present. + * in other words, the last byte of the db entry is always 0 + * if a nickname is present. * NOTE: if nickname is not present, then nickname-len-msb and - * nickname-len-lsb will both be zero. + * nickname-len-lsb will both be zero. */ struct _certDBEntryCert { certDBEntryCommon common; @@ -230,11 +230,11 @@ struct _certDBEntryCert { /* * Certificate Nickname entry: * - * byte offset field - * ----------- ----- - * 0 subjectname-len-msb - * 1 subjectname-len-lsb - * 2... subjectname + * byte offset field + * ----------- ----- + * 0 subjectname-len-msb + * 1 subjectname-len-lsb + * 2... subjectname * * The database key for this type of entry is a nickname string * The "subjectname" value is the DER encoded DN of the identity @@ -251,22 +251,22 @@ typedef struct { /* * Certificate Subject entry: * - * byte offset field - * ----------- ----- - * 0 ncerts-msb - * 1 ncerts-lsb - * 2 nickname-msb - * 3 nickname-lsb - * 4 emailAddr-msb - * 5 emailAddr-lsb - * ... nickname - * ... emailAddr - * ...+2*i certkey-len-msb - * ...+1+2*i certkey-len-lsb - * ...+2*ncerts+2*i keyid-len-msb - * ...+1+2*ncerts+2*i keyid-len-lsb - * ... certkeys - * ... keyids + * byte offset field + * ----------- ----- + * 0 ncerts-msb + * 1 ncerts-lsb + * 2 nickname-msb + * 3 nickname-lsb + * 4 emailAddr-msb + * 5 emailAddr-lsb + * ... nickname + * ... emailAddr + * ...+2*i certkey-len-msb + * ...+1+2*i certkey-len-lsb + * ...+2*ncerts+2*i keyid-len-msb + * ...+1+2*ncerts+2*i keyid-len-lsb + * ... certkeys + * ... keyids * * The database key for this type of entry is the DER encoded subject name * The "certkey" value is an array of certificate database lookup keys that @@ -290,17 +290,17 @@ typedef struct _certDBEntrySubject { /* * Certificate SMIME profile entry: * - * byte offset field - * ----------- ----- - * 0 subjectname-len-msb - * 1 subjectname-len-lsb - * 2 smimeoptions-len-msb - * 3 smimeoptions-len-lsb - * 4 options-date-len-msb - * 5 options-date-len-lsb - * 6... subjectname - * ... smimeoptions - * ... options-date + * byte offset field + * ----------- ----- + * 0 subjectname-len-msb + * 1 subjectname-len-lsb + * 2 smimeoptions-len-msb + * 3 smimeoptions-len-lsb + * 4 options-date-len-msb + * 5 options-date-len-lsb + * 6... subjectname + * ... smimeoptions + * ... options-date * * The database key for this type of entry is the email address string * The "subjectname" value is the DER encoded DN of the identity @@ -324,34 +324,34 @@ typedef struct { /* * Crl/krl entry: * - * byte offset field - * ----------- ----- - * 0 derCert-len-msb - * 1 derCert-len-lsb - * 2 url-len-msb - * 3 url-len-lsb - * ... derCert - * ... url + * byte offset field + * ----------- ----- + * 0 derCert-len-msb + * 1 derCert-len-lsb + * 2 url-len-msb + * 3 url-len-lsb + * ... derCert + * ... url * * NOTE: the url string as stored in the database is null terminated, - * in other words, the last byte of the db entry is always 0 - * if a nickname is present. + * in other words, the last byte of the db entry is always 0 + * if a nickname is present. * NOTE: if url is not present, then url-len-msb and - * url-len-lsb will both be zero. + * url-len-lsb will both be zero. */ -#define DB_CRL_ENTRY_HEADER_LEN 4 +#define DB_CRL_ENTRY_HEADER_LEN 4 struct _certDBEntryRevocation { certDBEntryCommon common; - SECItem derCrl; - char *url; /* where to load the crl from */ + SECItem derCrl; + char *url; /* where to load the crl from */ }; /* * Database Version Entry: * - * byte offset field - * ----------- ----- - * only the low level header... + * byte offset field + * ----------- ----- + * only the low level header... * * The database key for this type of entry is the string "Version" */ @@ -365,9 +365,9 @@ typedef struct { /* * Database Content Version Entry: * - * byte offset field - * ----------- ----- - * 0 contentVersion + * byte offset field + * ----------- ----- + * 0 contentVersion * * The database key for this type of entry is the string "ContentVersion" */ @@ -380,39 +380,39 @@ typedef struct { #define SEC_DB_CONTENT_VERSION_KEY_LEN sizeof(SEC_DB_CONTENT_VERSION_KEY) typedef union { - certDBEntryCommon common; - certDBEntryCert cert; + certDBEntryCommon common; + certDBEntryCert cert; certDBEntryContentVersion content; - certDBEntryNickname nickname; - certDBEntryRevocation revocation; - certDBEntrySMime smime; - certDBEntrySubject subject; - certDBEntryVersion version; + certDBEntryNickname nickname; + certDBEntryRevocation revocation; + certDBEntrySMime smime; + certDBEntrySubject subject; + certDBEntryVersion version; } certDBEntry; /* length of the fixed part of a database entry */ -#define DBCERT_V4_HEADER_LEN 7 -#define DB_CERT_V5_ENTRY_HEADER_LEN 7 -#define DB_CERT_V6_ENTRY_HEADER_LEN 7 -#define DB_CERT_ENTRY_HEADER_LEN 10 +#define DBCERT_V4_HEADER_LEN 7 +#define DB_CERT_V5_ENTRY_HEADER_LEN 7 +#define DB_CERT_V6_ENTRY_HEADER_LEN 7 +#define DB_CERT_ENTRY_HEADER_LEN 10 /* common flags for all types of certificates */ -#define CERTDB_TERMINAL_RECORD (1u<<0) -#define CERTDB_TRUSTED (1u<<1) -#define CERTDB_SEND_WARN (1u<<2) -#define CERTDB_VALID_CA (1u<<3) -#define CERTDB_TRUSTED_CA (1u<<4) /* trusted for issuing server certs */ -#define CERTDB_NS_TRUSTED_CA (1u<<5) -#define CERTDB_USER (1u<<6) -#define CERTDB_TRUSTED_CLIENT_CA (1u<<7) /* trusted for issuing client certs */ -#define CERTDB_INVISIBLE_CA (1u<<8) /* don't show in UI */ -#define CERTDB_GOVT_APPROVED_CA (1u<<9) /* can do strong crypto in export ver */ -#define CERTDB_MUST_VERIFY (1u<<10) /* explicitly don't trust this cert */ -#define CERTDB_TRUSTED_UNKNOWN (1u<<11) /* accept trust from another source */ +#define CERTDB_TERMINAL_RECORD (1u << 0) +#define CERTDB_TRUSTED (1u << 1) +#define CERTDB_SEND_WARN (1u << 2) +#define CERTDB_VALID_CA (1u << 3) +#define CERTDB_TRUSTED_CA (1u << 4) /* trusted for issuing server certs */ +#define CERTDB_NS_TRUSTED_CA (1u << 5) +#define CERTDB_USER (1u << 6) +#define CERTDB_TRUSTED_CLIENT_CA (1u << 7) /* trusted for issuing client certs */ +#define CERTDB_INVISIBLE_CA (1u << 8) /* don't show in UI */ +#define CERTDB_GOVT_APPROVED_CA (1u << 9) /* can do strong crypto in export ver */ +#define CERTDB_MUST_VERIFY (1u << 10) /* explicitly don't trust this cert */ +#define CERTDB_TRUSTED_UNKNOWN (1u << 11) /* accept trust from another source */ /* bits not affected by the CKO_NETSCAPE_TRUST object */ -#define CERTDB_PRESERVE_TRUST_BITS (CERTDB_USER | \ - CERTDB_NS_TRUSTED_CA | CERTDB_VALID_CA | CERTDB_INVISIBLE_CA | \ - CERTDB_GOVT_APPROVED_CA) +#define CERTDB_PRESERVE_TRUST_BITS (CERTDB_USER | \ + CERTDB_NS_TRUSTED_CA | CERTDB_VALID_CA | CERTDB_INVISIBLE_CA | \ + CERTDB_GOVT_APPROVED_CA) #endif /* _PCERTT_H_ */ diff --git a/nss/lib/softoken/legacydb/pk11db.c b/nss/lib/softoken/legacydb/pk11db.c index 7d0a03c..a7421c8 100644 --- a/nss/lib/softoken/legacydb/pk11db.c +++ b/nss/lib/softoken/legacydb/pk11db.c @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * The following code handles the storage of PKCS 11 modules used by the * NSS. This file is written to abstract away how the modules are * stored so we can deside that later. @@ -12,18 +12,25 @@ #include "secerr.h" #include "utilpars.h" -#define FREE_CLEAR(p) if (p) { PORT_Free(p); p = NULL; } +#define FREE_CLEAR(p) \ + if (p) { \ + PORT_Free(p); \ + p = NULL; \ + } /* Construct a database key for a given module */ -static SECStatus lgdb_MakeKey(DBT *key, char * module) { +static SECStatus +lgdb_MakeKey(DBT *key, char *module) +{ int len = 0; char *commonName; - commonName = NSSUTIL_ArgGetParamValue("name",module); + commonName = NSSUTIL_ArgGetParamValue("name", module); if (commonName == NULL) { - commonName = NSSUTIL_ArgGetParamValue("library",module); + commonName = NSSUTIL_ArgGetParamValue("library", module); } - if (commonName == NULL) return SECFailure; + if (commonName == NULL) + return SECFailure; len = PORT_Strlen(commonName); key->data = commonName; key->size = len; @@ -31,11 +38,11 @@ static SECStatus lgdb_MakeKey(DBT *key, char * module) { } /* free out constructed database key */ -static void -lgdb_FreeKey(DBT *key) +static void +lgdb_FreeKey(DBT *key) { if (key->data) { - PORT_Free(key->data); + PORT_Free(key->data); } key->data = NULL; key->size = 0; @@ -58,7 +65,7 @@ struct lgdbDataStr { unsigned char isModuleDBOnly; unsigned char isCritical; unsigned char reserved[4]; - unsigned char names[6]; /* enough space for the length fields */ + unsigned char names[6]; /* enough space for the length fields */ }; struct lgdbSlotDataStr { @@ -77,162 +84,165 @@ struct lgdbSlotDataStr { #define LGDB_DB_NOUI_VERSION_MAJOR 0 #define LGDB_DB_NOUI_VERSION_MINOR 4 -#define LGDB_PUTSHORT(dest,src) \ - (dest)[1] = (unsigned char) ((src)&0xff); \ - (dest)[0] = (unsigned char) (((src) >> 8) & 0xff); -#define LGDB_PUTLONG(dest,src) \ - (dest)[3] = (unsigned char) ((src)&0xff); \ - (dest)[2] = (unsigned char) (((src) >> 8) & 0xff); \ - (dest)[1] = (unsigned char) (((src) >> 16) & 0xff); \ - (dest)[0] = (unsigned char) (((src) >> 24) & 0xff); +#define LGDB_PUTSHORT(dest, src) \ + (dest)[1] = (unsigned char)((src)&0xff); \ + (dest)[0] = (unsigned char)(((src) >> 8) & 0xff); +#define LGDB_PUTLONG(dest, src) \ + (dest)[3] = (unsigned char)((src)&0xff); \ + (dest)[2] = (unsigned char)(((src) >> 8) & 0xff); \ + (dest)[1] = (unsigned char)(((src) >> 16) & 0xff); \ + (dest)[0] = (unsigned char)(((src) >> 24) & 0xff); #define LGDB_GETSHORT(src) \ - ((unsigned short) (((src)[0] << 8) | (src)[1])) -#define LGDB_GETLONG(src) \ - ((unsigned long) (( (unsigned long) (src)[0] << 24) | \ - ( (unsigned long) (src)[1] << 16) | \ - ( (unsigned long) (src)[2] << 8) | \ - (unsigned long) (src)[3])) + ((unsigned short)(((src)[0] << 8) | (src)[1])) +#define LGDB_GETLONG(src) \ + ((unsigned long)(((unsigned long)(src)[0] << 24) | \ + ((unsigned long)(src)[1] << 16) | \ + ((unsigned long)(src)[2] << 8) | \ + (unsigned long)(src)[3])) /* - * build a data base entry from a module + * build a data base entry from a module */ -static SECStatus -lgdb_EncodeData(DBT *data, char * module) +static SECStatus +lgdb_EncodeData(DBT *data, char *module) { lgdbData *encoded = NULL; lgdbSlotData *slot; - unsigned char *dataPtr; + unsigned char *dataPtr, *offsetPtr; unsigned short len, len2 = 0, len3 = 0; int count = 0; unsigned short offset; int dataLen, i; unsigned long order; - unsigned long ssl[2]; - char *commonName = NULL , *dllName = NULL, *param = NULL, *nss = NULL; + unsigned long ssl[2]; + char *commonName = NULL, *dllName = NULL, *param = NULL, *nss = NULL; char *slotParams, *ciphers; struct NSSUTILPreSlotInfoStr *slotInfo = NULL; SECStatus rv = SECFailure; - rv = NSSUTIL_ArgParseModuleSpec(module,&dllName,&commonName,¶m,&nss); - if (rv != SECSuccess) return rv; + rv = NSSUTIL_ArgParseModuleSpec(module, &dllName, &commonName, ¶m, &nss); + if (rv != SECSuccess) + return rv; rv = SECFailure; if (commonName == NULL) { - /* set error */ - goto loser; + /* set error */ + goto loser; } len = PORT_Strlen(commonName); if (dllName) { - len2 = PORT_Strlen(dllName); + len2 = PORT_Strlen(dllName); } if (param) { - len3 = PORT_Strlen(param); + len3 = PORT_Strlen(param); } - slotParams = NSSUTIL_ArgGetParamValue("slotParams",nss); - slotInfo = NSSUTIL_ArgParseSlotInfo(NULL,slotParams,&count); - if (slotParams) PORT_Free(slotParams); + slotParams = NSSUTIL_ArgGetParamValue("slotParams", nss); + slotInfo = NSSUTIL_ArgParseSlotInfo(NULL, slotParams, &count); + if (slotParams) + PORT_Free(slotParams); if (count && slotInfo == NULL) { - /* set error */ - goto loser; + /* set error */ + goto loser; } dataLen = sizeof(lgdbData) + len + len2 + len3 + sizeof(unsigned short) + - count*sizeof(lgdbSlotData); + count * sizeof(lgdbSlotData); - data->data = (unsigned char *) PORT_ZAlloc(dataLen); + data->data = (unsigned char *)PORT_ZAlloc(dataLen); encoded = (lgdbData *)data->data; - dataPtr = (unsigned char *) data->data; + dataPtr = (unsigned char *)data->data; data->size = dataLen; if (encoded == NULL) { - /* set error */ - goto loser; + /* set error */ + goto loser; } encoded->major = LGDB_DB_VERSION_MAJOR; encoded->minor = LGDB_DB_VERSION_MINOR; - encoded->internal = (unsigned char) - (NSSUTIL_ArgHasFlag("flags","internal",nss) ? 1 : 0); - encoded->fips = (unsigned char) - (NSSUTIL_ArgHasFlag("flags","FIPS",nss) ? 1 : 0); - encoded->isModuleDB = (unsigned char) - (NSSUTIL_ArgHasFlag("flags","isModuleDB",nss) ? 1 : 0); - encoded->isModuleDBOnly = (unsigned char) - (NSSUTIL_ArgHasFlag("flags","isModuleDBOnly",nss) ? 1 : 0); - encoded->isCritical = (unsigned char) - (NSSUTIL_ArgHasFlag("flags","critical",nss) ? 1 : 0); + encoded->internal = (unsigned char)(NSSUTIL_ArgHasFlag("flags", "internal", nss) ? 1 : 0); + encoded->fips = (unsigned char)(NSSUTIL_ArgHasFlag("flags", "FIPS", nss) ? 1 : 0); + encoded->isModuleDB = (unsigned char)(NSSUTIL_ArgHasFlag("flags", "isModuleDB", nss) ? 1 : 0); + encoded->isModuleDBOnly = (unsigned char)(NSSUTIL_ArgHasFlag("flags", "isModuleDBOnly", nss) ? 1 : 0); + encoded->isCritical = (unsigned char)(NSSUTIL_ArgHasFlag("flags", "critical", nss) ? 1 : 0); order = NSSUTIL_ArgReadLong("trustOrder", nss, - NSSUTIL_DEFAULT_TRUST_ORDER, NULL); - LGDB_PUTLONG(encoded->trustOrder,order); - order = NSSUTIL_ArgReadLong("cipherOrder", nss, - NSSUTIL_DEFAULT_CIPHER_ORDER, NULL); - LGDB_PUTLONG(encoded->cipherOrder,order); - - - ciphers = NSSUTIL_ArgGetParamValue("ciphers",nss); - NSSUTIL_ArgParseCipherFlags(&ssl[0], ciphers); - LGDB_PUTLONG(encoded->ssl,ssl[0]); - LGDB_PUTLONG(&encoded->ssl[4],ssl[1]); - if (ciphers) PORT_Free(ciphers); - - offset = (unsigned short) offsetof(lgdbData, names); - LGDB_PUTSHORT(encoded->nameStart,offset); - offset = offset + len + len2 + len3 + 3*sizeof(unsigned short); - LGDB_PUTSHORT(encoded->slotOffset,offset); - + NSSUTIL_DEFAULT_TRUST_ORDER, NULL); + LGDB_PUTLONG(encoded->trustOrder, order); + order = NSSUTIL_ArgReadLong("cipherOrder", nss, + NSSUTIL_DEFAULT_CIPHER_ORDER, NULL); + LGDB_PUTLONG(encoded->cipherOrder, order); - LGDB_PUTSHORT(&dataPtr[offset],((unsigned short)count)); - slot = (lgdbSlotData *)(dataPtr+offset+sizeof(unsigned short)); - - offset = 0; - LGDB_PUTSHORT(encoded->names,len); - offset += sizeof(unsigned short); - PORT_Memcpy(&encoded->names[offset],commonName,len); - offset += len; - - - LGDB_PUTSHORT(&encoded->names[offset],len2); - offset += sizeof(unsigned short); - if (len2) PORT_Memcpy(&encoded->names[offset],dllName,len2); - offset += len2; + ciphers = NSSUTIL_ArgGetParamValue("ciphers", nss); + NSSUTIL_ArgParseCipherFlags(&ssl[0], ciphers); + LGDB_PUTLONG(encoded->ssl, ssl[0]); + LGDB_PUTLONG(&encoded->ssl[4], ssl[1]); + if (ciphers) + PORT_Free(ciphers); + + offset = (unsigned short)offsetof(lgdbData, names); + LGDB_PUTSHORT(encoded->nameStart, offset); + offset = offset + len + len2 + len3 + 3 * sizeof(unsigned short); + LGDB_PUTSHORT(encoded->slotOffset, offset); + + LGDB_PUTSHORT(&dataPtr[offset], ((unsigned short)count)); + slot = (lgdbSlotData *)(dataPtr + offset + sizeof(unsigned short)); + + offsetPtr = encoded->names; + LGDB_PUTSHORT(encoded->names, len); + offsetPtr += sizeof(unsigned short); + PORT_Memcpy(offsetPtr, commonName, len); + offsetPtr += len; + + LGDB_PUTSHORT(offsetPtr, len2); + offsetPtr += sizeof(unsigned short); + if (len2) { + PORT_Memcpy(offsetPtr, dllName, len2); + } + offsetPtr += len2; - LGDB_PUTSHORT(&encoded->names[offset],len3); - offset += sizeof(unsigned short); - if (len3) PORT_Memcpy(&encoded->names[offset],param,len3); - offset += len3; + LGDB_PUTSHORT(offsetPtr, len3); + offsetPtr += sizeof(unsigned short); + if (len3) { + PORT_Memcpy(offsetPtr, param, len3); + } + offsetPtr += len3; if (count) { - for (i=0; i < count; i++) { - LGDB_PUTLONG(slot[i].slotID, slotInfo[i].slotID); - LGDB_PUTLONG(slot[i].defaultFlags, - slotInfo[i].defaultFlags); - LGDB_PUTLONG(slot[i].timeout,slotInfo[i].timeout); - slot[i].askpw = slotInfo[i].askpw; - slot[i].hasRootCerts = slotInfo[i].hasRootCerts; - PORT_Memset(slot[i].reserved, 0, sizeof(slot[i].reserved)); - } + for (i = 0; i < count; i++) { + LGDB_PUTLONG(slot[i].slotID, slotInfo[i].slotID); + LGDB_PUTLONG(slot[i].defaultFlags, + slotInfo[i].defaultFlags); + LGDB_PUTLONG(slot[i].timeout, slotInfo[i].timeout); + slot[i].askpw = slotInfo[i].askpw; + slot[i].hasRootCerts = slotInfo[i].hasRootCerts; + PORT_Memset(slot[i].reserved, 0, sizeof(slot[i].reserved)); + } } rv = SECSuccess; loser: - if (commonName) PORT_Free(commonName); - if (dllName) PORT_Free(dllName); - if (param) PORT_Free(param); - if (slotInfo) PORT_Free(slotInfo); - if (nss) PORT_Free(nss); + if (commonName) + PORT_Free(commonName); + if (dllName) + PORT_Free(dllName); + if (param) + PORT_Free(param); + if (slotInfo) + PORT_Free(slotInfo); + if (nss) + PORT_Free(nss); return rv; - } -static void +static void lgdb_FreeData(DBT *data) { if (data->data) { - PORT_Free(data->data); + PORT_Free(data->data); } } @@ -241,11 +251,11 @@ lgdb_FreeSlotStrings(char **slotStrings, int count) { int i; - for (i=0; i < count; i++) { - if (slotStrings[i]) { - PR_smprintf_free(slotStrings[i]); - slotStrings[i] = NULL; - } + for (i = 0; i < count; i++) { + if (slotStrings[i]) { + PR_smprintf_free(slotStrings[i]); + slotStrings[i] = NULL; + } } } @@ -258,88 +268,87 @@ lgdb_DecodeData(char *defParams, DBT *data, PRBool *retInternal) lgdbData *encoded; lgdbSlotData *slots; PLArenaPool *arena; - char *commonName = NULL; - char *dllName = NULL; - char *parameters = NULL; + char *commonName = NULL; + char *dllName = NULL; + char *parameters = NULL; char *nss; char *moduleSpec; - char **slotStrings = NULL; + char **slotStrings = NULL; unsigned char *names; unsigned long slotCount; - unsigned long ssl0 =0; - unsigned long ssl1 =0; + unsigned long ssl0 = 0; + unsigned long ssl1 = 0; unsigned long slotID; unsigned long defaultFlags; unsigned long timeout; - unsigned long trustOrder = NSSUTIL_DEFAULT_TRUST_ORDER; - unsigned long cipherOrder = NSSUTIL_DEFAULT_CIPHER_ORDER; + unsigned long trustOrder = NSSUTIL_DEFAULT_TRUST_ORDER; + unsigned long cipherOrder = NSSUTIL_DEFAULT_CIPHER_ORDER; unsigned short len; - unsigned short namesOffset = 0; /* start of the names block */ - unsigned long namesRunningOffset; /* offset to name we are - * currently processing */ + unsigned short namesOffset = 0; /* start of the names block */ + unsigned long namesRunningOffset; /* offset to name we are + * currently processing */ unsigned short slotOffset; - PRBool isOldVersion = PR_FALSE; + PRBool isOldVersion = PR_FALSE; PRBool internal; PRBool isFIPS; - PRBool isModuleDB =PR_FALSE; - PRBool isModuleDBOnly =PR_FALSE; - PRBool extended =PR_FALSE; + PRBool isModuleDB = PR_FALSE; + PRBool isModuleDBOnly = PR_FALSE; + PRBool extended = PR_FALSE; int i; - arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); - if (arena == NULL) - return NULL; + if (arena == NULL) + return NULL; -#define CHECK_SIZE(x) \ - if ((unsigned int) data->size < (unsigned int)(x)) goto db_loser +#define CHECK_SIZE(x) \ + if ((unsigned int)data->size < (unsigned int)(x)) \ + goto db_loser /* ------------------------------------------------------------- - ** Process the buffer header, which is the lgdbData struct. - ** It may be an old or new version. Check the length for each. + ** Process the buffer header, which is the lgdbData struct. + ** It may be an old or new version. Check the length for each. */ - CHECK_SIZE( offsetof(lgdbData, trustOrder[0]) ); + CHECK_SIZE(offsetof(lgdbData, trustOrder[0])); encoded = (lgdbData *)data->data; - internal = (encoded->internal != 0) ? PR_TRUE: PR_FALSE; - isFIPS = (encoded->fips != 0) ? PR_TRUE: PR_FALSE; + internal = (encoded->internal != 0) ? PR_TRUE : PR_FALSE; + isFIPS = (encoded->fips != 0) ? PR_TRUE : PR_FALSE; if (retInternal) - *retInternal = internal; + *retInternal = internal; if (internal) { - parameters = PORT_ArenaStrdup(arena,defParams); - if (parameters == NULL) - goto loser; + parameters = PORT_ArenaStrdup(arena, defParams); + if (parameters == NULL) + goto loser; } if (internal && (encoded->major == LGDB_DB_NOUI_VERSION_MAJOR) && - (encoded->minor <= LGDB_DB_NOUI_VERSION_MINOR)) { - isOldVersion = PR_TRUE; + (encoded->minor <= LGDB_DB_NOUI_VERSION_MINOR)) { + isOldVersion = PR_TRUE; } if ((encoded->major == LGDB_DB_EXT1_VERSION_MAJOR) && - (encoded->minor >= LGDB_DB_EXT1_VERSION_MINOR)) { - CHECK_SIZE( sizeof(lgdbData)); - trustOrder = LGDB_GETLONG(encoded->trustOrder); - cipherOrder = LGDB_GETLONG(encoded->cipherOrder); - isModuleDB = (encoded->isModuleDB != 0) ? PR_TRUE: PR_FALSE; - isModuleDBOnly = (encoded->isModuleDBOnly != 0) ? PR_TRUE: PR_FALSE; - extended = PR_TRUE; - } + (encoded->minor >= LGDB_DB_EXT1_VERSION_MINOR)) { + CHECK_SIZE(sizeof(lgdbData)); + trustOrder = LGDB_GETLONG(encoded->trustOrder); + cipherOrder = LGDB_GETLONG(encoded->cipherOrder); + isModuleDB = (encoded->isModuleDB != 0) ? PR_TRUE : PR_FALSE; + isModuleDBOnly = (encoded->isModuleDBOnly != 0) ? PR_TRUE : PR_FALSE; + extended = PR_TRUE; + } if (internal && !extended) { - trustOrder = 0; - cipherOrder = 100; + trustOrder = 0; + cipherOrder = 100; } /* decode SSL cipher enable flags */ ssl0 = LGDB_GETLONG(encoded->ssl); ssl1 = LGDB_GETLONG(encoded->ssl + 4); - slotOffset = LGDB_GETSHORT(encoded->slotOffset); + slotOffset = LGDB_GETSHORT(encoded->slotOffset); namesOffset = LGDB_GETSHORT(encoded->nameStart); - /*-------------------------------------------------------------- - ** Now process the variable length set of names. + ** Now process the variable length set of names. ** The names have this structure: ** struct { ** BYTE commonNameLen[ 2 ]; @@ -354,60 +363,60 @@ lgdb_DecodeData(char *defParams, DBT *data, PRBool *retInternal) namesRunningOffset = namesOffset; /* copy the module's common name */ - CHECK_SIZE( namesRunningOffset + 2); + CHECK_SIZE(namesRunningOffset + 2); names = (unsigned char *)data->data; - len = LGDB_GETSHORT(names+namesRunningOffset); + len = LGDB_GETSHORT(names + namesRunningOffset); - CHECK_SIZE( namesRunningOffset + 2 + len); - commonName = (char*)PORT_ArenaAlloc(arena,len+1); - if (commonName == NULL) - goto loser; + CHECK_SIZE(namesRunningOffset + 2 + len); + commonName = (char *)PORT_ArenaAlloc(arena, len + 1); + if (commonName == NULL) + goto loser; PORT_Memcpy(commonName, names + namesRunningOffset + 2, len); commonName[len] = 0; namesRunningOffset += len + 2; /* copy the module's shared library file name. */ - CHECK_SIZE( namesRunningOffset + 2); + CHECK_SIZE(namesRunningOffset + 2); len = LGDB_GETSHORT(names + namesRunningOffset); if (len) { - CHECK_SIZE( namesRunningOffset + 2 + len); - dllName = (char*)PORT_ArenaAlloc(arena,len + 1); - if (dllName == NULL) - goto loser; - PORT_Memcpy(dllName, names + namesRunningOffset + 2, len); - dllName[len] = 0; + CHECK_SIZE(namesRunningOffset + 2 + len); + dllName = (char *)PORT_ArenaAlloc(arena, len + 1); + if (dllName == NULL) + goto loser; + PORT_Memcpy(dllName, names + namesRunningOffset + 2, len); + dllName[len] = 0; } namesRunningOffset += len + 2; /* copy the module's initialization string, if present. */ if (!internal && extended) { - CHECK_SIZE( namesRunningOffset + 2); - len = LGDB_GETSHORT(names+namesRunningOffset); - if (len) { - CHECK_SIZE( namesRunningOffset + 2 + len ); - parameters = (char*)PORT_ArenaAlloc(arena,len + 1); - if (parameters == NULL) - goto loser; - PORT_Memcpy(parameters,names + namesRunningOffset + 2, len); - parameters[len] = 0; - } - namesRunningOffset += len + 2; + CHECK_SIZE(namesRunningOffset + 2); + len = LGDB_GETSHORT(names + namesRunningOffset); + if (len) { + CHECK_SIZE(namesRunningOffset + 2 + len); + parameters = (char *)PORT_ArenaAlloc(arena, len + 1); + if (parameters == NULL) + goto loser; + PORT_Memcpy(parameters, names + namesRunningOffset + 2, len); + parameters[len] = 0; + } + namesRunningOffset += len + 2; } - /* + /* * Consistency check: Make sure the slot and names blocks don't - * overlap. These blocks can occur in any order, so this check is made - * in 2 parts. First we check the case where the slot block starts + * overlap. These blocks can occur in any order, so this check is made + * in 2 parts. First we check the case where the slot block starts * after the name block. Later, when we have the slot block length, * we check the case where slot block starts before the name block. - * NOTE: in most cases any overlap will likely be detected by invalid - * data read from the blocks, but it's better to find out sooner + * NOTE: in most cases any overlap will likely be detected by invalid + * data read from the blocks, but it's better to find out sooner * than later. */ if (slotOffset >= namesOffset) { /* slot block starts after name block */ - if (slotOffset < namesRunningOffset) { - goto db_loser; - } + if (slotOffset < namesRunningOffset) { + goto db_loser; + } } /* ------------------------------------------------------------------ @@ -419,137 +428,135 @@ lgdb_DecodeData(char *defParams, DBT *data, PRBool *retInternal) ** { */ - CHECK_SIZE( slotOffset + 2 ); + CHECK_SIZE(slotOffset + 2); slotCount = LGDB_GETSHORT((unsigned char *)data->data + slotOffset); - /* - * Consistency check: Part 2. We now have the slot block length, we can + /* + * Consistency check: Part 2. We now have the slot block length, we can * check the case where the slotblock procedes the name block. */ if (slotOffset < namesOffset) { /* slot block starts before name block */ - if (namesOffset < slotOffset + 2 + slotCount*sizeof(lgdbSlotData)) { - goto db_loser; - } + if (namesOffset < slotOffset + 2 + slotCount * sizeof(lgdbSlotData)) { + goto db_loser; + } } - CHECK_SIZE( (slotOffset + 2 + slotCount * sizeof(lgdbSlotData))); - slots = (lgdbSlotData *) ((unsigned char *)data->data + slotOffset + 2); + CHECK_SIZE((slotOffset + 2 + slotCount * sizeof(lgdbSlotData))); + slots = (lgdbSlotData *)((unsigned char *)data->data + slotOffset + 2); /* slotCount; */ slotStrings = (char **)PORT_ArenaZAlloc(arena, slotCount * sizeof(char *)); if (slotStrings == NULL) - goto loser; - for (i=0; i < (int) slotCount; i++, slots++) { - PRBool hasRootCerts =PR_FALSE; - PRBool hasRootTrust =PR_FALSE; - slotID = LGDB_GETLONG(slots->slotID); - defaultFlags = LGDB_GETLONG(slots->defaultFlags); - timeout = LGDB_GETLONG(slots->timeout); - hasRootCerts = slots->hasRootCerts; - if (isOldVersion && internal && (slotID != 2)) { - unsigned long internalFlags= - NSSUTIL_ArgParseSlotFlags("slotFlags", - NSSUTIL_DEFAULT_SFTKN_FLAGS); - defaultFlags |= internalFlags; - } - if (hasRootCerts && !extended) { - trustOrder = 100; - } - - slotStrings[i] = NSSUTIL_MkSlotString(slotID, defaultFlags, timeout, - (unsigned char)slots->askpw, - hasRootCerts, hasRootTrust); - if (slotStrings[i] == NULL) { - lgdb_FreeSlotStrings(slotStrings,i); - goto loser; - } + goto loser; + for (i = 0; i < (int)slotCount; i++, slots++) { + PRBool hasRootCerts = PR_FALSE; + PRBool hasRootTrust = PR_FALSE; + slotID = LGDB_GETLONG(slots->slotID); + defaultFlags = LGDB_GETLONG(slots->defaultFlags); + timeout = LGDB_GETLONG(slots->timeout); + hasRootCerts = slots->hasRootCerts; + if (isOldVersion && internal && (slotID != 2)) { + unsigned long internalFlags = + NSSUTIL_ArgParseSlotFlags("slotFlags", + NSSUTIL_DEFAULT_SFTKN_FLAGS); + defaultFlags |= internalFlags; + } + if (hasRootCerts && !extended) { + trustOrder = 100; + } + + slotStrings[i] = NSSUTIL_MkSlotString(slotID, defaultFlags, timeout, + (unsigned char)slots->askpw, + hasRootCerts, hasRootTrust); + if (slotStrings[i] == NULL) { + lgdb_FreeSlotStrings(slotStrings, i); + goto loser; + } } - nss = NSSUTIL_MkNSSString(slotStrings, slotCount, internal, isFIPS, - isModuleDB, isModuleDBOnly, internal, trustOrder, - cipherOrder, ssl0, ssl1); - lgdb_FreeSlotStrings(slotStrings,slotCount); + nss = NSSUTIL_MkNSSString(slotStrings, slotCount, internal, isFIPS, + isModuleDB, isModuleDBOnly, internal, trustOrder, + cipherOrder, ssl0, ssl1); + lgdb_FreeSlotStrings(slotStrings, slotCount); /* it's permissible (and normal) for nss to be NULL. it simply means * there are no NSS specific parameters in the database */ - moduleSpec = NSSUTIL_MkModuleSpec(dllName,commonName,parameters,nss); + moduleSpec = NSSUTIL_MkModuleSpec(dllName, commonName, parameters, nss); PR_smprintf_free(nss); - PORT_FreeArena(arena,PR_TRUE); + PORT_FreeArena(arena, PR_TRUE); return moduleSpec; db_loser: PORT_SetError(SEC_ERROR_BAD_DATABASE); loser: - PORT_FreeArena(arena,PR_TRUE); + PORT_FreeArena(arena, PR_TRUE); return NULL; } static DB * -lgdb_OpenDB(const char *appName, const char *filename, const char *dbName, - PRBool readOnly, PRBool update) +lgdb_OpenDB(const char *appName, const char *filename, const char *dbName, + PRBool readOnly, PRBool update) { DB *pkcs11db = NULL; - if (appName) { - char *secname = PORT_Strdup(filename); - int len = strlen(secname); - int status = RDB_FAIL; - - if (len >= 3 && PORT_Strcmp(&secname[len-3],".db") == 0) { - secname[len-3] = 0; - } - pkcs11db= - rdbopen(appName, "", secname, readOnly ? NO_RDONLY:NO_RDWR, NULL); - if (update && !pkcs11db) { - DB *updatedb; - - pkcs11db = rdbopen(appName, "", secname, NO_CREATE, &status); - if (!pkcs11db) { - if (status == RDB_RETRY) { - pkcs11db= rdbopen(appName, "", secname, - readOnly ? NO_RDONLY:NO_RDWR, NULL); - } - PORT_Free(secname); - return pkcs11db; - } - updatedb = dbopen(dbName, NO_RDONLY, 0600, DB_HASH, 0); - if (updatedb) { - db_Copy(pkcs11db,updatedb); - (*updatedb->close)(updatedb); - } else { - (*pkcs11db->close)(pkcs11db); - PORT_Free(secname); - return NULL; - } - } - PORT_Free(secname); - return pkcs11db; + char *secname = PORT_Strdup(filename); + int len = strlen(secname); + int status = RDB_FAIL; + + if (len >= 3 && PORT_Strcmp(&secname[len - 3], ".db") == 0) { + secname[len - 3] = 0; + } + pkcs11db = + rdbopen(appName, "", secname, readOnly ? NO_RDONLY : NO_RDWR, NULL); + if (update && !pkcs11db) { + DB *updatedb; + + pkcs11db = rdbopen(appName, "", secname, NO_CREATE, &status); + if (!pkcs11db) { + if (status == RDB_RETRY) { + pkcs11db = rdbopen(appName, "", secname, + readOnly ? NO_RDONLY : NO_RDWR, NULL); + } + PORT_Free(secname); + return pkcs11db; + } + updatedb = dbopen(dbName, NO_RDONLY, 0600, DB_HASH, 0); + if (updatedb) { + db_Copy(pkcs11db, updatedb); + (*updatedb->close)(updatedb); + } else { + (*pkcs11db->close)(pkcs11db); + PORT_Free(secname); + return NULL; + } + } + PORT_Free(secname); + return pkcs11db; } - + /* I'm sure we should do more checks here sometime... */ pkcs11db = dbopen(dbName, readOnly ? NO_RDONLY : NO_RDWR, 0600, DB_HASH, 0); /* didn't exist? create it */ if (pkcs11db == NULL) { - if (readOnly) - return NULL; + if (readOnly) + return NULL; - pkcs11db = dbopen( dbName, NO_CREATE, 0600, DB_HASH, 0 ); - if (pkcs11db) - (* pkcs11db->sync)(pkcs11db, 0); + pkcs11db = dbopen(dbName, NO_CREATE, 0600, DB_HASH, 0); + if (pkcs11db) + (*pkcs11db->sync)(pkcs11db, 0); } return pkcs11db; } -static void -lgdb_CloseDB(DB *pkcs11db) +static void +lgdb_CloseDB(DB *pkcs11db) { - (*pkcs11db->close)(pkcs11db); + (*pkcs11db->close)(pkcs11db); } - -SECStatus legacy_AddSecmodDB(const char *appName, const char *filename, - const char *dbname, char *module, PRBool rw); +SECStatus legacy_AddSecmodDB(const char *appName, const char *filename, + const char *dbname, char *module, PRBool rw); #define LGDB_STEP 10 /* @@ -557,83 +564,84 @@ SECStatus legacy_AddSecmodDB(const char *appName, const char *filename, */ char ** legacy_ReadSecmodDB(const char *appName, const char *filename, - const char *dbname, char *params, PRBool rw) + const char *dbname, char *params, PRBool rw) { - DBT key,data; + DBT key, data; int ret; DB *pkcs11db = NULL; char **moduleList = NULL, **newModuleList = NULL; int moduleCount = 1; int useCount = LGDB_STEP; - moduleList = (char **) PORT_ZAlloc(useCount*sizeof(char **)); - if (moduleList == NULL) return NULL; + moduleList = (char **)PORT_ZAlloc(useCount * sizeof(char **)); + if (moduleList == NULL) + return NULL; - pkcs11db = lgdb_OpenDB(appName,filename,dbname,PR_TRUE,rw); - if (pkcs11db == NULL) goto done; + pkcs11db = lgdb_OpenDB(appName, filename, dbname, PR_TRUE, rw); + if (pkcs11db == NULL) + goto done; /* read and parse the file or data base */ ret = (*pkcs11db->seq)(pkcs11db, &key, &data, R_FIRST); - if (ret) goto done; - + if (ret) + goto done; do { - char *moduleString; - PRBool internal = PR_FALSE; - if ((moduleCount+1) >= useCount) { - useCount += LGDB_STEP; - newModuleList = - (char **)PORT_Realloc(moduleList,useCount*sizeof(char *)); - if (newModuleList == NULL) goto done; - moduleList = newModuleList; - PORT_Memset(&moduleList[moduleCount+1],0, - sizeof(char *)*LGDB_STEP); - } - moduleString = lgdb_DecodeData(params,&data,&internal); - if (internal) { - moduleList[0] = moduleString; - } else { - moduleList[moduleCount] = moduleString; - moduleCount++; - } - } while ( (*pkcs11db->seq)(pkcs11db, &key, &data, R_NEXT) == 0); + char *moduleString; + PRBool internal = PR_FALSE; + if ((moduleCount + 1) >= useCount) { + useCount += LGDB_STEP; + newModuleList = + (char **)PORT_Realloc(moduleList, useCount * sizeof(char *)); + if (newModuleList == NULL) + goto done; + moduleList = newModuleList; + PORT_Memset(&moduleList[moduleCount + 1], 0, + sizeof(char *) * LGDB_STEP); + } + moduleString = lgdb_DecodeData(params, &data, &internal); + if (internal) { + moduleList[0] = moduleString; + } else { + moduleList[moduleCount] = moduleString; + moduleCount++; + } + } while ((*pkcs11db->seq)(pkcs11db, &key, &data, R_NEXT) == 0); done: if (!moduleList[0]) { - char * newparams = NSSUTIL_Quote(params,'"'); - if (newparams) { - moduleList[0] = PR_smprintf( - NSSUTIL_DEFAULT_INTERNAL_INIT1 "%s" - NSSUTIL_DEFAULT_INTERNAL_INIT2 "%s" - NSSUTIL_DEFAULT_INTERNAL_INIT3, - newparams, NSSUTIL_DEFAULT_SFTKN_FLAGS); - PORT_Free(newparams); - } + char *newparams = NSSUTIL_Quote(params, '"'); + if (newparams) { + moduleList[0] = PR_smprintf( + NSSUTIL_DEFAULT_INTERNAL_INIT1 "%s" NSSUTIL_DEFAULT_INTERNAL_INIT2 "%s" NSSUTIL_DEFAULT_INTERNAL_INIT3, + newparams, NSSUTIL_DEFAULT_SFTKN_FLAGS); + PORT_Free(newparams); + } } /* deal with trust cert db here */ if (pkcs11db) { - lgdb_CloseDB(pkcs11db); + lgdb_CloseDB(pkcs11db); } else if (moduleList[0] && rw) { - legacy_AddSecmodDB(appName,filename,dbname,moduleList[0], rw) ; + legacy_AddSecmodDB(appName, filename, dbname, moduleList[0], rw); } if (!moduleList[0]) { - PORT_Free(moduleList); - moduleList = NULL; + PORT_Free(moduleList); + moduleList = NULL; } return moduleList; } SECStatus -legacy_ReleaseSecmodDBData(const char *appName, const char *filename, - const char *dbname, char **moduleSpecList, PRBool rw) +legacy_ReleaseSecmodDBData(const char *appName, const char *filename, + const char *dbname, char **moduleSpecList, PRBool rw) { if (moduleSpecList) { - char **index; - for(index = moduleSpecList; *index; index++) { - PR_smprintf_free(*index); - } - PORT_Free(moduleSpecList); + char **index; + for (index = moduleSpecList; *index; index++) { + PR_smprintf_free(*index); + } + PORT_Free(moduleSpecList); } return SECSuccess; } @@ -642,32 +650,35 @@ legacy_ReleaseSecmodDBData(const char *appName, const char *filename, * Delete a module from the Data Base */ SECStatus -legacy_DeleteSecmodDB(const char *appName, const char *filename, - const char *dbname, char *args, PRBool rw) +legacy_DeleteSecmodDB(const char *appName, const char *filename, + const char *dbname, char *args, PRBool rw) { DBT key; SECStatus rv = SECFailure; DB *pkcs11db = NULL; int ret; - if (!rw) return SECFailure; + if (!rw) + return SECFailure; /* make sure we have a db handle */ - pkcs11db = lgdb_OpenDB(appName,filename,dbname,PR_FALSE,PR_FALSE); + pkcs11db = lgdb_OpenDB(appName, filename, dbname, PR_FALSE, PR_FALSE); if (pkcs11db == NULL) { - return SECFailure; + return SECFailure; } - rv = lgdb_MakeKey(&key,args); - if (rv != SECSuccess) goto done; + rv = lgdb_MakeKey(&key, args); + if (rv != SECSuccess) + goto done; rv = SECFailure; ret = (*pkcs11db->del)(pkcs11db, &key, 0); lgdb_FreeKey(&key); - if (ret != 0) goto done; - + if (ret != 0) + goto done; ret = (*pkcs11db->sync)(pkcs11db, 0); - if (ret == 0) rv = SECSuccess; + if (ret == 0) + rv = SECSuccess; done: lgdb_CloseDB(pkcs11db); @@ -675,41 +686,44 @@ done: } /* - * Add a module to the Data base + * Add a module to the Data base */ SECStatus -legacy_AddSecmodDB(const char *appName, const char *filename, - const char *dbname, char *module, PRBool rw) +legacy_AddSecmodDB(const char *appName, const char *filename, + const char *dbname, char *module, PRBool rw) { - DBT key,data; + DBT key, data; SECStatus rv = SECFailure; DB *pkcs11db = NULL; int ret; - - if (!rw) return SECFailure; + if (!rw) + return SECFailure; /* make sure we have a db handle */ - pkcs11db = lgdb_OpenDB(appName,filename,dbname,PR_FALSE,PR_FALSE); + pkcs11db = lgdb_OpenDB(appName, filename, dbname, PR_FALSE, PR_FALSE); if (pkcs11db == NULL) { - return SECFailure; + return SECFailure; } - rv = lgdb_MakeKey(&key,module); - if (rv != SECSuccess) goto done; - rv = lgdb_EncodeData(&data,module); + rv = lgdb_MakeKey(&key, module); + if (rv != SECSuccess) + goto done; + rv = lgdb_EncodeData(&data, module); if (rv != SECSuccess) { - lgdb_FreeKey(&key); - goto done; + lgdb_FreeKey(&key); + goto done; } rv = SECFailure; ret = (*pkcs11db->put)(pkcs11db, &key, &data, 0); lgdb_FreeKey(&key); lgdb_FreeData(&data); - if (ret != 0) goto done; + if (ret != 0) + goto done; ret = (*pkcs11db->sync)(pkcs11db, 0); - if (ret == 0) rv = SECSuccess; + if (ret == 0) + rv = SECSuccess; done: lgdb_CloseDB(pkcs11db); diff --git a/nss/lib/softoken/lgglue.c b/nss/lib/softoken/lgglue.c index c7b82bd..94f0541 100644 --- a/nss/lib/softoken/lgglue.c +++ b/nss/lib/softoken/lgglue.c @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * The following code handles the storage of PKCS 11 modules used by the * NSS. This file is written to abstract away how the modules are * stored so we can deside that later. @@ -35,49 +35,51 @@ static char * sftkdb_resolvePath(const char *orig) { int count = 0; - int len =0; + int len = 0; int ret = -1; char *resolved = NULL; char *source = NULL; len = 1025; /* MAX PATH +1*/ - if (strlen(orig)+1 > len) { - /* PATH TOO LONG */ - return NULL; + if (strlen(orig) + 1 > len) { + /* PATH TOO LONG */ + return NULL; } resolved = PORT_Alloc(len); if (!resolved) { - return NULL; + return NULL; } source = PORT_Alloc(len); if (!source) { - goto loser; + goto loser; } PORT_Strcpy(source, orig); /* Walk down all the links */ - while ( count++ < LG_MAX_LINKS) { - char *tmp; - /* swap our previous sorce out with resolved */ - /* read it */ - ret = readlink(source, resolved, len-1); - if (ret < 0) { - break; - } - resolved[ret] = 0; - tmp = source; source = resolved; resolved = tmp; + while (count++ < LG_MAX_LINKS) { + char *tmp; + /* swap our previous sorce out with resolved */ + /* read it */ + ret = readlink(source, resolved, len - 1); + if (ret < 0) { + break; + } + resolved[ret] = 0; + tmp = source; + source = resolved; + resolved = tmp; } if (count > 1) { - ret = 0; + ret = 0; } loser: if (resolved) { - PORT_Free(resolved); + PORT_Free(resolved); } if (ret < 0) { - if (source) { - PORT_Free(source); - source = NULL; - } + if (source) { + PORT_Free(source); + source = NULL; + } } return source; } @@ -93,22 +95,21 @@ sftkdb_LoadFromPath(const char *path, const char *libname) PRLibSpec libSpec; PRLibrary *lib = NULL; - - /* strip of our parent's library name */ + /* strip of our parent's library name */ c = strrchr(path, PR_GetDirectorySeparator()); if (!c) { - return NULL; /* invalid path */ + return NULL; /* invalid path */ } - pathLen = (c-path)+1; + pathLen = (c - path) + 1; nameLen = strlen(libname); - fullPathLen = pathLen + nameLen +1; + fullPathLen = pathLen + nameLen + 1; fullPathName = (char *)PORT_Alloc(fullPathLen); if (fullPathName == NULL) { - return NULL; /* memory allocation error */ + return NULL; /* memory allocation error */ } PORT_Memcpy(fullPathName, path, pathLen); - PORT_Memcpy(fullPathName+pathLen, libname, nameLen); - fullPathName[fullPathLen-1] = 0; + PORT_Memcpy(fullPathName + pathLen, libname, nameLen); + fullPathName[fullPathLen - 1] = 0; libSpec.type = PR_LibSpec_Pathname; libSpec.value.pathname = fullPathName; @@ -117,7 +118,6 @@ sftkdb_LoadFromPath(const char *path, const char *libname) return lib; } - static PRLibrary * sftkdb_LoadLibrary(const char *libname) { @@ -125,37 +125,37 @@ sftkdb_LoadLibrary(const char *libname) PRFuncPtr fn_addr; char *parentLibPath = NULL; - fn_addr = (PRFuncPtr) &sftkdb_LoadLibrary; + fn_addr = (PRFuncPtr)&sftkdb_LoadLibrary; parentLibPath = PR_GetLibraryFilePathname(SOFTOKEN_LIB_NAME, fn_addr); if (!parentLibPath) { - goto done; + goto done; } lib = sftkdb_LoadFromPath(parentLibPath, libname); #ifdef XP_UNIX /* handle symbolic link case */ if (!lib) { - char *trueParentLibPath = sftkdb_resolvePath(parentLibPath); - if (!trueParentLibPath) { - goto done; - } - lib = sftkdb_LoadFromPath(trueParentLibPath, libname); - PORT_Free(trueParentLibPath); + char *trueParentLibPath = sftkdb_resolvePath(parentLibPath); + if (!trueParentLibPath) { + goto done; + } + lib = sftkdb_LoadFromPath(trueParentLibPath, libname); + PORT_Free(trueParentLibPath); } #endif done: if (parentLibPath) { - PORT_Free(parentLibPath); + PORT_Free(parentLibPath); } /* still couldn't load it, try the generic path */ if (!lib) { - PRLibSpec libSpec; - libSpec.type = PR_LibSpec_Pathname; - libSpec.value.pathname = libname; - lib = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW | PR_LD_LOCAL); + PRLibSpec libSpec; + libSpec.type = PR_LibSpec_Pathname; + libSpec.value.pathname = libname; + lib = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW | PR_LD_LOCAL); } return lib; @@ -167,35 +167,35 @@ done: */ static SECStatus sftkdb_encrypt_stub(PLArenaPool *arena, SDB *sdb, SECItem *plainText, - SECItem **cipherText) + SECItem **cipherText) { SFTKDBHandle *handle = sdb->app_private; SECStatus rv; if (handle == NULL) { - return SECFailure; + return SECFailure; } /* if we aren't the key handle, try the other handle */ if (handle->type != SFTK_KEYDB_TYPE) { - handle = handle->peerDB; + handle = handle->peerDB; } /* not a key handle */ if (handle == NULL || handle->passwordLock == NULL) { - return SECFailure; + return SECFailure; } PZ_Lock(handle->passwordLock); if (handle->passwordKey.data == NULL) { - PZ_Unlock(handle->passwordLock); - /* PORT_SetError */ - return SECFailure; + PZ_Unlock(handle->passwordLock); + /* PORT_SetError */ + return SECFailure; } - rv = sftkdb_EncryptAttribute(arena, - handle->newKey?handle->newKey:&handle->passwordKey, - plainText, cipherText); + rv = sftkdb_EncryptAttribute(arena, + handle->newKey ? handle->newKey : &handle->passwordKey, + plainText, cipherText); PZ_Unlock(handle->passwordLock); return rv; @@ -206,200 +206,176 @@ sftkdb_encrypt_stub(PLArenaPool *arena, SDB *sdb, SECItem *plainText, * various keys and attributes. */ static SECStatus -sftkdb_decrypt_stub(SDB *sdb, SECItem *cipherText, SECItem **plainText) +sftkdb_decrypt_stub(SDB *sdb, SECItem *cipherText, SECItem **plainText) { SFTKDBHandle *handle = sdb->app_private; SECStatus rv; SECItem *oldKey = NULL; if (handle == NULL) { - return SECFailure; + return SECFailure; } /* if we aren't th handle, try the other handle */ oldKey = handle->oldKey; if (handle->type != SFTK_KEYDB_TYPE) { - handle = handle->peerDB; + handle = handle->peerDB; } /* not a key handle */ if (handle == NULL || handle->passwordLock == NULL) { - return SECFailure; + return SECFailure; } PZ_Lock(handle->passwordLock); if (handle->passwordKey.data == NULL) { - PZ_Unlock(handle->passwordLock); - /* PORT_SetError */ - return SECFailure; + PZ_Unlock(handle->passwordLock); + /* PORT_SetError */ + return SECFailure; } - rv = sftkdb_DecryptAttribute( oldKey ? oldKey : &handle->passwordKey, - cipherText, plainText); + rv = sftkdb_DecryptAttribute(oldKey ? oldKey : &handle->passwordKey, + cipherText, plainText); PZ_Unlock(handle->passwordLock); return rv; } -static const char *LEGACY_LIB_NAME = - SHLIB_PREFIX"nssdbm"SHLIB_VERSION"."SHLIB_SUFFIX; +static const char *LEGACY_LIB_NAME = + SHLIB_PREFIX "nssdbm" SHLIB_VERSION "." SHLIB_SUFFIX; /* * 2 bools to tell us if we've check the legacy library successfully or * not. Initialize on startup to false by the C BSS segment; */ -static PRBool legacy_glue_libCheckFailed; /* set if we failed the check */ -static PRBool legacy_glue_libCheckSucceeded; /* set if we passed the check */ static PRLibrary *legacy_glue_lib = NULL; -static SECStatus -sftkdbLoad_Legacy(PRBool isFIPS) +static SECStatus +sftkdbLoad_Legacy() { PRLibrary *lib = NULL; LGSetCryptFunc setCryptFunction = NULL; if (legacy_glue_lib) { - /* this check is necessary because it's possible we loaded the - * legacydb to read secmod.db, which told us whether we were in - * FIPS mode or not. */ - if (isFIPS && !legacy_glue_libCheckSucceeded) { - if (legacy_glue_libCheckFailed || - !BLAPI_SHVerify(LEGACY_LIB_NAME,(PRFuncPtr)legacy_glue_open)) { - legacy_glue_libCheckFailed = PR_TRUE; - /* don't clobber legacy glue to avoid race. just let it - * get cleared in shutdown */ - return SECFailure; - } - legacy_glue_libCheckSucceeded = PR_TRUE; - } - return SECSuccess; + return SECSuccess; } lib = sftkdb_LoadLibrary(LEGACY_LIB_NAME); if (lib == NULL) { - return SECFailure; + return SECFailure; } - + legacy_glue_open = (LGOpenFunc)PR_FindFunctionSymbol(lib, "legacy_Open"); - legacy_glue_readSecmod = (LGReadSecmodFunc) PR_FindFunctionSymbol(lib, - "legacy_ReadSecmodDB"); - legacy_glue_releaseSecmod = (LGReleaseSecmodFunc) PR_FindFunctionSymbol(lib, - "legacy_ReleaseSecmodDBData"); - legacy_glue_deleteSecmod = (LGDeleteSecmodFunc) PR_FindFunctionSymbol(lib, - "legacy_DeleteSecmodDB"); - legacy_glue_addSecmod = (LGAddSecmodFunc)PR_FindFunctionSymbol(lib, - "legacy_AddSecmodDB"); - legacy_glue_shutdown = (LGShutdownFunc) PR_FindFunctionSymbol(lib, - "legacy_Shutdown"); - setCryptFunction = (LGSetCryptFunc) PR_FindFunctionSymbol(lib, - "legacy_SetCryptFunctions"); - - if (!legacy_glue_open || !legacy_glue_readSecmod || - !legacy_glue_releaseSecmod || !legacy_glue_deleteSecmod || - !legacy_glue_addSecmod || !setCryptFunction) { - PR_UnloadLibrary(lib); - return SECFailure; - } - - /* verify the loaded library if we are in FIPS mode */ - if (isFIPS) { - if (!BLAPI_SHVerify(LEGACY_LIB_NAME,(PRFuncPtr)legacy_glue_open)) { - PR_UnloadLibrary(lib); - return SECFailure; - } - legacy_glue_libCheckSucceeded = PR_TRUE; - } - - setCryptFunction(sftkdb_encrypt_stub,sftkdb_decrypt_stub); + legacy_glue_readSecmod = + (LGReadSecmodFunc)PR_FindFunctionSymbol(lib, "legacy_ReadSecmodDB"); + legacy_glue_releaseSecmod = + (LGReleaseSecmodFunc)PR_FindFunctionSymbol(lib, "legacy_ReleaseSecmodDBData"); + legacy_glue_deleteSecmod = + (LGDeleteSecmodFunc)PR_FindFunctionSymbol(lib, "legacy_DeleteSecmodDB"); + legacy_glue_addSecmod = + (LGAddSecmodFunc)PR_FindFunctionSymbol(lib, "legacy_AddSecmodDB"); + legacy_glue_shutdown = + (LGShutdownFunc)PR_FindFunctionSymbol(lib, "legacy_Shutdown"); + setCryptFunction = + (LGSetCryptFunc)PR_FindFunctionSymbol(lib, "legacy_SetCryptFunctions"); + + if (!legacy_glue_open || !legacy_glue_readSecmod || + !legacy_glue_releaseSecmod || !legacy_glue_deleteSecmod || + !legacy_glue_addSecmod || !setCryptFunction) { + PR_UnloadLibrary(lib); + return SECFailure; + } + + setCryptFunction(sftkdb_encrypt_stub, sftkdb_decrypt_stub); legacy_glue_lib = lib; return SECSuccess; } CK_RV -sftkdbCall_open(const char *dir, const char *certPrefix, const char *keyPrefix, - int certVersion, int keyVersion, int flags, PRBool isFIPS, - SDB **certDB, SDB **keyDB) +sftkdbCall_open(const char *dir, const char *certPrefix, const char *keyPrefix, + int certVersion, int keyVersion, int flags, + SDB **certDB, SDB **keyDB) { SECStatus rv; - rv = sftkdbLoad_Legacy(isFIPS); + rv = sftkdbLoad_Legacy(); if (rv != SECSuccess) { - return CKR_GENERAL_ERROR; + return CKR_GENERAL_ERROR; } if (!legacy_glue_open) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } - return (*legacy_glue_open)(dir, certPrefix, keyPrefix, - certVersion, keyVersion, - flags, certDB, keyDB); + return (*legacy_glue_open)(dir, certPrefix, keyPrefix, + certVersion, keyVersion, + flags, certDB, keyDB); } char ** -sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, - const char *dbname, char *params, PRBool rw) +sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, + const char *dbname, char *params, PRBool rw) { SECStatus rv; - rv = sftkdbLoad_Legacy(PR_FALSE); + rv = sftkdbLoad_Legacy(); if (rv != SECSuccess) { - return NULL; + return NULL; } if (!legacy_glue_readSecmod) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return NULL; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return NULL; } return (*legacy_glue_readSecmod)(appName, filename, dbname, params, rw); } SECStatus -sftkdbCall_ReleaseSecmodDBData(const char *appName, - const char *filename, const char *dbname, - char **moduleSpecList, PRBool rw) +sftkdbCall_ReleaseSecmodDBData(const char *appName, + const char *filename, const char *dbname, + char **moduleSpecList, PRBool rw) { SECStatus rv; - rv = sftkdbLoad_Legacy(PR_FALSE); + rv = sftkdbLoad_Legacy(); if (rv != SECSuccess) { - return rv; + return rv; } if (!legacy_glue_releaseSecmod) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } - return (*legacy_glue_releaseSecmod)(appName, filename, dbname, - moduleSpecList, rw); + return (*legacy_glue_releaseSecmod)(appName, filename, dbname, + moduleSpecList, rw); } SECStatus -sftkdbCall_DeleteSecmodDB(const char *appName, - const char *filename, const char *dbname, - char *args, PRBool rw) +sftkdbCall_DeleteSecmodDB(const char *appName, + const char *filename, const char *dbname, + char *args, PRBool rw) { SECStatus rv; - rv = sftkdbLoad_Legacy(PR_FALSE); + rv = sftkdbLoad_Legacy(); if (rv != SECSuccess) { - return rv; + return rv; } if (!legacy_glue_deleteSecmod) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } return (*legacy_glue_deleteSecmod)(appName, filename, dbname, args, rw); } SECStatus -sftkdbCall_AddSecmodDB(const char *appName, - const char *filename, const char *dbname, - char *module, PRBool rw) +sftkdbCall_AddSecmodDB(const char *appName, + const char *filename, const char *dbname, + char *module, PRBool rw) { SECStatus rv; - rv = sftkdbLoad_Legacy(PR_FALSE); + rv = sftkdbLoad_Legacy(); if (rv != SECSuccess) { - return rv; + return rv; } if (!legacy_glue_addSecmod) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } return (*legacy_glue_addSecmod)(appName, filename, dbname, module, rw); } @@ -410,15 +386,15 @@ sftkdbCall_Shutdown(void) CK_RV crv = CKR_OK; char *disableUnload = NULL; if (!legacy_glue_lib) { - return CKR_OK; + return CKR_OK; } if (legacy_glue_shutdown) { #ifdef NO_FORK_CHECK - PRBool parentForkedAfterC_Initialize = PR_FALSE; + PRBool parentForkedAfterC_Initialize = PR_FALSE; #endif - crv = (*legacy_glue_shutdown)(parentForkedAfterC_Initialize); + crv = (*legacy_glue_shutdown)(parentForkedAfterC_Initialize); } - disableUnload = PR_GetEnv("NSS_DISABLE_UNLOAD"); + disableUnload = PR_GetEnvSecure("NSS_DISABLE_UNLOAD"); if (!disableUnload) { PR_UnloadLibrary(legacy_glue_lib); } @@ -428,9 +404,5 @@ sftkdbCall_Shutdown(void) legacy_glue_releaseSecmod = NULL; legacy_glue_deleteSecmod = NULL; legacy_glue_addSecmod = NULL; - legacy_glue_libCheckFailed = PR_FALSE; - legacy_glue_libCheckSucceeded = PR_FALSE; return crv; } - - diff --git a/nss/lib/softoken/lgglue.h b/nss/lib/softoken/lgglue.h index b87f756..61dbfec 100644 --- a/nss/lib/softoken/lgglue.h +++ b/nss/lib/softoken/lgglue.h @@ -1,7 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * This code defines the glue layer between softoken and the legacy DB library */ #include "sdb.h" @@ -11,29 +11,29 @@ */ typedef SECStatus (*LGEncryptFunc)(PLArenaPool *arena, SDB *sdb, - SECItem *plainText, SECItem **cipherText); -typedef SECStatus (*LGDecryptFunc)(SDB *sdb, SECItem *cipherText, - SECItem **plainText); + SECItem *plainText, SECItem **cipherText); +typedef SECStatus (*LGDecryptFunc)(SDB *sdb, SECItem *cipherText, + SECItem **plainText); /* * function prototypes for the exported functions. */ -typedef CK_RV (*LGOpenFunc) (const char *dir, const char *certPrefix, - const char *keyPrefix, - int certVersion, int keyVersion, int flags, - SDB **certDB, SDB **keyDB); -typedef char ** (*LGReadSecmodFunc)(const char *appName, - const char *filename, - const char *dbname, char *params, PRBool rw); +typedef CK_RV (*LGOpenFunc)(const char *dir, const char *certPrefix, + const char *keyPrefix, + int certVersion, int keyVersion, int flags, + SDB **certDB, SDB **keyDB); +typedef char **(*LGReadSecmodFunc)(const char *appName, + const char *filename, + const char *dbname, char *params, PRBool rw); typedef SECStatus (*LGReleaseSecmodFunc)(const char *appName, - const char *filename, - const char *dbname, char **params, PRBool rw); + const char *filename, + const char *dbname, char **params, PRBool rw); typedef SECStatus (*LGDeleteSecmodFunc)(const char *appName, - const char *filename, - const char *dbname, char *params, PRBool rw); -typedef SECStatus (*LGAddSecmodFunc)(const char *appName, - const char *filename, - const char *dbname, char *params, PRBool rw); + const char *filename, + const char *dbname, char *params, PRBool rw); +typedef SECStatus (*LGAddSecmodFunc)(const char *appName, + const char *filename, + const char *dbname, char *params, PRBool rw); typedef SECStatus (*LGShutdownFunc)(PRBool forked); typedef void (*LGSetForkStateFunc)(PRBool); typedef void (*LGSetCryptFunc)(LGEncryptFunc, LGDecryptFunc); @@ -41,20 +41,19 @@ typedef void (*LGSetCryptFunc)(LGEncryptFunc, LGDecryptFunc); /* * Softoken Glue Functions */ -CK_RV sftkdbCall_open(const char *dir, const char *certPrefix, - const char *keyPrefix, - int certVersion, int keyVersion, int flags, PRBool isFIPS, - SDB **certDB, SDB **keyDB); -char ** sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, - const char *dbname, char *params, PRBool rw); -SECStatus sftkdbCall_ReleaseSecmodDBData(const char *appName, - const char *filename, const char *dbname, - char **moduleSpecList, PRBool rw); -SECStatus sftkdbCall_DeleteSecmodDB(const char *appName, - const char *filename, const char *dbname, - char *args, PRBool rw); -SECStatus sftkdbCall_AddSecmodDB(const char *appName, - const char *filename, const char *dbname, - char *module, PRBool rw); +CK_RV sftkdbCall_open(const char *dir, const char *certPrefix, + const char *keyPrefix, + int certVersion, int keyVersion, int flags, + SDB **certDB, SDB **keyDB); +char **sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, + const char *dbname, char *params, PRBool rw); +SECStatus sftkdbCall_ReleaseSecmodDBData(const char *appName, + const char *filename, const char *dbname, + char **moduleSpecList, PRBool rw); +SECStatus sftkdbCall_DeleteSecmodDB(const char *appName, + const char *filename, const char *dbname, + char *args, PRBool rw); +SECStatus sftkdbCall_AddSecmodDB(const char *appName, + const char *filename, const char *dbname, + char *module, PRBool rw); CK_RV sftkdbCall_Shutdown(void); - diff --git a/nss/lib/softoken/lowkey.c b/nss/lib/softoken/lowkey.c index d043342..73b1dc9 100644 --- a/nss/lib/softoken/lowkey.c +++ b/nss/lib/softoken/lowkey.c @@ -19,12 +19,12 @@ SEC_ASN1_MKSUB(SEC_ObjectIDTemplate) SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) const SEC_ASN1Template nsslowkey_AttributeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYAttribute) }, + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(NSSLOWKEYAttribute) }, { SEC_ASN1_OBJECT_ID, offsetof(NSSLOWKEYAttribute, attrType) }, - { SEC_ASN1_SET_OF | SEC_ASN1_XTRN , - offsetof(NSSLOWKEYAttribute, attrValue), - SEC_ASN1_SUB(SEC_AnyTemplate) }, + { SEC_ASN1_SET_OF | SEC_ASN1_XTRN, + offsetof(NSSLOWKEYAttribute, attrValue), + SEC_ASN1_SUB(SEC_AnyTemplate) }, { 0 } }; @@ -34,78 +34,64 @@ const SEC_ASN1Template nsslowkey_SetOfAttributeTemplate[] = { /* ASN1 Templates for new decoder/encoder */ const SEC_ASN1Template nsslowkey_PrivateKeyInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSLOWKEYPrivateKeyInfo) }, + 0, NULL, sizeof(NSSLOWKEYPrivateKeyInfo) }, { SEC_ASN1_INTEGER, - offsetof(NSSLOWKEYPrivateKeyInfo,version) }, + offsetof(NSSLOWKEYPrivateKeyInfo, version) }, { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(NSSLOWKEYPrivateKeyInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + offsetof(NSSLOWKEYPrivateKeyInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKeyInfo,privateKey) }, + offsetof(NSSLOWKEYPrivateKeyInfo, privateKey) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKeyInfo, attributes), - nsslowkey_SetOfAttributeTemplate }, + offsetof(NSSLOWKEYPrivateKeyInfo, attributes), + nsslowkey_SetOfAttributeTemplate }, { 0 } }; const SEC_ASN1Template nsslowkey_PQGParamsTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PQGParams) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,prime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,subPrime) }, - { SEC_ASN1_INTEGER, offsetof(PQGParams,base) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(PQGParams, prime) }, + { SEC_ASN1_INTEGER, offsetof(PQGParams, subPrime) }, + { SEC_ASN1_INTEGER, offsetof(PQGParams, base) }, + { 0 } }; const SEC_ASN1Template nsslowkey_RSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.version) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.prime2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent1) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.exponent2) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.rsa.coefficient) }, - { 0 } -}; - + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.version) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.modulus) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.publicExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.privateExponent) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.prime2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent1) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.exponent2) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.rsa.coefficient) }, + { 0 } +}; const SEC_ASN1Template nsslowkey_DSAPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dsa.publicValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dsa.privateValue) }, + { 0 } }; const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[] = { - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dsa.privateValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dsa.privateValue) }, }; const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.publicValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.privateValue) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.base) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.prime) }, - { 0, } + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.publicValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.privateValue) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.base) }, + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.dh.prime) }, + { 0 } }; #ifndef NSS_DISABLE_ECC -/* XXX This is just a placeholder for later when we support - * generic curves and need full-blown support for parsing EC - * parameters. For now, we only support named curves in which - * EC params are simply encoded as an object ID and we don't - * use nsslowkey_ECParamsTemplate. - */ -const SEC_ASN1Template nsslowkey_ECParamsTemplate[] = { - { SEC_ASN1_CHOICE, offsetof(ECParams,type), NULL, sizeof(ECParams) }, - { SEC_ASN1_OBJECT_ID, offsetof(ECParams,curveOID), NULL, ec_params_named }, - { 0, } -}; - - /* NOTE: The SECG specification allows the private key structure * to contain curve parameters but recommends that they be stored * in the PrivateKeyAlgorithmIdentifier field of the PrivateKeyInfo @@ -113,32 +99,23 @@ const SEC_ASN1Template nsslowkey_ECParamsTemplate[] = { */ const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[] = { { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.ec.version) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSLOWKEYPrivateKey,u.ec.privateValue) }, - /* XXX The following template works for now since we only - * support named curves for which the parameters are - * encoded as an object ID. When we support generic curves, - * we'll need to define nsslowkey_ECParamsTemplate + { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey, u.ec.version) }, + { SEC_ASN1_OCTET_STRING, + offsetof(NSSLOWKEYPrivateKey, u.ec.privateValue) }, + /* We only support named curves for which the parameters are + * encoded as an object ID. */ -#if 1 { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams.curveOID), - SEC_ASN1_SUB(SEC_ObjectIDTemplate) }, -#else + SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 0, + offsetof(NSSLOWKEYPrivateKey, u.ec.ecParams.curveOID), + SEC_ASN1_SUB(SEC_ObjectIDTemplate) }, { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSLOWKEYPrivateKey,u.ec.ecParams), - nsslowkey_ECParamsTemplate }, -#endif - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_XTRN | 1, - offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue), - SEC_ASN1_SUB(SEC_BitStringTemplate) }, - { 0, } + SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | + SEC_ASN1_XTRN | 1, + offsetof(NSSLOWKEYPrivateKey, u.ec.publicValue), + SEC_ASN1_SUB(SEC_BitStringTemplate) }, + { 0 } }; #endif /* NSS_DISABLE_ECC */ /* @@ -219,7 +196,7 @@ void nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *privk) { if (privk && privk->arena) { - PORT_FreeArena(privk->arena, PR_TRUE); + PORT_FreeArena(privk->arena, PR_TRUE); } } @@ -227,7 +204,7 @@ void nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *pubk) { if (pubk && pubk->arena) { - PORT_FreeArena(pubk->arena, PR_FALSE); + PORT_FreeArena(pubk->arena, PR_FALSE); } } unsigned @@ -239,11 +216,11 @@ nsslowkey_PublicModulusLen(NSSLOWKEYPublicKey *pubk) * fortezza that's the public key length */ switch (pubk->keyType) { - case NSSLOWKEYRSAKey: - b0 = pubk->u.rsa.modulus.data[0]; - return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1; - default: - break; + case NSSLOWKEYRSAKey: + b0 = pubk->u.rsa.modulus.data[0]; + return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1; + default: + break; } return 0; } @@ -255,11 +232,11 @@ nsslowkey_PrivateModulusLen(NSSLOWKEYPrivateKey *privk) unsigned char b0; switch (privk->keyType) { - case NSSLOWKEYRSAKey: - b0 = privk->u.rsa.modulus.data[0]; - return b0 ? privk->u.rsa.modulus.len : privk->u.rsa.modulus.len - 1; - default: - break; + case NSSLOWKEYRSAKey: + b0 = privk->u.rsa.modulus.data[0]; + return b0 ? privk->u.rsa.modulus.len : privk->u.rsa.modulus.len - 1; + default: + break; } return 0; } @@ -270,104 +247,113 @@ nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privk) NSSLOWKEYPublicKey *pubk; PLArenaPool *arena; - - arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE); + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); + PORT_SetError(SEC_ERROR_NO_MEMORY); return NULL; } - switch(privk->keyType) { - case NSSLOWKEYRSAKey: - case NSSLOWKEYNullKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof (NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - if (privk->keyType == NSSLOWKEYNullKey) return pubk; - rv = SECITEM_CopyItem(arena, &pubk->u.rsa.modulus, - &privk->u.rsa.modulus); - if (rv == SECSuccess) { - rv = SECITEM_CopyItem (arena, &pubk->u.rsa.publicExponent, - &privk->u.rsa.publicExponent); - if (rv == SECSuccess) - return pubk; - } - } else { - PORT_SetError (SEC_ERROR_NO_MEMORY); - } - break; - case NSSLOWKEYDSAKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.publicValue, - &privk->u.dsa.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime, - &privk->u.dsa.params.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime, - &privk->u.dsa.params.subPrime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base, - &privk->u.dsa.params.base); - if (rv == SECSuccess) return pubk; - } - break; - case NSSLOWKEYDHKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.publicValue, - &privk->u.dh.publicValue); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime, - &privk->u.dh.prime); - if (rv != SECSuccess) break; - rv = SECITEM_CopyItem(arena, &pubk->u.dh.base, - &privk->u.dh.base); - if (rv == SECSuccess) return pubk; - } - break; + switch (privk->keyType) { + case NSSLOWKEYRSAKey: + case NSSLOWKEYNullKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + if (privk->keyType == NSSLOWKEYNullKey) + return pubk; + rv = SECITEM_CopyItem(arena, &pubk->u.rsa.modulus, + &privk->u.rsa.modulus); + if (rv == SECSuccess) { + rv = SECITEM_CopyItem(arena, &pubk->u.rsa.publicExponent, + &privk->u.rsa.publicExponent); + if (rv == SECSuccess) + return pubk; + } + } else { + PORT_SetError(SEC_ERROR_NO_MEMORY); + } + break; + case NSSLOWKEYDSAKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.publicValue, + &privk->u.dsa.publicValue); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.prime, + &privk->u.dsa.params.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.subPrime, + &privk->u.dsa.params.subPrime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dsa.params.base, + &privk->u.dsa.params.base); + if (rv == SECSuccess) + return pubk; + } + break; + case NSSLOWKEYDHKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.publicValue, + &privk->u.dh.publicValue); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime, + &privk->u.dh.prime); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(arena, &pubk->u.dh.base, + &privk->u.dh.base); + if (rv == SECSuccess) + return pubk; + } + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPublicKey)); - if (pubk != NULL) { - SECStatus rv; - - pubk->arena = arena; - pubk->keyType = privk->keyType; - rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, - &privk->u.ec.publicValue); - if (rv != SECSuccess) break; - pubk->u.ec.ecParams.arena = arena; - /* Copy the rest of the params */ - rv = EC_CopyParams(arena, &(pubk->u.ec.ecParams), - &(privk->u.ec.ecParams)); - if (rv == SECSuccess) return pubk; - } - break; + case NSSLOWKEYECKey: + pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPublicKey)); + if (pubk != NULL) { + SECStatus rv; + + pubk->arena = arena; + pubk->keyType = privk->keyType; + rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, + &privk->u.ec.publicValue); + if (rv != SECSuccess) + break; + pubk->u.ec.ecParams.arena = arena; + /* Copy the rest of the params */ + rv = EC_CopyParams(arena, &(pubk->u.ec.ecParams), + &(privk->u.ec.ecParams)); + if (rv == SECSuccess) + return pubk; + } + break; #endif /* NSS_DISABLE_ECC */ - /* No Fortezza in Low Key implementations (Fortezza keys aren't - * stored in our data base */ - default: - break; + /* No Fortezza in Low Key implementations (Fortezza keys aren't + * stored in our data base */ + default: + break; } - PORT_FreeArena (arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); return NULL; } @@ -378,114 +364,136 @@ nsslowkey_CopyPrivateKey(NSSLOWKEYPrivateKey *privKey) SECStatus rv = SECFailure; PLArenaPool *poolp; - if(!privKey) { - return NULL; + if (!privKey) { + return NULL; } poolp = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(!poolp) { - return NULL; + if (!poolp) { + return NULL; } - returnKey = (NSSLOWKEYPrivateKey*)PORT_ArenaZAlloc(poolp, sizeof(NSSLOWKEYPrivateKey)); - if(!returnKey) { - rv = SECFailure; - goto loser; + returnKey = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(poolp, sizeof(NSSLOWKEYPrivateKey)); + if (!returnKey) { + rv = SECFailure; + goto loser; } returnKey->keyType = privKey->keyType; returnKey->arena = poolp; - switch(privKey->keyType) { - case NSSLOWKEYRSAKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.modulus), - &(privKey->u.rsa.modulus)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.version), - &(privKey->u.rsa.version)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.publicExponent), - &(privKey->u.rsa.publicExponent)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.privateExponent), - &(privKey->u.rsa.privateExponent)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime1), - &(privKey->u.rsa.prime1)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime2), - &(privKey->u.rsa.prime2)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent1), - &(privKey->u.rsa.exponent1)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent2), - &(privKey->u.rsa.exponent2)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.coefficient), - &(privKey->u.rsa.coefficient)); - if(rv != SECSuccess) break; - break; - case NSSLOWKEYDSAKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.publicValue), - &(privKey->u.dsa.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.privateValue), - &(privKey->u.dsa.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.dsa.params.arena = poolp; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.prime), - &(privKey->u.dsa.params.prime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.subPrime), - &(privKey->u.dsa.params.subPrime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.base), - &(privKey->u.dsa.params.base)); - if(rv != SECSuccess) break; - break; - case NSSLOWKEYDHKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.publicValue), - &(privKey->u.dh.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.privateValue), - &(privKey->u.dh.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.dsa.params.arena = poolp; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.prime), - &(privKey->u.dh.prime)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.base), - &(privKey->u.dh.base)); - if(rv != SECSuccess) break; - break; + switch (privKey->keyType) { + case NSSLOWKEYRSAKey: + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.modulus), + &(privKey->u.rsa.modulus)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.version), + &(privKey->u.rsa.version)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.publicExponent), + &(privKey->u.rsa.publicExponent)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.privateExponent), + &(privKey->u.rsa.privateExponent)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime1), + &(privKey->u.rsa.prime1)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.prime2), + &(privKey->u.rsa.prime2)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent1), + &(privKey->u.rsa.exponent1)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.exponent2), + &(privKey->u.rsa.exponent2)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.rsa.coefficient), + &(privKey->u.rsa.coefficient)); + if (rv != SECSuccess) + break; + break; + case NSSLOWKEYDSAKey: + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.publicValue), + &(privKey->u.dsa.publicValue)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.privateValue), + &(privKey->u.dsa.privateValue)); + if (rv != SECSuccess) + break; + returnKey->u.dsa.params.arena = poolp; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.prime), + &(privKey->u.dsa.params.prime)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.subPrime), + &(privKey->u.dsa.params.subPrime)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dsa.params.base), + &(privKey->u.dsa.params.base)); + if (rv != SECSuccess) + break; + break; + case NSSLOWKEYDHKey: + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.publicValue), + &(privKey->u.dh.publicValue)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.privateValue), + &(privKey->u.dh.privateValue)); + if (rv != SECSuccess) + break; + returnKey->u.dsa.params.arena = poolp; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.prime), + &(privKey->u.dh.prime)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.base), + &(privKey->u.dh.base)); + if (rv != SECSuccess) + break; + break; #ifndef NSS_DISABLE_ECC - case NSSLOWKEYECKey: - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.version), - &(privKey->u.ec.version)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.publicValue), - &(privKey->u.ec.publicValue)); - if(rv != SECSuccess) break; - rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.privateValue), - &(privKey->u.ec.privateValue)); - if(rv != SECSuccess) break; - returnKey->u.ec.ecParams.arena = poolp; - /* Copy the rest of the params */ - rv = EC_CopyParams(poolp, &(returnKey->u.ec.ecParams), - &(privKey->u.ec.ecParams)); - if (rv != SECSuccess) break; - break; + case NSSLOWKEYECKey: + rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.version), + &(privKey->u.ec.version)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.publicValue), + &(privKey->u.ec.publicValue)); + if (rv != SECSuccess) + break; + rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.privateValue), + &(privKey->u.ec.privateValue)); + if (rv != SECSuccess) + break; + returnKey->u.ec.ecParams.arena = poolp; + /* Copy the rest of the params */ + rv = EC_CopyParams(poolp, &(returnKey->u.ec.ecParams), + &(privKey->u.ec.ecParams)); + if (rv != SECSuccess) + break; + break; #endif /* NSS_DISABLE_ECC */ - default: - rv = SECFailure; + default: + rv = SECFailure; } loser: - if(rv != SECSuccess) { - PORT_FreeArena(poolp, PR_TRUE); - returnKey = NULL; + if (rv != SECSuccess) { + PORT_FreeArena(poolp, PR_TRUE); + returnKey = NULL; } return returnKey; diff --git a/nss/lib/softoken/lowkeyi.h b/nss/lib/softoken/lowkeyi.h index 7282ffe..a5878c2 100644 --- a/nss/lib/softoken/lowkeyi.h +++ b/nss/lib/softoken/lowkeyi.h @@ -32,15 +32,15 @@ extern void prepare_low_ecparams_for_asn1(ECParams *params); /* ** Destroy a private key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects +** "key" the object +** "freeit" if PR_TRUE then free the object as well as its sub-objects */ extern void nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *key); /* ** Destroy a public key object. -** "key" the object -** "freeit" if PR_TRUE then free the object as well as its sub-objects +** "key" the object +** "freeit" if PR_TRUE then free the object as well as its sub-objects */ extern void nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *key); @@ -49,18 +49,16 @@ extern void nsslowkey_DestroyPublicKey(NSSLOWKEYPublicKey *key); */ extern unsigned int nsslowkey_PublicModulusLen(NSSLOWKEYPublicKey *pubKey); - /* ** Return the modulus length of "privKey". */ extern unsigned int nsslowkey_PrivateModulusLen(NSSLOWKEYPrivateKey *privKey); - /* ** Convert a low private key "privateKey" into a public low key */ -extern NSSLOWKEYPublicKey - *nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privateKey); +extern NSSLOWKEYPublicKey * +nsslowkey_ConvertToPublicKey(NSSLOWKEYPrivateKey *privateKey); /* Make a copy of a low private key in it's own arena. * a return of NULL indicates an error. @@ -68,7 +66,6 @@ extern NSSLOWKEYPublicKey extern NSSLOWKEYPrivateKey * nsslowkey_CopyPrivateKey(NSSLOWKEYPrivateKey *privKey); - SEC_END_PROTOS #endif /* _LOWKEYI_H_ */ diff --git a/nss/lib/softoken/lowkeyti.h b/nss/lib/softoken/lowkeyti.h index a4c94d8..2ef1640 100644 --- a/nss/lib/softoken/lowkeyti.h +++ b/nss/lib/softoken/lowkeyti.h @@ -21,8 +21,7 @@ extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[]; extern const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[]; extern const SEC_ASN1Template nsslowkey_DHPrivateKeyExportTemplate[]; #ifndef NSS_DISABLE_ECC -#define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */ -extern const SEC_ASN1Template nsslowkey_ECParamsTemplate[]; +#define NSSLOWKEY_EC_PRIVATE_KEY_VERSION 1 /* as per SECG 1 C.4 */ extern const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[]; #endif /* NSS_DISABLE_ECC */ @@ -49,12 +48,12 @@ struct NSSLOWKEYPrivateKeyInfoStr { NSSLOWKEYAttribute **attributes; }; typedef struct NSSLOWKEYPrivateKeyInfoStr NSSLOWKEYPrivateKeyInfo; -#define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */ +#define NSSLOWKEY_PRIVATE_KEY_INFO_VERSION 0 /* what we *create* */ -typedef enum { - NSSLOWKEYNullKey = 0, - NSSLOWKEYRSAKey = 1, - NSSLOWKEYDSAKey = 2, +typedef enum { + NSSLOWKEYNullKey = 0, + NSSLOWKEYRSAKey = 1, + NSSLOWKEYDSAKey = 2, NSSLOWKEYDHKey = 4, NSSLOWKEYECKey = 5 } NSSLOWKEYType; @@ -64,12 +63,12 @@ typedef enum { */ struct NSSLOWKEYPublicKeyStr { PLArenaPool *arena; - NSSLOWKEYType keyType ; + NSSLOWKEYType keyType; union { RSAPublicKey rsa; - DSAPublicKey dsa; - DHPublicKey dh; - ECPublicKey ec; + DSAPublicKey dsa; + DHPublicKey dh; + ECPublicKey ec; } u; }; typedef struct NSSLOWKEYPublicKeyStr NSSLOWKEYPublicKey; @@ -84,11 +83,11 @@ struct NSSLOWKEYPrivateKeyStr { NSSLOWKEYType keyType; union { RSAPrivateKey rsa; - DSAPrivateKey dsa; - DHPrivateKey dh; - ECPrivateKey ec; + DSAPrivateKey dsa; + DHPrivateKey dh; + ECPrivateKey ec; } u; }; typedef struct NSSLOWKEYPrivateKeyStr NSSLOWKEYPrivateKey; -#endif /* _LOWKEYTI_H_ */ +#endif /* _LOWKEYTI_H_ */ diff --git a/nss/lib/softoken/lowpbe.c b/nss/lib/softoken/lowpbe.c index 16d4c91..b78302e 100644 --- a/nss/lib/softoken/lowpbe.c +++ b/nss/lib/softoken/lowpbe.c @@ -26,73 +26,69 @@ SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) * if RSA updates PKCS 5. */ static const SEC_ASN1Template NSSPKCS5PBEParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSSPKCS5PBEParameter) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSSPKCS5PBEParameter, salt) }, - { SEC_ASN1_INTEGER, - offsetof(NSSPKCS5PBEParameter, iteration) }, - { 0 } -}; + { + { SEC_ASN1_SEQUENCE, + 0, NULL, sizeof(NSSPKCS5PBEParameter) }, + { SEC_ASN1_OCTET_STRING, + offsetof(NSSPKCS5PBEParameter, salt) }, + { SEC_ASN1_INTEGER, + offsetof(NSSPKCS5PBEParameter, iteration) }, + { 0 } + }; static const SEC_ASN1Template NSSPKCS5PKCS12V2PBEParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) }, - { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) }, - { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) }, - { 0 } -}; - + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) }, + { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) }, + { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) }, + { 0 } + }; /* PKCS5 v2 */ struct nsspkcs5V2PBEParameterStr { - SECAlgorithmID keyParams; /* parameters of the key generation */ - SECAlgorithmID algParams; /* parameters for the encryption or mac op */ + SECAlgorithmID keyParams; /* parameters of the key generation */ + SECAlgorithmID algParams; /* parameters for the encryption or mac op */ }; typedef struct nsspkcs5V2PBEParameterStr nsspkcs5V2PBEParameter; -#define PBKDF2 -#ifdef PBKDF2 static const SEC_ASN1Template NSSPKCS5V2PBES2ParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(nsspkcs5V2PBEParameter) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, - offsetof(nsspkcs5V2PBEParameter, keyParams), + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(nsspkcs5V2PBEParameter) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + offsetof(nsspkcs5V2PBEParameter, keyParams), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(nsspkcs5V2PBEParameter, algParams), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { 0 } -}; + { 0 } + }; static const SEC_ASN1Template NSSPKCS5V2PBEParameterTemplate[] = -{ - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) }, - /* this is really a choice, but since we don't understand any other - *choice, just inline it. */ - { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) }, - { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) }, - { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, keyLength) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + { + { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSPKCS5PBEParameter) }, + /* this is really a choice, but since we don't understand any other + * choice, just inline it. */ + { SEC_ASN1_OCTET_STRING, offsetof(NSSPKCS5PBEParameter, salt) }, + { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, iteration) }, + { SEC_ASN1_INTEGER, offsetof(NSSPKCS5PBEParameter, keyLength) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(NSSPKCS5PBEParameter, prfAlg), SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, - { 0 } -}; -#endif + { 0 } + }; SECStatus nsspkcs5_HashBuf(const SECHashObject *hashObj, unsigned char *dest, - unsigned char *src, int len) + unsigned char *src, int len) { void *ctx; unsigned int retLen; ctx = hashObj->create(); - if(ctx == NULL) { - return SECFailure; + if (ctx == NULL) { + return SECFailure; } hashObj->begin(ctx); hashObj->update(ctx, src, len); @@ -104,72 +100,72 @@ nsspkcs5_HashBuf(const SECHashObject *hashObj, unsigned char *dest, /* generate bits using any hash */ static SECItem * -nsspkcs5_PBKDF1(const SECHashObject *hashObj, SECItem *salt, SECItem *pwd, - int iter, PRBool faulty3DES) +nsspkcs5_PBKDF1(const SECHashObject *hashObj, SECItem *salt, SECItem *pwd, + int iter, PRBool faulty3DES) { SECItem *hash = NULL, *pre_hash = NULL; SECStatus rv = SECFailure; - if((salt == NULL) || (pwd == NULL) || (iter < 0)) { - return NULL; + if ((salt == NULL) || (pwd == NULL) || (iter < 0)) { + return NULL; } - + hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); pre_hash = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if((hash != NULL) && (pre_hash != NULL)) { - int i, ph_len; - - ph_len = hashObj->length; - if((salt->len + pwd->len) > hashObj->length) { - ph_len = salt->len + pwd->len; - } - - rv = SECFailure; - - /* allocate buffers */ - hash->len = hashObj->length; - hash->data = (unsigned char *)PORT_ZAlloc(hash->len); - pre_hash->data = (unsigned char *)PORT_ZAlloc(ph_len); - - /* in pbeSHA1TripleDESCBC there was an allocation error that made - * it into the caller. We do not want to propagate those errors - * further, so we are doing it correctly, but reading the old method. - */ - if (faulty3DES) { - pre_hash->len = ph_len; - } else { - pre_hash->len = salt->len + pwd->len; - } - - /* preform hash */ - if ((hash->data != NULL) && (pre_hash->data != NULL)) { - rv = SECSuccess; - /* check for 0 length password */ - if(pwd->len > 0) { - PORT_Memcpy(pre_hash->data, pwd->data, pwd->len); - } - if(salt->len > 0) { - PORT_Memcpy((pre_hash->data+pwd->len), salt->data, salt->len); - } - for(i = 0; ((i < iter) && (rv == SECSuccess)); i++) { - rv = nsspkcs5_HashBuf(hashObj, hash->data, - pre_hash->data, pre_hash->len); - if(rv != SECFailure) { - pre_hash->len = hashObj->length; - PORT_Memcpy(pre_hash->data, hash->data, hashObj->length); - } - } - } - } - - if(pre_hash != NULL) { - SECITEM_FreeItem(pre_hash, PR_TRUE); - } - - if((rv != SECSuccess) && (hash != NULL)) { - SECITEM_FreeItem(hash, PR_TRUE); - hash = NULL; + if ((hash != NULL) && (pre_hash != NULL)) { + int i, ph_len; + + ph_len = hashObj->length; + if ((salt->len + pwd->len) > hashObj->length) { + ph_len = salt->len + pwd->len; + } + + rv = SECFailure; + + /* allocate buffers */ + hash->len = hashObj->length; + hash->data = (unsigned char *)PORT_ZAlloc(hash->len); + pre_hash->data = (unsigned char *)PORT_ZAlloc(ph_len); + + /* in pbeSHA1TripleDESCBC there was an allocation error that made + * it into the caller. We do not want to propagate those errors + * further, so we are doing it correctly, but reading the old method. + */ + if (faulty3DES) { + pre_hash->len = ph_len; + } else { + pre_hash->len = salt->len + pwd->len; + } + + /* preform hash */ + if ((hash->data != NULL) && (pre_hash->data != NULL)) { + rv = SECSuccess; + /* check for 0 length password */ + if (pwd->len > 0) { + PORT_Memcpy(pre_hash->data, pwd->data, pwd->len); + } + if (salt->len > 0) { + PORT_Memcpy((pre_hash->data + pwd->len), salt->data, salt->len); + } + for (i = 0; ((i < iter) && (rv == SECSuccess)); i++) { + rv = nsspkcs5_HashBuf(hashObj, hash->data, + pre_hash->data, pre_hash->len); + if (rv != SECFailure) { + pre_hash->len = hashObj->length; + PORT_Memcpy(pre_hash->data, hash->data, hashObj->length); + } + } + } + } + + if (pre_hash != NULL) { + SECITEM_FreeItem(pre_hash, PR_TRUE); + } + + if ((rv != SECSuccess) && (hash != NULL)) { + SECITEM_FreeItem(hash, PR_TRUE); + hash = NULL; } return hash; @@ -184,7 +180,7 @@ nsspkcs5_PBKDF1(const SECHashObject *hashObj, SECItem *salt, SECItem *pwd, */ static SECItem * nsspkcs5_PFXPBE(const SECHashObject *hashObj, NSSPKCS5PBEParameter *pbe_param, - SECItem *init_hash, unsigned int bytes_needed) + SECItem *init_hash, unsigned int bytes_needed) { SECItem *ret_bits = NULL; int hash_size = 0; @@ -200,69 +196,69 @@ nsspkcs5_PFXPBE(const SECHashObject *hashObj, NSSPKCS5PBEParameter *pbe_param, hash_iter = (bytes_needed + (unsigned int)hash_size - 1) / hash_size; /* allocate return buffer */ - ret_bits = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(ret_bits == NULL) - return NULL; + ret_bits = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); + if (ret_bits == NULL) + return NULL; ret_bits->data = (unsigned char *)PORT_ZAlloc((hash_iter * hash_size) + 1); ret_bits->len = (hash_iter * hash_size); - if(ret_bits->data == NULL) { - PORT_Free(ret_bits); - return NULL; + if (ret_bits->data == NULL) { + PORT_Free(ret_bits); + return NULL; } /* allocate intermediate hash buffer. 8 is for the 8 bytes of - * data which are added based on iteration number + * data which are added based on iteration number */ if ((unsigned int)hash_size > pbe_param->salt.len) { - state_len = hash_size; + state_len = hash_size; } else { - state_len = pbe_param->salt.len; + state_len = pbe_param->salt.len; } state = (unsigned char *)PORT_ZAlloc(state_len); - if(state == NULL) { - rv = SECFailure; - goto loser; + if (state == NULL) { + rv = SECFailure; + goto loser; } - if(pbe_param->salt.len > 0) { - PORT_Memcpy(state, pbe_param->salt.data, pbe_param->salt.len); + if (pbe_param->salt.len > 0) { + PORT_Memcpy(state, pbe_param->salt.data, pbe_param->salt.len); } cx = HMAC_Create(hashObj, init_hash->data, init_hash->len, PR_TRUE); if (cx == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } - for(i = 0; i < hash_iter; i++) { + for (i = 0; i < hash_iter; i++) { - /* generate output bits */ - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - HMAC_Update(cx, pbe_param->salt.data, pbe_param->salt.len); - rv = HMAC_Finish(cx, ret_bits->data + (i * hash_size), - &dig_len, hash_size); - if (rv != SECSuccess) - goto loser; - PORT_Assert((unsigned int)hash_size == dig_len); + /* generate output bits */ + HMAC_Begin(cx); + HMAC_Update(cx, state, state_len); + HMAC_Update(cx, pbe_param->salt.data, pbe_param->salt.len); + rv = HMAC_Finish(cx, ret_bits->data + (i * hash_size), + &dig_len, hash_size); + if (rv != SECSuccess) + goto loser; + PORT_Assert((unsigned int)hash_size == dig_len); - /* generate new state */ - HMAC_Begin(cx); - HMAC_Update(cx, state, state_len); - rv = HMAC_Finish(cx, state, &state_len, state_len); - if (rv != SECSuccess) - goto loser; - PORT_Assert(state_len == dig_len); + /* generate new state */ + HMAC_Begin(cx); + HMAC_Update(cx, state, state_len); + rv = HMAC_Finish(cx, state, &state_len, state_len); + if (rv != SECSuccess) + goto loser; + PORT_Assert(state_len == dig_len); } loser: if (state != NULL) - PORT_ZFree(state, state_len); + PORT_ZFree(state, state_len); HMAC_Destroy(cx, PR_TRUE); - if(rv != SECSuccess) { - SECITEM_ZfreeItem(ret_bits, PR_TRUE); - ret_bits = NULL; + if (rv != SECSuccess) { + SECITEM_ZfreeItem(ret_bits, PR_TRUE); + ret_bits = NULL; } return ret_bits; @@ -274,47 +270,45 @@ loser: */ static SECItem * nsspkcs5_PBKDF1Extended(const SECHashObject *hashObj, - NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, PRBool faulty3DES) + NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, PRBool faulty3DES) { - SECItem * hash = NULL; - SECItem * newHash = NULL; - int bytes_needed; - int bytes_available; - + SECItem *hash = NULL; + SECItem *newHash = NULL; + int bytes_needed; + int bytes_available; + bytes_needed = pbe_param->ivLen + pbe_param->keyLen; bytes_available = hashObj->length; - - hash = nsspkcs5_PBKDF1(hashObj, &pbe_param->salt, pwitem, - pbe_param->iter, faulty3DES); - if(hash == NULL) { - return NULL; + hash = nsspkcs5_PBKDF1(hashObj, &pbe_param->salt, pwitem, + pbe_param->iter, faulty3DES); + + if (hash == NULL) { + return NULL; } - if(bytes_needed <= bytes_available) { - return hash; - } + if (bytes_needed <= bytes_available) { + return hash; + } newHash = nsspkcs5_PFXPBE(hashObj, pbe_param, hash, bytes_needed); if (hash != newHash) - SECITEM_FreeItem(hash, PR_TRUE); + SECITEM_FreeItem(hash, PR_TRUE); return newHash; } -#ifdef PBKDF2 - /* * PBDKDF2 is PKCS #5 v2.0 it's currently not used by NSS */ static void do_xor(unsigned char *dest, unsigned char *src, int len) { - /* use byt xor, not all platforms are happy about inaligned - * integer fetches */ + /* use byt xor, not all platforms are happy about inaligned + * integer fetches */ while (len--) { - *dest = *dest ^ *src; - dest++; - src++; + *dest = *dest ^ *src; + dest++; + src++; } } @@ -330,51 +324,51 @@ nsspkcs5_PBKDF2_F(const SECHashObject *hashobj, SECItem *pwitem, SECItem *salt, unsigned int lastLength = salt->len + 4; unsigned int lastBufLength; - cx=HMAC_Create(hashobj,pwitem->data,pwitem->len,PR_FALSE); + cx = HMAC_Create(hashobj, pwitem->data, pwitem->len, PR_FALSE); if (cx == NULL) { - goto loser; + goto loser; } - PORT_Memset(T,0,hLen); + PORT_Memset(T, 0, hLen); lastBufLength = PR_MAX(lastLength, hLen); last = PORT_Alloc(lastBufLength); if (last == NULL) { - goto loser; + goto loser; } - PORT_Memcpy(last,salt->data,salt->len); - last[salt->len ] = (i >> 24) & 0xff; - last[salt->len+1] = (i >> 16) & 0xff; - last[salt->len+2] = (i >> 8) & 0xff; - last[salt->len+3] = i & 0xff; + PORT_Memcpy(last, salt->data, salt->len); + last[salt->len] = (i >> 24) & 0xff; + last[salt->len + 1] = (i >> 16) & 0xff; + last[salt->len + 2] = (i >> 8) & 0xff; + last[salt->len + 3] = i & 0xff; /* NOTE: we need at least one iteration to return success! */ - for (j=0; j < iterations; j++) { - HMAC_Begin(cx); - HMAC_Update(cx,last,lastLength); - rv =HMAC_Finish(cx,last,&lastLength,hLen); - if (rv !=SECSuccess) { - break; - } - do_xor(T,last,hLen); + for (j = 0; j < iterations; j++) { + HMAC_Begin(cx); + HMAC_Update(cx, last, lastLength); + rv = HMAC_Finish(cx, last, &lastLength, hLen); + if (rv != SECSuccess) { + break; + } + do_xor(T, last, hLen); } loser: if (cx) { - HMAC_Destroy(cx, PR_TRUE); + HMAC_Destroy(cx, PR_TRUE); } if (last) { - PORT_ZFree(last,lastBufLength); + PORT_ZFree(last, lastBufLength); } return rv; } static SECItem * -nsspkcs5_PBKDF2(const SECHashObject *hashobj, NSSPKCS5PBEParameter *pbe_param, - SECItem *pwitem) +nsspkcs5_PBKDF2(const SECHashObject *hashobj, NSSPKCS5PBEParameter *pbe_param, + SECItem *pwitem) { int iterations = pbe_param->iter; int bytesNeeded = pbe_param->keyLen; unsigned int dkLen = bytesNeeded; unsigned int hLen = hashobj->length; - unsigned int nblocks = (dkLen+hLen-1) / hLen; + unsigned int nblocks = (dkLen + hLen - 1) / hLen; unsigned int i; unsigned char *rp; unsigned char *T = NULL; @@ -382,89 +376,88 @@ nsspkcs5_PBKDF2(const SECHashObject *hashobj, NSSPKCS5PBEParameter *pbe_param, SECItem *salt = &pbe_param->salt; SECStatus rv = SECFailure; - result = SECITEM_AllocItem(NULL,NULL,nblocks*hLen); + result = SECITEM_AllocItem(NULL, NULL, nblocks * hLen); if (result == NULL) { - return NULL; + return NULL; } T = PORT_Alloc(hLen); if (T == NULL) { - goto loser; + goto loser; } - for (i=1,rp=result->data; i <= nblocks ; i++, rp +=hLen) { + for (i = 1, rp = result->data; i <= nblocks; i++, rp += hLen) { rv = nsspkcs5_PBKDF2_F(hashobj, pwitem, salt, iterations, i, T); - if (rv != SECSuccess) { - break; - } - PORT_Memcpy(rp,T,hLen); + if (rv != SECSuccess) { + break; + } + PORT_Memcpy(rp, T, hLen); } loser: if (T) { - PORT_ZFree(T,hLen); + PORT_ZFree(T, hLen); } if (rv != SECSuccess) { - SECITEM_FreeItem(result,PR_TRUE); - result = NULL; + SECITEM_FreeItem(result, PR_TRUE); + result = NULL; } else { - result->len = dkLen; + result->len = dkLen; } return result; } -#endif #define HMAC_BUFFER 64 -#define NSSPBE_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y)) -#define NSSPBE_MIN(x,y) ((x) < (y) ? (x) : (y)) +#define NSSPBE_ROUNDUP(x, y) ((((x) + ((y)-1)) / (y)) * (y)) +#define NSSPBE_MIN(x, y) ((x) < (y) ? (x) : (y)) /* * This is the extended PBE function defined by the final PKCS #12 spec. */ static SECItem * -nsspkcs5_PKCS12PBE(const SECHashObject *hashObject, - NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - PBEBitGenID bitGenPurpose, unsigned int bytesNeeded) +nsspkcs5_PKCS12PBE(const SECHashObject *hashObject, + NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, + PBEBitGenID bitGenPurpose, unsigned int bytesNeeded) { PLArenaPool *arena = NULL; - unsigned int SLen,PLen; + unsigned int SLen, PLen; unsigned int hashLength = hashObject->length; unsigned char *S, *P; SECItem *A = NULL, B, D, I; SECItem *salt = &pbe_param->salt; - unsigned int c,i = 0; + unsigned int c, i = 0; unsigned int hashLen; int iter; unsigned char *iterBuf; void *hash = NULL; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if(!arena) { - return NULL; + if (!arena) { + return NULL; } /* how many hash object lengths are needed */ - c = (bytesNeeded + (hashLength-1))/hashLength; + c = (bytesNeeded + (hashLength - 1)) / hashLength; /* initialize our buffers */ D.len = HMAC_BUFFER; /* B and D are the same length, use one alloc go get both */ - D.data = (unsigned char*)PORT_ArenaZAlloc(arena, D.len*2); + D.data = (unsigned char *)PORT_ArenaZAlloc(arena, D.len * 2); B.len = D.len; B.data = D.data + D.len; /* if all goes well, A will be returned, so don't use our temp arena */ - A = SECITEM_AllocItem(NULL,NULL,c*hashLength); + A = SECITEM_AllocItem(NULL, NULL, c * hashLength); if (A == NULL) { - goto loser; + goto loser; } - - SLen = NSSPBE_ROUNDUP(salt->len,HMAC_BUFFER); - PLen = NSSPBE_ROUNDUP(pwitem->len,HMAC_BUFFER); - I.len = SLen+PLen; - I.data = (unsigned char*)PORT_ArenaZAlloc(arena, I.len); + + SLen = NSSPBE_ROUNDUP(salt->len, HMAC_BUFFER); + PLen = NSSPBE_ROUNDUP(pwitem->len, HMAC_BUFFER); + I.len = SLen + PLen; + I.data = (unsigned char *)PORT_ArenaZAlloc(arena, I.len); if (I.data == NULL) { - goto loser; + goto loser; } /* S & P are only used to initialize I */ @@ -473,88 +466,87 @@ nsspkcs5_PKCS12PBE(const SECHashObject *hashObject, PORT_Memset(D.data, (char)bitGenPurpose, D.len); if (SLen) { - for (i=0; i < SLen; i += salt->len) { - PORT_Memcpy(S+i, salt->data, NSSPBE_MIN(SLen-i,salt->len)); - } - } + for (i = 0; i < SLen; i += salt->len) { + PORT_Memcpy(S + i, salt->data, NSSPBE_MIN(SLen - i, salt->len)); + } + } if (PLen) { - for (i=0; i < PLen; i += pwitem->len) { - PORT_Memcpy(P+i, pwitem->data, NSSPBE_MIN(PLen-i,pwitem->len)); - } - } + for (i = 0; i < PLen; i += pwitem->len) { + PORT_Memcpy(P + i, pwitem->data, NSSPBE_MIN(PLen - i, pwitem->len)); + } + } - iterBuf = (unsigned char*)PORT_ArenaZAlloc(arena,hashLength); + iterBuf = (unsigned char *)PORT_ArenaZAlloc(arena, hashLength); if (iterBuf == NULL) { - goto loser; + goto loser; } hash = hashObject->create(); - if(!hash) { - goto loser; + if (!hash) { + goto loser; } /* calculate the PBE now */ - for(i = 0; i < c; i++) { - int Bidx; /* must be signed or the for loop won't terminate */ - unsigned int k, j; - unsigned char *Ai = A->data+i*hashLength; - - - for(iter = 0; iter < pbe_param->iter; iter++) { - hashObject->begin(hash); - - if (iter) { - hashObject->update(hash, iterBuf, hashLen); - } else { - hashObject->update(hash, D.data, D.len); - hashObject->update(hash, I.data, I.len); - } - - hashObject->end(hash, iterBuf, &hashLen, hashObject->length); - if(hashLen != hashObject->length) { - break; - } - } - - PORT_Memcpy(Ai, iterBuf, hashLength); - for (Bidx = 0; Bidx < (int)B.len; Bidx += hashLength) { - PORT_Memcpy(B.data+Bidx,iterBuf,NSSPBE_MIN(B.len-Bidx,hashLength)); - } - - k = I.len/B.len; - for(j = 0; j < k; j++) { - unsigned int q, carryBit; - unsigned char *Ij = I.data + j*B.len; - - /* (Ij = Ij+B+1) */ - for (Bidx = (B.len-1), q=1, carryBit=0; Bidx >= 0; Bidx--,q=0) { - q += (unsigned int)Ij[Bidx]; - q += (unsigned int)B.data[Bidx]; - q += carryBit; - - carryBit = (q > 0xff); - Ij[Bidx] = (unsigned char)(q & 0xff); - } - } + for (i = 0; i < c; i++) { + int Bidx; /* must be signed or the for loop won't terminate */ + unsigned int k, j; + unsigned char *Ai = A->data + i * hashLength; + + for (iter = 0; iter < pbe_param->iter; iter++) { + hashObject->begin(hash); + + if (iter) { + hashObject->update(hash, iterBuf, hashLen); + } else { + hashObject->update(hash, D.data, D.len); + hashObject->update(hash, I.data, I.len); + } + + hashObject->end(hash, iterBuf, &hashLen, hashObject->length); + if (hashLen != hashObject->length) { + break; + } + } + + PORT_Memcpy(Ai, iterBuf, hashLength); + for (Bidx = 0; Bidx < (int)B.len; Bidx += hashLength) { + PORT_Memcpy(B.data + Bidx, iterBuf, NSSPBE_MIN(B.len - Bidx, hashLength)); + } + + k = I.len / B.len; + for (j = 0; j < k; j++) { + unsigned int q, carryBit; + unsigned char *Ij = I.data + j * B.len; + + /* (Ij = Ij+B+1) */ + for (Bidx = (B.len - 1), q = 1, carryBit = 0; Bidx >= 0; Bidx--, q = 0) { + q += (unsigned int)Ij[Bidx]; + q += (unsigned int)B.data[Bidx]; + q += carryBit; + + carryBit = (q > 0xff); + Ij[Bidx] = (unsigned char)(q & 0xff); + } + } } loser: if (hash) { - hashObject->destroy(hash, PR_TRUE); + hashObject->destroy(hash, PR_TRUE); } - if(arena) { - PORT_FreeArena(arena, PR_TRUE); + if (arena) { + PORT_FreeArena(arena, PR_TRUE); } if (A) { /* if i != c, then we didn't complete the loop above and must of failed * somwhere along the way */ if (i != c) { - SECITEM_ZfreeItem(A,PR_TRUE); - A = NULL; + SECITEM_ZfreeItem(A, PR_TRUE); + A = NULL; } else { - A->len = bytesNeeded; + A->len = bytesNeeded; } } - + return A; } @@ -563,78 +555,76 @@ loser: */ SECItem * nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - SECItem *iv, PRBool faulty3DES) + SECItem *iv, PRBool faulty3DES) { SECItem *hash = NULL, *key = NULL; const SECHashObject *hashObj; PRBool getIV = PR_FALSE; - if((pbe_param == NULL) || (pwitem == NULL)) { - return NULL; + if ((pbe_param == NULL) || (pwitem == NULL)) { + return NULL; } - key = SECITEM_AllocItem(NULL,NULL,pbe_param->keyLen); + key = SECITEM_AllocItem(NULL, NULL, pbe_param->keyLen); if (key == NULL) { - return NULL; + return NULL; } if (iv && (pbe_param->ivLen) && (iv->data == NULL)) { - getIV = PR_TRUE; - iv->data = (unsigned char *)PORT_Alloc(pbe_param->ivLen); - if (iv->data == NULL) { - goto loser; - } - iv->len = pbe_param->ivLen; + getIV = PR_TRUE; + iv->data = (unsigned char *)PORT_Alloc(pbe_param->ivLen); + if (iv->data == NULL) { + goto loser; + } + iv->len = pbe_param->ivLen; } hashObj = HASH_GetRawHashObject(pbe_param->hashType); switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - hash = nsspkcs5_PBKDF1Extended(hashObj,pbe_param,pwitem,faulty3DES); - if (hash == NULL) { - goto loser; - } - PORT_Assert(hash->len >= key->len+(getIV ? iv->len : 0)); - if (getIV) { - PORT_Memcpy(iv->data, hash->data+(hash->len - iv->len),iv->len); - } - - break; -#ifdef PBKDF2 - case NSSPKCS5_PBKDF2: - hash = nsspkcs5_PBKDF2(hashObj,pbe_param,pwitem); - if (getIV) { - PORT_Memcpy(iv->data, pbe_param->ivData, iv->len); - } - break; -#endif - case NSSPKCS5_PKCS12_V2: - if (getIV) { - hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem, - pbeBitGenCipherIV,iv->len); - if (hash == NULL) { - goto loser; - } - PORT_Memcpy(iv->data,hash->data,iv->len); - SECITEM_ZfreeItem(hash,PR_TRUE); - hash = NULL; - } - hash = nsspkcs5_PKCS12PBE(hashObj,pbe_param,pwitem, - pbe_param->keyID,key->len); - default: - break; + case NSSPKCS5_PBKDF1: + hash = nsspkcs5_PBKDF1Extended(hashObj, pbe_param, pwitem, faulty3DES); + if (hash == NULL) { + goto loser; + } + PORT_Assert(hash->len >= key->len + (getIV ? iv->len : 0)); + if (getIV) { + PORT_Memcpy(iv->data, hash->data + (hash->len - iv->len), iv->len); + } + + break; + case NSSPKCS5_PBKDF2: + hash = nsspkcs5_PBKDF2(hashObj, pbe_param, pwitem); + if (getIV) { + PORT_Memcpy(iv->data, pbe_param->ivData, iv->len); + } + break; + case NSSPKCS5_PKCS12_V2: + if (getIV) { + hash = nsspkcs5_PKCS12PBE(hashObj, pbe_param, pwitem, + pbeBitGenCipherIV, iv->len); + if (hash == NULL) { + goto loser; + } + PORT_Memcpy(iv->data, hash->data, iv->len); + SECITEM_ZfreeItem(hash, PR_TRUE); + hash = NULL; + } + hash = nsspkcs5_PKCS12PBE(hashObj, pbe_param, pwitem, + pbe_param->keyID, key->len); + default: + break; } if (hash == NULL) { - goto loser; + goto loser; } if (pbe_param->is2KeyDES) { - PORT_Memcpy(key->data, hash->data, (key->len * 2) / 3); - PORT_Memcpy(&(key->data[(key->len * 2) / 3]), key->data, - key->len / 3); + PORT_Memcpy(key->data, hash->data, (key->len * 2) / 3); + PORT_Memcpy(&(key->data[(key->len * 2) / 3]), key->data, + key->len / 3); } else { - PORT_Memcpy(key->data, hash->data, key->len); + PORT_Memcpy(key->data, hash->data, key->len); } SECITEM_ZfreeItem(hash, PR_TRUE); @@ -642,8 +632,8 @@ nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, loser: if (getIV && iv->data) { - PORT_ZFree(iv->data,iv->len); - iv->data = NULL; + PORT_ZFree(iv->data, iv->len); + iv->data = NULL; } SECITEM_ZfreeItem(key, PR_TRUE); @@ -651,86 +641,85 @@ loser: } static SECStatus -nsspkcs5_FillInParam(SECOidTag algorithm, NSSPKCS5PBEParameter *pbe_param) +nsspkcs5_FillInParam(SECOidTag algorithm, HASH_HashType hashType, + NSSPKCS5PBEParameter *pbe_param) { PRBool skipType = PR_FALSE; pbe_param->keyLen = 5; pbe_param->ivLen = 8; - pbe_param->hashType = HASH_AlgSHA1; + pbe_param->hashType = hashType; pbe_param->pbeType = NSSPKCS5_PBKDF1; pbe_param->encAlg = SEC_OID_RC2_CBC; pbe_param->is2KeyDES = PR_FALSE; - switch(algorithm) { - /* DES3 Algorithms */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC: - pbe_param->is2KeyDES = PR_TRUE; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC: - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC: - pbe_param->keyLen = 24; - pbe_param->encAlg = SEC_OID_DES_EDE3_CBC; - break; - - /* DES Algorithms */ - case SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC: - pbe_param->hashType = HASH_AlgMD2; - goto finish_des; - case SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC: - pbe_param->hashType = HASH_AlgMD5; - /* fall through */ - case SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC: -finish_des: - pbe_param->keyLen = 8; - pbe_param->encAlg = SEC_OID_DES_CBC; - break; - - /* RC2 Algorithms */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - break; - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: - break; - - /* RC4 algorithms */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC4: - skipType = PR_TRUE; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4: - pbe_param->keyLen = 16; - /* fall through */ - case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4: - if (!skipType) { - pbe_param->pbeType = NSSPKCS5_PKCS12_V2; - } - /* fall through */ - case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC4: - pbe_param->ivLen = 0; - pbe_param->encAlg = SEC_OID_RC4; - break; - -#ifdef PBKDF2 - case SEC_OID_PKCS5_PBKDF2: - case SEC_OID_PKCS5_PBES2: - case SEC_OID_PKCS5_PBMAC1: - /* everything else will be filled in by the template */ - pbe_param->ivLen = 0; - pbe_param->pbeType = NSSPKCS5_PBKDF2; - pbe_param->encAlg = SEC_OID_PKCS5_PBKDF2; - pbe_param->keyLen = 0; /* needs to be set by caller after return */ - break; -#endif - - default: - return SECFailure; + switch (algorithm) { + /* DES3 Algorithms */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC: + pbe_param->is2KeyDES = PR_TRUE; + /* fall through */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC: + pbe_param->pbeType = NSSPKCS5_PKCS12_V2; + /* fall through */ + case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC: + pbe_param->keyLen = 24; + pbe_param->encAlg = SEC_OID_DES_EDE3_CBC; + break; + + /* DES Algorithms */ + case SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC: + pbe_param->hashType = HASH_AlgMD2; + goto finish_des; + case SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC: + pbe_param->hashType = HASH_AlgMD5; + /* fall through */ + case SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC: + finish_des: + pbe_param->keyLen = 8; + pbe_param->encAlg = SEC_OID_DES_CBC; + break; + + /* RC2 Algorithms */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: + pbe_param->keyLen = 16; + /* fall through */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: + pbe_param->pbeType = NSSPKCS5_PKCS12_V2; + break; + case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC: + pbe_param->keyLen = 16; + /* fall through */ + case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC: + break; + + /* RC4 algorithms */ + case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_128_BIT_RC4: + skipType = PR_TRUE; + /* fall through */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4: + pbe_param->keyLen = 16; + /* fall through */ + case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4: + if (!skipType) { + pbe_param->pbeType = NSSPKCS5_PKCS12_V2; + } + /* fall through */ + case SEC_OID_PKCS12_PBE_WITH_SHA1_AND_40_BIT_RC4: + pbe_param->ivLen = 0; + pbe_param->encAlg = SEC_OID_RC4; + break; + + case SEC_OID_PKCS5_PBKDF2: + case SEC_OID_PKCS5_PBES2: + case SEC_OID_PKCS5_PBMAC1: + /* everything else will be filled in by the template */ + pbe_param->ivLen = 0; + pbe_param->pbeType = NSSPKCS5_PBKDF2; + pbe_param->encAlg = SEC_OID_PKCS5_PBKDF2; + pbe_param->keyLen = 0; /* needs to be set by caller after return */ + break; + + default: + return SECFailure; } return SECSuccess; @@ -739,7 +728,8 @@ finish_des: /* decode the algid and generate a PKCS 5 parameter from it */ NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) +nsspkcs5_NewParam(SECOidTag alg, HASH_HashType hashType, SECItem *salt, + int iterationCount) { PLArenaPool *arena = NULL; NSSPKCS5PBEParameter *pbe_param = NULL; @@ -747,26 +737,26 @@ nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); if (arena == NULL) - return NULL; + return NULL; /* allocate memory for the parameter */ - pbe_param = (NSSPKCS5PBEParameter *)PORT_ArenaZAlloc(arena, - sizeof(NSSPKCS5PBEParameter)); + pbe_param = (NSSPKCS5PBEParameter *)PORT_ArenaZAlloc(arena, + sizeof(NSSPKCS5PBEParameter)); if (pbe_param == NULL) { - goto loser; + goto loser; } pbe_param->poolp = arena; - rv = nsspkcs5_FillInParam(alg, pbe_param); + rv = nsspkcs5_FillInParam(alg, hashType, pbe_param); if (rv != SECSuccess) { - goto loser; + goto loser; } - pbe_param->iter = iterator; + pbe_param->iter = iterationCount; if (salt) { - rv = SECITEM_CopyItem(arena,&pbe_param->salt,salt); + rv = SECITEM_CopyItem(arena, &pbe_param->salt, salt); } /* default key gen */ @@ -774,8 +764,8 @@ nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator) loser: if (rv != SECSuccess) { - PORT_FreeArena(arena, PR_TRUE); - pbe_param = NULL; + PORT_FreeArena(arena, PR_TRUE); + pbe_param = NULL; } return pbe_param; @@ -789,17 +779,17 @@ HASH_HashType HASH_FromHMACOid(SECOidTag hmac) { switch (hmac) { - case SEC_OID_HMAC_SHA1: - return HASH_AlgSHA1; - case SEC_OID_HMAC_SHA256: - return HASH_AlgSHA256; - case SEC_OID_HMAC_SHA384: - return HASH_AlgSHA384; - case SEC_OID_HMAC_SHA512: - return HASH_AlgSHA512; - case SEC_OID_HMAC_SHA224: - default: - break; + case SEC_OID_HMAC_SHA1: + return HASH_AlgSHA1; + case SEC_OID_HMAC_SHA256: + return HASH_AlgSHA256; + case SEC_OID_HMAC_SHA384: + return HASH_AlgSHA384; + case SEC_OID_HMAC_SHA512: + return HASH_AlgSHA512; + case SEC_OID_HMAC_SHA224: + default: + break; } return HASH_AlgNULL; } @@ -815,169 +805,166 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid) SECStatus rv = SECFailure; if (algid == NULL) { - return NULL; + return NULL; } algorithm = SECOID_GetAlgorithmTag(algid); if (algorithm == SEC_OID_UNKNOWN) { - goto loser; + goto loser; } - pbe_param = nsspkcs5_NewParam(algorithm, NULL, 1); + pbe_param = nsspkcs5_NewParam(algorithm, HASH_AlgSHA1, NULL, 1); if (pbe_param == NULL) { - goto loser; + goto loser; } /* decode parameter */ rv = SECFailure; switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5PBEParameterTemplate, &algid->parameters); - break; - case NSSPKCS5_PKCS12_V2: - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5PKCS12V2PBEParameterTemplate, &algid->parameters); - break; -#ifdef PBKDF2 - case NSSPKCS5_PBKDF2: - PORT_Memset(&pbev2_param,0, sizeof(pbev2_param)); - /* just the PBE */ - if (algorithm == SEC_OID_PKCS5_PBKDF2) { - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5V2PBEParameterTemplate, &algid->parameters); - } else { - /* PBE data an others */ - rv = SEC_ASN1DecodeItem(pbe_param->poolp, &pbev2_param, - NSSPKCS5V2PBES2ParameterTemplate, &algid->parameters); - if (rv != SECSuccess) { - break; - } - pbe_param->encAlg = SECOID_GetAlgorithmTag(&pbev2_param.algParams); - rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, - NSSPKCS5V2PBEParameterTemplate, - &pbev2_param.keyParams.parameters); - if (rv != SECSuccess) { - break; - } - pbe_param->keyLen = DER_GetInteger(&pbe_param->keyLength); - } - /* we we are encrypting, save any iv's */ - if (algorithm == SEC_OID_PKCS5_PBES2) { - pbe_param->ivLen = pbev2_param.algParams.parameters.len; - pbe_param->ivData = pbev2_param.algParams.parameters.data; - } - pbe_param->hashType = - HASH_FromHMACOid(SECOID_GetAlgorithmTag(&pbe_param->prfAlg)); - if (pbe_param->hashType == HASH_AlgNULL) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - rv = SECFailure; - } - break; -#endif + case NSSPKCS5_PBKDF1: + rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, + NSSPKCS5PBEParameterTemplate, &algid->parameters); + break; + case NSSPKCS5_PKCS12_V2: + rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, + NSSPKCS5PKCS12V2PBEParameterTemplate, &algid->parameters); + break; + case NSSPKCS5_PBKDF2: + PORT_Memset(&pbev2_param, 0, sizeof(pbev2_param)); + /* just the PBE */ + if (algorithm == SEC_OID_PKCS5_PBKDF2) { + rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, + NSSPKCS5V2PBEParameterTemplate, &algid->parameters); + } else { + /* PBE data an others */ + rv = SEC_ASN1DecodeItem(pbe_param->poolp, &pbev2_param, + NSSPKCS5V2PBES2ParameterTemplate, &algid->parameters); + if (rv != SECSuccess) { + break; + } + pbe_param->encAlg = SECOID_GetAlgorithmTag(&pbev2_param.algParams); + rv = SEC_ASN1DecodeItem(pbe_param->poolp, pbe_param, + NSSPKCS5V2PBEParameterTemplate, + &pbev2_param.keyParams.parameters); + if (rv != SECSuccess) { + break; + } + pbe_param->keyLen = DER_GetInteger(&pbe_param->keyLength); + } + /* we we are encrypting, save any iv's */ + if (algorithm == SEC_OID_PKCS5_PBES2) { + pbe_param->ivLen = pbev2_param.algParams.parameters.len; + pbe_param->ivData = pbev2_param.algParams.parameters.data; + } + pbe_param->hashType = + HASH_FromHMACOid(SECOID_GetAlgorithmTag(&pbe_param->prfAlg)); + if (pbe_param->hashType == HASH_AlgNULL) { + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + rv = SECFailure; + } + break; } loser: if (rv == SECSuccess) { - pbe_param->iter = DER_GetInteger(&pbe_param->iteration); + pbe_param->iter = DER_GetInteger(&pbe_param->iteration); } else { - nsspkcs5_DestroyPBEParameter(pbe_param); - pbe_param = NULL; + nsspkcs5_DestroyPBEParameter(pbe_param); + pbe_param = NULL; } return pbe_param; } -/* destroy a pbe parameter. it assumes that the parameter was +/* destroy a pbe parameter. it assumes that the parameter was * generated using the appropriate create function and therefor * contains an arena pool. */ -void +void nsspkcs5_DestroyPBEParameter(NSSPKCS5PBEParameter *pbe_param) { if (pbe_param != NULL) { - PORT_FreeArena(pbe_param->poolp, PR_FALSE); + PORT_FreeArena(pbe_param->poolp, PR_FALSE); } } - /* crypto routines */ /* perform DES encryption and decryption. these routines are called * by nsspkcs5_CipherData. In the case of an error, NULL is returned. */ static SECItem * -sec_pkcs5_des(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, - PRBool encrypt) +sec_pkcs5_des(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, + PRBool encrypt) { SECItem *dest; SECItem *dup_src; SECStatus rv = SECFailure; int pad; - if((src == NULL) || (key == NULL) || (iv == NULL)) - return NULL; + if ((src == NULL) || (key == NULL) || (iv == NULL)) + return NULL; dup_src = SECITEM_DupItem(src); - if(dup_src == NULL) { - return NULL; + if (dup_src == NULL) { + return NULL; } - if(encrypt != PR_FALSE) { - void *dummy; + if (encrypt != PR_FALSE) { + void *dummy; - dummy = CBC_PadBuffer(NULL, dup_src->data, - dup_src->len, &dup_src->len, 8 /* DES_BLOCK_SIZE */); - if(dummy == NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - return NULL; - } - dup_src->data = (unsigned char*)dummy; + dummy = CBC_PadBuffer(NULL, dup_src->data, + dup_src->len, &dup_src->len, 8 /* DES_BLOCK_SIZE */); + if (dummy == NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); + return NULL; + } + dup_src->data = (unsigned char *)dummy; } dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - /* allocate with over flow */ - dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); - if(dest->data != NULL) { - DESContext *ctxt; - ctxt = DES_CreateContext(key->data, iv->data, - (triple_des ? NSS_DES_EDE3_CBC : NSS_DES_CBC), - encrypt); - - if(ctxt != NULL) { - rv = (encrypt ? DES_Encrypt : DES_Decrypt)( - ctxt, dest->data, &dest->len, - dup_src->len + 64, dup_src->data, dup_src->len); - - /* remove padding -- assumes 64 bit blocks */ - if((encrypt == PR_FALSE) && (rv == SECSuccess)) { - pad = dest->data[dest->len-1]; - if((pad > 0) && (pad <= 8)) { - if(dest->data[dest->len-pad] != pad) { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } else { - dest->len -= pad; - } - } else { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } - } - DES_DestroyContext(ctxt, PR_TRUE); - } - } - } - - if(rv == SECFailure) { - if(dest != NULL) { - SECITEM_FreeItem(dest, PR_TRUE); - } - dest = NULL; - } - - if(dup_src != NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); + if (dest != NULL) { + /* allocate with over flow */ + dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); + if (dest->data != NULL) { + DESContext *ctxt; + ctxt = DES_CreateContext(key->data, iv->data, + (triple_des ? NSS_DES_EDE3_CBC : NSS_DES_CBC), + encrypt); + + if (ctxt != NULL) { + rv = (encrypt ? DES_Encrypt : DES_Decrypt)( + ctxt, dest->data, &dest->len, + dup_src->len + 64, dup_src->data, dup_src->len); + + /* remove padding -- assumes 64 bit blocks */ + if ((encrypt == PR_FALSE) && (rv == SECSuccess)) { + pad = dest->data[dest->len - 1]; + if ((pad > 0) && (pad <= 8)) { + if (dest->data[dest->len - pad] != pad) { + rv = SECFailure; + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + } else { + dest->len -= pad; + } + } else { + rv = SECFailure; + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + } + } + DES_DestroyContext(ctxt, PR_TRUE); + } + } + } + + if (rv == SECFailure) { + if (dest != NULL) { + SECITEM_FreeItem(dest, PR_TRUE); + } + dest = NULL; + } + + if (dup_src != NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); } return dest; @@ -986,77 +973,77 @@ sec_pkcs5_des(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, /* perform aes encryption/decryption if an error occurs, NULL is returned */ static SECItem * -sec_pkcs5_aes(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, - PRBool encrypt) +sec_pkcs5_aes(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, + PRBool encrypt) { SECItem *dest; SECItem *dup_src; SECStatus rv = SECFailure; int pad; - if((src == NULL) || (key == NULL) || (iv == NULL)) - return NULL; + if ((src == NULL) || (key == NULL) || (iv == NULL)) + return NULL; dup_src = SECITEM_DupItem(src); - if(dup_src == NULL) { - return NULL; + if (dup_src == NULL) { + return NULL; } - if(encrypt != PR_FALSE) { - void *dummy; + if (encrypt != PR_FALSE) { + void *dummy; - dummy = CBC_PadBuffer(NULL, dup_src->data, - dup_src->len, &dup_src->len,AES_BLOCK_SIZE); - if(dummy == NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - return NULL; - } - dup_src->data = (unsigned char*)dummy; + dummy = CBC_PadBuffer(NULL, dup_src->data, + dup_src->len, &dup_src->len, AES_BLOCK_SIZE); + if (dummy == NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); + return NULL; + } + dup_src->data = (unsigned char *)dummy; } dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - /* allocate with over flow */ - dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); - if(dest->data != NULL) { - AESContext *ctxt; - ctxt = AES_CreateContext(key->data, iv->data, - NSS_AES_CBC, encrypt, key->len, 16); - - if(ctxt != NULL) { - rv = (encrypt ? AES_Encrypt : AES_Decrypt)( - ctxt, dest->data, &dest->len, - dup_src->len + 64, dup_src->data, dup_src->len); - - /* remove padding -- assumes 64 bit blocks */ - if((encrypt == PR_FALSE) && (rv == SECSuccess)) { - pad = dest->data[dest->len-1]; - if((pad > 0) && (pad <= 16)) { - if(dest->data[dest->len-pad] != pad) { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } else { - dest->len -= pad; - } - } else { - rv = SECFailure; - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - } - } - AES_DestroyContext(ctxt, PR_TRUE); - } - } - } - - if(rv == SECFailure) { - if(dest != NULL) { - SECITEM_FreeItem(dest, PR_TRUE); - } - dest = NULL; - } - - if(dup_src != NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); + if (dest != NULL) { + /* allocate with over flow */ + dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); + if (dest->data != NULL) { + AESContext *ctxt; + ctxt = AES_CreateContext(key->data, iv->data, + NSS_AES_CBC, encrypt, key->len, 16); + + if (ctxt != NULL) { + rv = (encrypt ? AES_Encrypt : AES_Decrypt)( + ctxt, dest->data, &dest->len, + dup_src->len + 64, dup_src->data, dup_src->len); + + /* remove padding -- assumes 64 bit blocks */ + if ((encrypt == PR_FALSE) && (rv == SECSuccess)) { + pad = dest->data[dest->len - 1]; + if ((pad > 0) && (pad <= 16)) { + if (dest->data[dest->len - pad] != pad) { + rv = SECFailure; + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + } else { + dest->len -= pad; + } + } else { + rv = SECFailure; + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + } + } + AES_DestroyContext(ctxt, PR_TRUE); + } + } + } + + if (rv == SECFailure) { + if (dest != NULL) { + SECITEM_FreeItem(dest, PR_TRUE); + } + dest = NULL; + } + + if (dup_src != NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); } return dest; @@ -1065,76 +1052,75 @@ sec_pkcs5_aes(SECItem *key, SECItem *iv, SECItem *src, PRBool triple_des, /* perform rc2 encryption/decryption if an error occurs, NULL is returned */ static SECItem * -sec_pkcs5_rc2(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy, - PRBool encrypt) +sec_pkcs5_rc2(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy, + PRBool encrypt) { SECItem *dest; SECItem *dup_src; SECStatus rv = SECFailure; int pad; - if((src == NULL) || (key == NULL) || (iv == NULL)) { - return NULL; + if ((src == NULL) || (key == NULL) || (iv == NULL)) { + return NULL; } dup_src = SECITEM_DupItem(src); - if(dup_src == NULL) { - return NULL; + if (dup_src == NULL) { + return NULL; } - if(encrypt != PR_FALSE) { - void *dummy; + if (encrypt != PR_FALSE) { + void *dummy; - dummy = CBC_PadBuffer(NULL, dup_src->data, - dup_src->len, &dup_src->len, 8 /* RC2_BLOCK_SIZE */); - if(dummy == NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); - return NULL; - } - dup_src->data = (unsigned char*)dummy; + dummy = CBC_PadBuffer(NULL, dup_src->data, + dup_src->len, &dup_src->len, 8 /* RC2_BLOCK_SIZE */); + if (dummy == NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); + return NULL; + } + dup_src->data = (unsigned char *)dummy; } dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); - if(dest->data != NULL) { - RC2Context *ctxt; - - ctxt = RC2_CreateContext(key->data, key->len, iv->data, - NSS_RC2_CBC, key->len); - - if(ctxt != NULL) { - rv = (encrypt ? RC2_Encrypt: RC2_Decrypt)( - ctxt, dest->data, &dest->len, - dup_src->len + 64, dup_src->data, dup_src->len); - - /* assumes 8 byte blocks -- remove padding */ - if((rv == SECSuccess) && (encrypt != PR_TRUE)) { - pad = dest->data[dest->len-1]; - if((pad > 0) && (pad <= 8)) { - if(dest->data[dest->len-pad] != pad) { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - rv = SECFailure; - } else { - dest->len -= pad; - } - } else { - PORT_SetError(SEC_ERROR_BAD_PASSWORD); - rv = SECFailure; - } - } - - } - } + if (dest != NULL) { + dest->data = (unsigned char *)PORT_ZAlloc(dup_src->len + 64); + if (dest->data != NULL) { + RC2Context *ctxt; + + ctxt = RC2_CreateContext(key->data, key->len, iv->data, + NSS_RC2_CBC, key->len); + + if (ctxt != NULL) { + rv = (encrypt ? RC2_Encrypt : RC2_Decrypt)( + ctxt, dest->data, &dest->len, + dup_src->len + 64, dup_src->data, dup_src->len); + + /* assumes 8 byte blocks -- remove padding */ + if ((rv == SECSuccess) && (encrypt != PR_TRUE)) { + pad = dest->data[dest->len - 1]; + if ((pad > 0) && (pad <= 8)) { + if (dest->data[dest->len - pad] != pad) { + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + rv = SECFailure; + } else { + dest->len -= pad; + } + } else { + PORT_SetError(SEC_ERROR_BAD_PASSWORD); + rv = SECFailure; + } + } + } + } } - if((rv != SECSuccess) && (dest != NULL)) { - SECITEM_FreeItem(dest, PR_TRUE); - dest = NULL; + if ((rv != SECSuccess) && (dest != NULL)) { + SECITEM_FreeItem(dest, PR_TRUE); + dest = NULL; } - if(dup_src != NULL) { - SECITEM_FreeItem(dup_src, PR_TRUE); + if (dup_src != NULL) { + SECITEM_FreeItem(dup_src, PR_TRUE); } return dest; @@ -1143,53 +1129,53 @@ sec_pkcs5_rc2(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy, /* perform rc4 encryption and decryption */ static SECItem * sec_pkcs5_rc4(SECItem *key, SECItem *iv, SECItem *src, PRBool dummy_op, - PRBool encrypt) + PRBool encrypt) { SECItem *dest; SECStatus rv = SECFailure; - if((src == NULL) || (key == NULL) || (iv == NULL)) { - return NULL; + if ((src == NULL) || (key == NULL) || (iv == NULL)) { + return NULL; } dest = (SECItem *)PORT_ZAlloc(sizeof(SECItem)); - if(dest != NULL) { - dest->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * - (src->len + 64)); - if(dest->data != NULL) { - RC4Context *ctxt; - - ctxt = RC4_CreateContext(key->data, key->len); - if(ctxt) { - rv = (encrypt ? RC4_Encrypt : RC4_Decrypt)( - ctxt, dest->data, &dest->len, - src->len + 64, src->data, src->len); - RC4_DestroyContext(ctxt, PR_TRUE); - } - } + if (dest != NULL) { + dest->data = (unsigned char *)PORT_ZAlloc(sizeof(unsigned char) * + (src->len + 64)); + if (dest->data != NULL) { + RC4Context *ctxt; + + ctxt = RC4_CreateContext(key->data, key->len); + if (ctxt) { + rv = (encrypt ? RC4_Encrypt : RC4_Decrypt)( + ctxt, dest->data, &dest->len, + src->len + 64, src->data, src->len); + RC4_DestroyContext(ctxt, PR_TRUE); + } + } } - if((rv != SECSuccess) && (dest)) { - SECITEM_FreeItem(dest, PR_TRUE); - dest = NULL; + if ((rv != SECSuccess) && (dest)) { + SECITEM_FreeItem(dest, PR_TRUE); + dest = NULL; } return dest; } /* function pointer template for crypto functions */ -typedef SECItem *(* pkcs5_crypto_func)(SECItem *key, SECItem *iv, - SECItem *src, PRBool op1, PRBool op2); +typedef SECItem *(*pkcs5_crypto_func)(SECItem *key, SECItem *iv, + SECItem *src, PRBool op1, PRBool op2); /* performs the cipher operation on the src and returns the result. - * if an error occurs, NULL is returned. + * if an error occurs, NULL is returned. * * a null length password is allowed. this corresponds to encrypting * the data with ust the salt. */ /* change this to use PKCS 11? */ SECItem * -nsspkcs5_CipherData(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, - SECItem *src, PRBool encrypt, PRBool *update) +nsspkcs5_CipherData(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, + SECItem *src, PRBool encrypt, PRBool *update) { SECItem *key = NULL, iv; SECItem *dest = NULL; @@ -1198,71 +1184,72 @@ nsspkcs5_CipherData(NSSPKCS5PBEParameter *pbe_param, SECItem *pwitem, iv.data = NULL; - if (update) { + if (update) { *update = PR_FALSE; } if ((pwitem == NULL) || (src == NULL)) { - return NULL; + return NULL; } /* get key, and iv */ key = nsspkcs5_ComputeKeyAndIV(pbe_param, pwitem, &iv, PR_FALSE); - if(key == NULL) { - return NULL; - } - - switch(pbe_param->encAlg) { - /* PKCS 5 v2 only */ - case SEC_OID_AES_128_CBC: - case SEC_OID_AES_192_CBC: - case SEC_OID_AES_256_CBC: - cryptof = sec_pkcs5_aes; - break; - case SEC_OID_DES_EDE3_CBC: - cryptof = sec_pkcs5_des; - tripleDES = PR_TRUE; - break; - case SEC_OID_DES_CBC: - cryptof = sec_pkcs5_des; - tripleDES = PR_FALSE; - break; - case SEC_OID_RC2_CBC: - cryptof = sec_pkcs5_rc2; - break; - case SEC_OID_RC4: - cryptof = sec_pkcs5_rc4; - break; - default: - cryptof = NULL; - break; + if (key == NULL) { + return NULL; + } + + switch (pbe_param->encAlg) { + /* PKCS 5 v2 only */ + case SEC_OID_AES_128_CBC: + case SEC_OID_AES_192_CBC: + case SEC_OID_AES_256_CBC: + cryptof = sec_pkcs5_aes; + break; + case SEC_OID_DES_EDE3_CBC: + cryptof = sec_pkcs5_des; + tripleDES = PR_TRUE; + break; + case SEC_OID_DES_CBC: + cryptof = sec_pkcs5_des; + tripleDES = PR_FALSE; + break; + case SEC_OID_RC2_CBC: + cryptof = sec_pkcs5_rc2; + break; + case SEC_OID_RC4: + cryptof = sec_pkcs5_rc4; + break; + default: + cryptof = NULL; + break; } if (cryptof == NULL) { - goto loser; + goto loser; } dest = (*cryptof)(key, &iv, src, tripleDES, encrypt); - /* + /* * it's possible for some keys and keydb's to claim to * be triple des when they're really des. In this case * we simply try des. If des works we set the update flag * so the key db knows it needs to update all it's entries. - * The case can only happen on decrypted of a + * The case can only happen on decrypted of a * SEC_OID_DES_EDE3_CBD. */ - if ((dest == NULL) && (encrypt == PR_FALSE) && - (pbe_param->encAlg == SEC_OID_DES_EDE3_CBC)) { - dest = (*cryptof)(key, &iv, src, PR_FALSE, encrypt); - if (update && (dest != NULL)) *update = PR_TRUE; + if ((dest == NULL) && (encrypt == PR_FALSE) && + (pbe_param->encAlg == SEC_OID_DES_EDE3_CBC)) { + dest = (*cryptof)(key, &iv, src, PR_FALSE, encrypt); + if (update && (dest != NULL)) + *update = PR_TRUE; } loser: if (key != NULL) { - SECITEM_ZfreeItem(key, PR_TRUE); + SECITEM_ZfreeItem(key, PR_TRUE); } if (iv.data != NULL) { - SECITEM_ZfreeItem(&iv, PR_FALSE); + SECITEM_ZfreeItem(&iv, PR_FALSE); } return dest; @@ -1271,14 +1258,14 @@ loser: /* creates a algorithm ID containing the PBE algorithm and appropriate * parameters. the required parameter is the algorithm. if salt is * not specified, it is generated randomly. if IV is specified, it overrides - * the PKCS 5 generation of the IV. + * the PKCS 5 generation of the IV. * - * the returned SECAlgorithmID should be destroyed using + * the returned SECAlgorithmID should be destroyed using * SECOID_DestroyAlgorithmID */ SECAlgorithmID * nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, - NSSPKCS5PBEParameter *pbe_param) + NSSPKCS5PBEParameter *pbe_param) { SECAlgorithmID *algid, *ret_algid = NULL; SECItem der_param; @@ -1288,7 +1275,7 @@ nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, void *dummy = NULL; if (arena == NULL) { - return NULL; + return NULL; } der_param.data = NULL; @@ -1297,82 +1284,80 @@ nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, /* generate the algorithm id */ algid = (SECAlgorithmID *)PORT_ArenaZAlloc(arena, sizeof(SECAlgorithmID)); if (algid == NULL) { - goto loser; + goto loser; } if (pbe_param->iteration.data == NULL) { - dummy = SEC_ASN1EncodeInteger(pbe_param->poolp,&pbe_param->iteration, - pbe_param->iter); - if (dummy == NULL) { - goto loser; - } + dummy = SEC_ASN1EncodeInteger(pbe_param->poolp, &pbe_param->iteration, + pbe_param->iter); + if (dummy == NULL) { + goto loser; + } } switch (pbe_param->pbeType) { - case NSSPKCS5_PBKDF1: - dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, - NSSPKCS5PBEParameterTemplate); - break; - case NSSPKCS5_PKCS12_V2: - dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, - NSSPKCS5PKCS12V2PBEParameterTemplate); - break; -#ifdef PBKDF2 - case NSSPKCS5_PBKDF2: - if (pbe_param->keyLength.data == NULL) { - dummy = SEC_ASN1EncodeInteger(pbe_param->poolp, - &pbe_param->keyLength, pbe_param->keyLen); - if (dummy == NULL) { - goto loser; - } - } - PORT_Memset(&pkcs5v2_param, 0, sizeof(pkcs5v2_param)); - dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, - NSSPKCS5V2PBEParameterTemplate); - if (dummy == NULL) { - break; - } - dummy = NULL; - rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.keyParams, - SEC_OID_PKCS5_PBKDF2, &der_param); - if (rv != SECSuccess) { - break; - } - der_param.data = pbe_param->ivData; - der_param.len = pbe_param->ivLen; - rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.algParams, - pbe_param->encAlg, pbe_param->ivLen ? &der_param : NULL); - if (rv != SECSuccess) { - break; - } - dummy = SEC_ASN1EncodeItem(arena, &der_param, &pkcs5v2_param, - NSSPKCS5V2PBES2ParameterTemplate); - break; -#endif - default: - break; + case NSSPKCS5_PBKDF1: + dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, + NSSPKCS5PBEParameterTemplate); + break; + case NSSPKCS5_PKCS12_V2: + dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, + NSSPKCS5PKCS12V2PBEParameterTemplate); + break; + case NSSPKCS5_PBKDF2: + if (pbe_param->keyLength.data == NULL) { + dummy = SEC_ASN1EncodeInteger(pbe_param->poolp, + &pbe_param->keyLength, pbe_param->keyLen); + if (dummy == NULL) { + goto loser; + } + } + PORT_Memset(&pkcs5v2_param, 0, sizeof(pkcs5v2_param)); + dummy = SEC_ASN1EncodeItem(arena, &der_param, pbe_param, + NSSPKCS5V2PBEParameterTemplate); + if (dummy == NULL) { + break; + } + dummy = NULL; + rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.keyParams, + SEC_OID_PKCS5_PBKDF2, &der_param); + if (rv != SECSuccess) { + break; + } + der_param.data = pbe_param->ivData; + der_param.len = pbe_param->ivLen; + rv = SECOID_SetAlgorithmID(arena, &pkcs5v2_param.algParams, + pbe_param->encAlg, pbe_param->ivLen ? &der_param : NULL); + if (rv != SECSuccess) { + break; + } + dummy = SEC_ASN1EncodeItem(arena, &der_param, &pkcs5v2_param, + NSSPKCS5V2PBES2ParameterTemplate); + break; + default: + break; } if (dummy == NULL) { - goto loser; + goto loser; } - + rv = SECOID_SetAlgorithmID(arena, algid, algorithm, &der_param); if (rv != SECSuccess) { - goto loser; + goto loser; } ret_algid = (SECAlgorithmID *)PORT_ZAlloc(sizeof(SECAlgorithmID)); if (ret_algid == NULL) { - goto loser; + goto loser; } rv = SECOID_CopyAlgorithmID(NULL, ret_algid, algid); if (rv != SECSuccess) { - SECOID_DestroyAlgorithmID(ret_algid, PR_TRUE); - ret_algid = NULL; + SECOID_DestroyAlgorithmID(ret_algid, PR_TRUE); + ret_algid = NULL; } -loser: +loser: return ret_algid; } diff --git a/nss/lib/softoken/lowpbe.h b/nss/lib/softoken/lowpbe.h index 00c1007..2080138 100644 --- a/nss/lib/softoken/lowpbe.h +++ b/nss/lib/softoken/lowpbe.h @@ -11,9 +11,9 @@ #include "secoidt.h" #include "hasht.h" -typedef SECItem * (* SEC_PKCS5GetPBEPassword)(void *arg); +typedef SECItem *(*SEC_PKCS5GetPBEPassword)(void *arg); -/* used for V2 PKCS 12 Draft Spec */ +/* used for V2 PKCS 12 Draft Spec */ typedef enum { pbeBitGenIDNull = 0, pbeBitGenCipherKey = 0x01, @@ -31,37 +31,36 @@ typedef struct NSSPKCS5PBEParameterStr NSSPKCS5PBEParameter; struct NSSPKCS5PBEParameterStr { PLArenaPool *poolp; - SECItem salt; /* octet string */ - SECItem iteration; /* integer */ - SECItem keyLength; /* integer */ + SECItem salt; /* octet string */ + SECItem iteration; /* integer */ + SECItem keyLength; /* integer */ /* used locally */ - int iter; - int keyLen; - int ivLen; + int iter; + int keyLen; + int ivLen; unsigned char *ivData; HASH_HashType hashType; NSSPKCS5PBEType pbeType; - SECAlgorithmID prfAlg; - PBEBitGenID keyID; - SECOidTag encAlg; - PRBool is2KeyDES; + SECAlgorithmID prfAlg; + PBEBitGenID keyID; + SECOidTag encAlg; + PRBool is2KeyDES; }; - SEC_BEGIN_PROTOS /* Create a PKCS5 Algorithm ID * The algorithm ID is set up using the PKCS #5 parameter structure * algorithm is the PBE algorithm ID for the desired algorithm - * pbe is a pbe param block with all the info needed to create the + * pbe is a pbe param block with all the info needed to create the * algorithm id. - * If an error occurs or the algorithm specified is not supported + * If an error occurs or the algorithm specified is not supported * or is not a password based encryption algorithm, NULL is returned. * Otherwise, a pointer to the algorithm id is returned. */ extern SECAlgorithmID * nsspkcs5_CreateAlgorithmID(PLArenaPool *arena, SECOidTag algorithm, - NSSPKCS5PBEParameter *pbe); + NSSPKCS5PBEParameter *pbe); /* * Convert an Algorithm ID to a PBE Param. @@ -77,10 +76,10 @@ nsspkcs5_AlgidToParam(SECAlgorithmID *algid); * keyDB which only support PKCS 5 v1, PFX, and PKCS 12. */ NSSPKCS5PBEParameter * -nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator); - +nsspkcs5_NewParam(SECOidTag alg, HASH_HashType hashType, SECItem *salt, + int iterationCount); -/* Encrypt/Decrypt data using password based encryption. +/* Encrypt/Decrypt data using password based encryption. * algid is the PBE algorithm identifier, * pwitem is the password, * src is the source for encryption/decryption, @@ -91,11 +90,11 @@ nsspkcs5_NewParam(SECOidTag alg, SECItem *salt, int iterator); */ extern SECItem * nsspkcs5_CipherData(NSSPKCS5PBEParameter *, SECItem *pwitem, - SECItem *src, PRBool encrypt, PRBool *update); + SECItem *src, PRBool encrypt, PRBool *update); extern SECItem * nsspkcs5_ComputeKeyAndIV(NSSPKCS5PBEParameter *, SECItem *pwitem, - SECItem *iv, PRBool faulty3DES); + SECItem *iv, PRBool faulty3DES); /* Destroys PBE parameter */ extern void diff --git a/nss/lib/softoken/manifest.mn b/nss/lib/softoken/manifest.mn index 2f43bb3..256d443 100644 --- a/nss/lib/softoken/manifest.mn +++ b/nss/lib/softoken/manifest.mn @@ -1,4 +1,4 @@ -# +# # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. @@ -18,12 +18,12 @@ INCLUDES += -I$(SQLITE_INCLUDE_DIR) endif EXPORTS = \ + lowkeyi.h \ + lowkeyti.h \ $(NULL) PRIVATE_EXPORTS = \ lgglue.h \ - lowkeyi.h \ - lowkeyti.h \ pkcs11ni.h \ softoken.h \ softoknt.h \ diff --git a/nss/lib/softoken/padbuf.c b/nss/lib/softoken/padbuf.c index 1f030b8..6e897f2 100644 --- a/nss/lib/softoken/padbuf.c +++ b/nss/lib/softoken/padbuf.c @@ -6,7 +6,7 @@ #include "secerr.h" /* - * Prepare a buffer for any padded CBC encryption algorithm, growing to the + * Prepare a buffer for any padded CBC encryption algorithm, growing to the * appropriate boundary and filling with the appropriate padding. * blockSize must be a power of 2. * @@ -15,12 +15,12 @@ */ unsigned char * CBC_PadBuffer(PLArenaPool *arena, unsigned char *inbuf, unsigned int inlen, - unsigned int *outlen, int blockSize) + unsigned int *outlen, int blockSize) { unsigned char *outbuf; - unsigned int des_len; - unsigned int i; - unsigned char des_pad_len; + unsigned int des_len; + unsigned int i; + unsigned char des_pad_len; /* * We need from 1 to blockSize bytes -- we *always* grow. @@ -30,19 +30,19 @@ CBC_PadBuffer(PLArenaPool *arena, unsigned char *inbuf, unsigned int inlen, des_len = (inlen + blockSize) & ~(blockSize - 1); if (arena != NULL) { - outbuf = (unsigned char*)PORT_ArenaGrow (arena, inbuf, inlen, des_len); + outbuf = (unsigned char *)PORT_ArenaGrow(arena, inbuf, inlen, des_len); } else { - outbuf = (unsigned char*)PORT_Realloc (inbuf, des_len); + outbuf = (unsigned char *)PORT_Realloc(inbuf, des_len); } if (outbuf == NULL) { - PORT_SetError (SEC_ERROR_NO_MEMORY); - return NULL; + PORT_SetError(SEC_ERROR_NO_MEMORY); + return NULL; } des_pad_len = des_len - inlen; for (i = inlen; i < des_len; i++) - outbuf[i] = des_pad_len; + outbuf[i] = des_pad_len; *outlen = des_len; return outbuf; diff --git a/nss/lib/softoken/pkcs11.c b/nss/lib/softoken/pkcs11.c index 97d6d3f..77212f7 100644 --- a/nss/lib/softoken/pkcs11.c +++ b/nss/lib/softoken/pkcs11.c @@ -6,11 +6,11 @@ * * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does + * slot 1 is our generic crypto support. It does not require login. + * It supports Public Key ops, and all they bulk ciphers and hashes. + * It can also support Private Key ops for imported Private keys. It does * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It + * slot 2 is our private key support. It requires a login before use. It * can store Private Keys and Certs as token objects. Currently only private * keys and their associated Certificates are saved on the token. * @@ -32,7 +32,7 @@ #include "softkver.h" #include "secoid.h" #include "sftkdb.h" -#include "utilpars.h" +#include "utilpars.h" #include "ec.h" #include "secasn1.h" #include "secerr.h" @@ -65,9 +65,9 @@ PRBool usePthread_atfork; */ /* The next three strings must be exactly 32 characters long */ -static char *manufacturerID = "Mozilla Foundation "; +static char *manufacturerID = "Mozilla Foundation "; static char manufacturerID_space[33]; -static char *libraryDescription = "NSS Internal Crypto Services "; +static char *libraryDescription = "NSS Internal Crypto Services "; static char libraryDescription_space[33]; /* @@ -75,48 +75,46 @@ static char libraryDescription_space[33]; * failure so that there are at most 60 login attempts per minute. */ static PRIntervalTime loginWaitTime; -static PRUint32 minSessionObjectHandle = 1U; +static PRUint32 minSessionObjectHandle = 1U; -#define __PASTE(x,y) x##y +#define __PASTE(x, y) x##y /* * we renamed all our internal functions, get the correct * definitions for them... - */ + */ #undef CK_PKCS11_FUNCTION_INFO #undef CK_NEED_ARG_LIST #define CK_EXTERN extern #define CK_PKCS11_FUNCTION_INFO(func) \ - CK_RV __PASTE(NS,func) -#define CK_NEED_ARG_LIST 1 - + CK_RV __PASTE(NS, func) +#define CK_NEED_ARG_LIST 1 + #include "pkcs11f.h" - - - + /* build the crypto module table */ static const CK_FUNCTION_LIST sftk_funcList = { { 1, 10 }, - + #undef CK_PKCS11_FUNCTION_INFO #undef CK_NEED_ARG_LIST - + #define CK_PKCS11_FUNCTION_INFO(func) \ - __PASTE(NS,func), + __PASTE(NS, func) \ + , #include "pkcs11f.h" - + }; - + #undef CK_PKCS11_FUNCTION_INFO #undef CK_NEED_ARG_LIST - - + #undef __PASTE -/* List of DES Weak Keys */ +/* List of DES Weak Keys */ typedef unsigned char desKey[8]; -static const desKey sftk_desWeakTable[] = { +static const desKey sftk_desWeakTable[] = { #ifdef noParity /* weak */ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, @@ -164,57 +162,56 @@ static const desKey sftk_desWeakTable[] = { { 0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e }, { 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01 }, - { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe }, + { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe }, { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1 } #endif }; - -static const int sftk_desWeakTableSize = sizeof(sftk_desWeakTable)/ - sizeof(sftk_desWeakTable[0]); +static const int sftk_desWeakTableSize = sizeof(sftk_desWeakTable) / + sizeof(sftk_desWeakTable[0]); /* DES KEY Parity conversion table. Takes each byte/2 as an index, returns * that byte with the proper parity bit set */ static const unsigned char parityTable[256] = { -/* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */ -/* E */ 0x01,0x02,0x04,0x07,0x08,0x0b,0x0d,0x0e, -/* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */ -/* O */ 0x10,0x13,0x15,0x16,0x19,0x1a,0x1c,0x1f, -/* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */ -/* O */ 0x20,0x23,0x25,0x26,0x29,0x2a,0x2c,0x2f, -/* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */ -/* E */ 0x31,0x32,0x34,0x37,0x38,0x3b,0x3d,0x3e, -/* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */ -/* O */ 0x40,0x43,0x45,0x46,0x49,0x4a,0x4c,0x4f, -/* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */ -/* E */ 0x51,0x52,0x54,0x57,0x58,0x5b,0x5d,0x5e, -/* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */ -/* E */ 0x61,0x62,0x64,0x67,0x68,0x6b,0x6d,0x6e, -/* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */ -/* O */ 0x70,0x73,0x75,0x76,0x79,0x7a,0x7c,0x7f, -/* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */ -/* O */ 0x80,0x83,0x85,0x86,0x89,0x8a,0x8c,0x8f, -/* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */ -/* E */ 0x91,0x92,0x94,0x97,0x98,0x9b,0x9d,0x9e, -/* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */ -/* E */ 0xa1,0xa2,0xa4,0xa7,0xa8,0xab,0xad,0xae, -/* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */ -/* O */ 0xb0,0xb3,0xb5,0xb6,0xb9,0xba,0xbc,0xbf, -/* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */ -/* E */ 0xc1,0xc2,0xc4,0xc7,0xc8,0xcb,0xcd,0xce, -/* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */ -/* O */ 0xd0,0xd3,0xd5,0xd6,0xd9,0xda,0xdc,0xdf, -/* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */ -/* O */ 0xe0,0xe3,0xe5,0xe6,0xe9,0xea,0xec,0xef, -/* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */ -/* E */ 0xf1,0xf2,0xf4,0xf7,0xf8,0xfb,0xfd,0xfe, + /* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */ + /* E */ 0x01, 0x02, 0x04, 0x07, 0x08, 0x0b, 0x0d, 0x0e, + /* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */ + /* O */ 0x10, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c, 0x1f, + /* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */ + /* O */ 0x20, 0x23, 0x25, 0x26, 0x29, 0x2a, 0x2c, 0x2f, + /* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */ + /* E */ 0x31, 0x32, 0x34, 0x37, 0x38, 0x3b, 0x3d, 0x3e, + /* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */ + /* O */ 0x40, 0x43, 0x45, 0x46, 0x49, 0x4a, 0x4c, 0x4f, + /* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */ + /* E */ 0x51, 0x52, 0x54, 0x57, 0x58, 0x5b, 0x5d, 0x5e, + /* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */ + /* E */ 0x61, 0x62, 0x64, 0x67, 0x68, 0x6b, 0x6d, 0x6e, + /* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */ + /* O */ 0x70, 0x73, 0x75, 0x76, 0x79, 0x7a, 0x7c, 0x7f, + /* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */ + /* O */ 0x80, 0x83, 0x85, 0x86, 0x89, 0x8a, 0x8c, 0x8f, + /* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */ + /* E */ 0x91, 0x92, 0x94, 0x97, 0x98, 0x9b, 0x9d, 0x9e, + /* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */ + /* E */ 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xab, 0xad, 0xae, + /* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */ + /* O */ 0xb0, 0xb3, 0xb5, 0xb6, 0xb9, 0xba, 0xbc, 0xbf, + /* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */ + /* E */ 0xc1, 0xc2, 0xc4, 0xc7, 0xc8, 0xcb, 0xcd, 0xce, + /* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */ + /* O */ 0xd0, 0xd3, 0xd5, 0xd6, 0xd9, 0xda, 0xdc, 0xdf, + /* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */ + /* O */ 0xe0, 0xe3, 0xe5, 0xe6, 0xe9, 0xea, 0xec, 0xef, + /* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */ + /* E */ 0xf1, 0xf2, 0xf4, 0xf7, 0xf8, 0xfb, 0xfd, 0xfe, }; /* Mechanisms */ struct mechanismList { - CK_MECHANISM_TYPE type; - CK_MECHANISM_INFO info; - PRBool privkey; + CK_MECHANISM_TYPE type; + CK_MECHANISM_INFO info; + PRBool privkey; }; /* @@ -222,24 +219,24 @@ struct mechanismList { * PKCS #11 version 2.01. Those Mechanisms not supported by this PKCS #11 * module are ifdef'ed out. */ -#define CKF_EN_DE CKF_ENCRYPT | CKF_DECRYPT -#define CKF_WR_UN CKF_WRAP | CKF_UNWRAP -#define CKF_SN_VR CKF_SIGN | CKF_VERIFY -#define CKF_SN_RE CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER +#define CKF_EN_DE CKF_ENCRYPT | CKF_DECRYPT +#define CKF_WR_UN CKF_WRAP | CKF_UNWRAP +#define CKF_SN_VR CKF_SIGN | CKF_VERIFY +#define CKF_SN_RE CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER -#define CKF_EN_DE_WR_UN CKF_EN_DE | CKF_WR_UN -#define CKF_SN_VR_RE CKF_SN_VR | CKF_SN_RE -#define CKF_DUZ_IT_ALL CKF_EN_DE_WR_UN | CKF_SN_VR_RE +#define CKF_EN_DE_WR_UN CKF_EN_DE | CKF_WR_UN +#define CKF_SN_VR_RE CKF_SN_VR | CKF_SN_RE +#define CKF_DUZ_IT_ALL CKF_EN_DE_WR_UN | CKF_SN_VR_RE -#define CKF_EC_PNU CKF_EC_FP | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS +#define CKF_EC_PNU CKF_EC_FP | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS -#define CKF_EC_BPNU CKF_EC_F_2M | CKF_EC_PNU +#define CKF_EC_BPNU CKF_EC_F_2M | CKF_EC_PNU #define CK_MAX 0xffffffff static const struct mechanismList mechanisms[] = { - /* + /* * PKCS #11 Mechanism List. * * The first argument is the PKCS #11 Mechanism we support. @@ -253,269 +250,257 @@ static const struct mechanismList mechanisms[] = { * in bytes for RC5, AES, Camellia, and CAST* * ignored for DES*, IDEA and FORTEZZA based * Flags - * What operations are supported by this mechanism. - * The third argument is a bool which tells if this mechanism is + * What operations are supported by this mechanism. + * The third argument is a bool which tells if this mechanism is * supported in the database token. * */ - /* ------------------------- RSA Operations ---------------------------*/ - {CKM_RSA_PKCS_KEY_PAIR_GEN,{RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_GENERATE_KEY_PAIR},PR_TRUE}, - {CKM_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, - {CKM_RSA_PKCS_PSS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_RSA_PKCS_OAEP, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_EN_DE_WR_UN}, PR_TRUE}, + /* ------------------------- RSA Operations ---------------------------*/ + { CKM_RSA_PKCS_KEY_PAIR_GEN, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_GENERATE_KEY_PAIR }, PR_TRUE }, + { CKM_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE }, + { CKM_RSA_PKCS_PSS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_RSA_PKCS_OAEP, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_EN_DE_WR_UN }, PR_TRUE }, #ifdef SFTK_RSA9796_SUPPORTED - {CKM_RSA_9796, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, + { CKM_RSA_9796, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE }, #endif - {CKM_RSA_X_509, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_DUZ_IT_ALL}, PR_TRUE}, - /* -------------- RSA Multipart Signing Operations -------------------- */ - {CKM_MD2_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_MD5_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA1_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA224_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512_RSA_PKCS, {RSA_MIN_MODULUS_BITS,CK_MAX, - CKF_SN_VR}, PR_TRUE}, - /* ------------------------- DSA Operations --------------------------- */ - {CKM_DSA_KEY_PAIR_GEN, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_GENERATE_KEY_PAIR}, PR_TRUE}, - {CKM_DSA, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_SN_VR}, PR_TRUE}, - {CKM_DSA_PARAMETER_GEN, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_GENERATE}, PR_TRUE}, - {CKM_DSA_SHA1, {DSA_MIN_P_BITS, DSA_MAX_P_BITS, - CKF_SN_VR}, PR_TRUE}, - /* -------------------- Diffie Hellman Operations --------------------- */ - /* no diffie hellman yet */ - {CKM_DH_PKCS_KEY_PAIR_GEN, {DH_MIN_P_BITS, DH_MAX_P_BITS, - CKF_GENERATE_KEY_PAIR}, PR_TRUE}, - {CKM_DH_PKCS_DERIVE, {DH_MIN_P_BITS, DH_MAX_P_BITS, - CKF_DERIVE}, PR_TRUE}, + { CKM_RSA_X_509, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_DUZ_IT_ALL }, PR_TRUE }, + /* -------------- RSA Multipart Signing Operations -------------------- */ + { CKM_MD2_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_MD5_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA1_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA224_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA256_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA384_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA512_RSA_PKCS, { RSA_MIN_MODULUS_BITS, CK_MAX, CKF_SN_VR }, PR_TRUE }, + /* ------------------------- DSA Operations --------------------------- */ + { CKM_DSA_KEY_PAIR_GEN, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE }, + { CKM_DSA, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE }, + { CKM_DSA_PARAMETER_GEN, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_GENERATE }, PR_TRUE }, + { CKM_DSA_SHA1, { DSA_MIN_P_BITS, DSA_MAX_P_BITS, CKF_SN_VR }, PR_TRUE }, + /* -------------------- Diffie Hellman Operations --------------------- */ + /* no diffie hellman yet */ + { CKM_DH_PKCS_KEY_PAIR_GEN, { DH_MIN_P_BITS, DH_MAX_P_BITS, CKF_GENERATE_KEY_PAIR }, PR_TRUE }, + { CKM_DH_PKCS_DERIVE, { DH_MIN_P_BITS, DH_MAX_P_BITS, CKF_DERIVE }, PR_TRUE }, #ifndef NSS_DISABLE_ECC - /* -------------------- Elliptic Curve Operations --------------------- */ - {CKM_EC_KEY_PAIR_GEN, {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, - CKF_GENERATE_KEY_PAIR|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDH1_DERIVE, {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, - CKF_DERIVE|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDSA, {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, - CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, - {CKM_ECDSA_SHA1, {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, - CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, + /* -------------------- Elliptic Curve Operations --------------------- */ + { CKM_EC_KEY_PAIR_GEN, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_GENERATE_KEY_PAIR | CKF_EC_BPNU }, PR_TRUE }, + { CKM_ECDH1_DERIVE, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_DERIVE | CKF_EC_BPNU }, PR_TRUE }, + { CKM_ECDSA, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE }, + { CKM_ECDSA_SHA1, { EC_MIN_KEY_BITS, EC_MAX_KEY_BITS, CKF_SN_VR | CKF_EC_BPNU }, PR_TRUE }, #endif /* NSS_DISABLE_ECC */ - /* ------------------------- RC2 Operations --------------------------- */ - {CKM_RC2_KEY_GEN, {1, 128, CKF_GENERATE}, PR_TRUE}, - {CKM_RC2_ECB, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC2_CBC, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC2_MAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_RC2_MAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_RC2_CBC_PAD, {1, 128, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- RC4 Operations --------------------------- */ - {CKM_RC4_KEY_GEN, {1, 256, CKF_GENERATE}, PR_FALSE}, - {CKM_RC4, {1, 256, CKF_EN_DE_WR_UN}, PR_FALSE}, - /* ------------------------- DES Operations --------------------------- */ - {CKM_DES_KEY_GEN, { 8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_DES_ECB, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES_CBC, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES_MAC, { 8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_DES_MAC_GENERAL, { 8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_DES_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_DES2_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE}, - {CKM_DES3_KEY_GEN, {24, 24, CKF_GENERATE}, PR_TRUE }, - {CKM_DES3_ECB, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - {CKM_DES3_CBC, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - {CKM_DES3_MAC, {24, 24, CKF_SN_VR}, PR_TRUE }, - {CKM_DES3_MAC_GENERAL, {24, 24, CKF_SN_VR}, PR_TRUE }, - {CKM_DES3_CBC_PAD, {24, 24, CKF_EN_DE_WR_UN}, PR_TRUE }, - /* ------------------------- CDMF Operations --------------------------- */ - {CKM_CDMF_KEY_GEN, {8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_CDMF_ECB, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CDMF_CBC, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CDMF_MAC, {8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CDMF_MAC_GENERAL, {8, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CDMF_CBC_PAD, {8, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- AES Operations --------------------------- */ - {CKM_AES_KEY_GEN, {16, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_AES_ECB, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_AES_CBC, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_AES_MAC, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_AES_MAC_GENERAL, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_AES_CBC_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_AES_CTS, {16, 32, CKF_EN_DE}, PR_TRUE}, - {CKM_AES_CTR, {16, 32, CKF_EN_DE}, PR_TRUE}, - {CKM_AES_GCM, {16, 32, CKF_EN_DE}, PR_TRUE}, - /* ------------------------- Camellia Operations --------------------- */ - {CKM_CAMELLIA_KEY_GEN, {16, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_CAMELLIA_ECB, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAMELLIA_CBC, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAMELLIA_MAC, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_CAMELLIA_MAC_GENERAL, {16, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_CAMELLIA_CBC_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- SEED Operations --------------------------- */ - {CKM_SEED_KEY_GEN, {16, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_SEED_ECB, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_SEED_CBC, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_SEED_MAC, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_SEED_MAC_GENERAL, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_SEED_CBC_PAD, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* ------------------------- Hashing Operations ----------------------- */ - {CKM_MD2, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_MD2_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD2_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD5, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_MD5_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_MD5_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA_1, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA_1_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA_1_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA224, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA224_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA224_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA256_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA256_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA384_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA384_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512, {0, 0, CKF_DIGEST}, PR_FALSE}, - {CKM_SHA512_HMAC, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_SHA512_HMAC_GENERAL, {1, 128, CKF_SN_VR}, PR_TRUE}, - {CKM_TLS_PRF_GENERAL, {0, 512, CKF_SN_VR}, PR_FALSE}, - {CKM_TLS_MAC, {0, 512, CKF_SN_VR}, PR_FALSE}, - {CKM_NSS_TLS_PRF_GENERAL_SHA256, - {0, 512, CKF_SN_VR}, PR_FALSE}, - /* ------------------------- HKDF Operations -------------------------- */ - {CKM_NSS_HKDF_SHA1, {1, 128, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_HKDF_SHA256, {1, 128, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_HKDF_SHA384, {1, 128, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_HKDF_SHA512, {1, 128, CKF_DERIVE}, PR_TRUE}, - /* ------------------------- CAST Operations --------------------------- */ + /* ------------------------- RC2 Operations --------------------------- */ + { CKM_RC2_KEY_GEN, { 1, 128, CKF_GENERATE }, PR_TRUE }, + { CKM_RC2_ECB, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_RC2_CBC, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_RC2_MAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_RC2_MAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_RC2_CBC_PAD, { 1, 128, CKF_EN_DE_WR_UN }, PR_TRUE }, + /* ------------------------- RC4 Operations --------------------------- */ + { CKM_RC4_KEY_GEN, { 1, 256, CKF_GENERATE }, PR_FALSE }, + { CKM_RC4, { 1, 256, CKF_EN_DE_WR_UN }, PR_FALSE }, + /* ------------------------- DES Operations --------------------------- */ + { CKM_DES_KEY_GEN, { 8, 8, CKF_GENERATE }, PR_TRUE }, + { CKM_DES_ECB, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_DES_CBC, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_DES_MAC, { 8, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_DES_MAC_GENERAL, { 8, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_DES_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_DES2_KEY_GEN, { 24, 24, CKF_GENERATE }, PR_TRUE }, + { CKM_DES3_KEY_GEN, { 24, 24, CKF_GENERATE }, PR_TRUE }, + { CKM_DES3_ECB, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_DES3_CBC, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_DES3_MAC, { 24, 24, CKF_SN_VR }, PR_TRUE }, + { CKM_DES3_MAC_GENERAL, { 24, 24, CKF_SN_VR }, PR_TRUE }, + { CKM_DES3_CBC_PAD, { 24, 24, CKF_EN_DE_WR_UN }, PR_TRUE }, + /* ------------------------- CDMF Operations --------------------------- */ + { CKM_CDMF_KEY_GEN, { 8, 8, CKF_GENERATE }, PR_TRUE }, + { CKM_CDMF_ECB, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CDMF_CBC, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CDMF_MAC, { 8, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_CDMF_MAC_GENERAL, { 8, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_CDMF_CBC_PAD, { 8, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + /* ------------------------- AES Operations --------------------------- */ + { CKM_AES_KEY_GEN, { 16, 32, CKF_GENERATE }, PR_TRUE }, + { CKM_AES_ECB, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_AES_CBC, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_AES_MAC, { 16, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_AES_MAC_GENERAL, { 16, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_AES_CBC_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_AES_CTS, { 16, 32, CKF_EN_DE }, PR_TRUE }, + { CKM_AES_CTR, { 16, 32, CKF_EN_DE }, PR_TRUE }, + { CKM_AES_GCM, { 16, 32, CKF_EN_DE }, PR_TRUE }, + /* ------------------------- Camellia Operations --------------------- */ + { CKM_CAMELLIA_KEY_GEN, { 16, 32, CKF_GENERATE }, PR_TRUE }, + { CKM_CAMELLIA_ECB, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAMELLIA_CBC, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAMELLIA_MAC, { 16, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_CAMELLIA_MAC_GENERAL, { 16, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_CAMELLIA_CBC_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + /* ------------------------- SEED Operations --------------------------- */ + { CKM_SEED_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE }, + { CKM_SEED_ECB, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_SEED_CBC, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_SEED_MAC, { 16, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_SEED_MAC_GENERAL, { 16, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_SEED_CBC_PAD, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, +#ifndef NSS_DISABLE_CHACHAPOLY + /* ------------------------- ChaCha20 Operations ---------------------- */ + { CKM_NSS_CHACHA20_KEY_GEN, { 32, 32, CKF_GENERATE }, PR_TRUE }, + { CKM_NSS_CHACHA20_POLY1305, { 32, 32, CKF_EN_DE }, PR_TRUE }, +#endif /* NSS_DISABLE_CHACHAPOLY */ + /* ------------------------- Hashing Operations ----------------------- */ + { CKM_MD2, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_MD2_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_MD2_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_MD5, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_MD5_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_MD5_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA_1, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_SHA_1_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA_1_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA224, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_SHA224_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA224_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA256, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_SHA256_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA256_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA384, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_SHA384_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA384_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA512, { 0, 0, CKF_DIGEST }, PR_FALSE }, + { CKM_SHA512_HMAC, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_SHA512_HMAC_GENERAL, { 1, 128, CKF_SN_VR }, PR_TRUE }, + { CKM_TLS_PRF_GENERAL, { 0, 512, CKF_SN_VR }, PR_FALSE }, + { CKM_TLS_MAC, { 0, 512, CKF_SN_VR }, PR_FALSE }, + { CKM_NSS_TLS_PRF_GENERAL_SHA256, + { 0, 512, CKF_SN_VR }, + PR_FALSE }, + /* ------------------------- HKDF Operations -------------------------- */ + { CKM_NSS_HKDF_SHA1, { 1, 128, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_HKDF_SHA256, { 1, 128, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_HKDF_SHA384, { 1, 128, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_HKDF_SHA512, { 1, 128, CKF_DERIVE }, PR_TRUE }, +/* ------------------------- CAST Operations --------------------------- */ #ifdef NSS_SOFTOKEN_DOES_CAST - /* Cast operations are not supported ( yet? ) */ - {CKM_CAST_KEY_GEN, {1, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST_ECB, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST_CBC, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST_MAC, {1, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST_MAC_GENERAL, {1, 8, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST_CBC_PAD, {1, 8, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST3_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST3_MAC, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST3_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST3_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_KEY_GEN, {1, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_CAST5_ECB, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_CBC, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_CAST5_MAC, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST5_MAC_GENERAL, {1, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_CAST5_CBC_PAD, {1, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, + /* Cast operations are not supported ( yet? ) */ + { CKM_CAST_KEY_GEN, { 1, 8, CKF_GENERATE }, PR_TRUE }, + { CKM_CAST_ECB, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST_CBC, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST_MAC, { 1, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST_MAC_GENERAL, { 1, 8, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST_CBC_PAD, { 1, 8, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST3_KEY_GEN, { 1, 16, CKF_GENERATE }, PR_TRUE }, + { CKM_CAST3_ECB, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST3_CBC, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST3_MAC, { 1, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST3_MAC_GENERAL, { 1, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST3_CBC_PAD, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST5_KEY_GEN, { 1, 16, CKF_GENERATE }, PR_TRUE }, + { CKM_CAST5_ECB, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST5_CBC, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_CAST5_MAC, { 1, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST5_MAC_GENERAL, { 1, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_CAST5_CBC_PAD, { 1, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, #endif #if NSS_SOFTOKEN_DOES_RC5 - /* ------------------------- RC5 Operations --------------------------- */ - {CKM_RC5_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_RC5_ECB, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC5_CBC, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_RC5_MAC, {1, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_RC5_MAC_GENERAL, {1, 32, CKF_SN_VR}, PR_TRUE}, - {CKM_RC5_CBC_PAD, {1, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, + /* ------------------------- RC5 Operations --------------------------- */ + { CKM_RC5_KEY_GEN, { 1, 32, CKF_GENERATE }, PR_TRUE }, + { CKM_RC5_ECB, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_RC5_CBC, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_RC5_MAC, { 1, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_RC5_MAC_GENERAL, { 1, 32, CKF_SN_VR }, PR_TRUE }, + { CKM_RC5_CBC_PAD, { 1, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, #endif #ifdef NSS_SOFTOKEN_DOES_IDEA - /* ------------------------- IDEA Operations -------------------------- */ - {CKM_IDEA_KEY_GEN, {16, 16, CKF_GENERATE}, PR_TRUE}, - {CKM_IDEA_ECB, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_IDEA_CBC, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_IDEA_MAC, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_IDEA_MAC_GENERAL, {16, 16, CKF_SN_VR}, PR_TRUE}, - {CKM_IDEA_CBC_PAD, {16, 16, CKF_EN_DE_WR_UN}, PR_TRUE}, + /* ------------------------- IDEA Operations -------------------------- */ + { CKM_IDEA_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE }, + { CKM_IDEA_ECB, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_IDEA_CBC, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_IDEA_MAC, { 16, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_IDEA_MAC_GENERAL, { 16, 16, CKF_SN_VR }, PR_TRUE }, + { CKM_IDEA_CBC_PAD, { 16, 16, CKF_EN_DE_WR_UN }, PR_TRUE }, #endif - /* --------------------- Secret Key Operations ------------------------ */ - {CKM_GENERIC_SECRET_KEY_GEN, {1, 32, CKF_GENERATE}, PR_TRUE}, - {CKM_CONCATENATE_BASE_AND_KEY, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_CONCATENATE_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_CONCATENATE_DATA_AND_BASE, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_XOR_BASE_AND_DATA, {1, 32, CKF_GENERATE}, PR_FALSE}, - {CKM_EXTRACT_KEY_FROM_KEY, {1, 32, CKF_DERIVE}, PR_FALSE}, - /* ---------------------- SSL Key Derivations ------------------------- */ - {CKM_SSL3_PRE_MASTER_KEY_GEN, {48, 48, CKF_GENERATE}, PR_FALSE}, - {CKM_SSL3_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_MD5_MAC, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_SSL3_SHA1_MAC, { 0, 20, CKF_DERIVE}, PR_FALSE}, - {CKM_MD5_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_MD2_KEY_DERIVATION, { 0, 16, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA1_KEY_DERIVATION, { 0, 20, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA224_KEY_DERIVATION, { 0, 28, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA256_KEY_DERIVATION, { 0, 32, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA384_KEY_DERIVATION, { 0, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_SHA512_KEY_DERIVATION, { 0, 64, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS12_MASTER_KEY_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256, - {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS12_MASTER_KEY_DERIVE_DH, {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256, - {8, 128, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_TLS12_KEY_AND_MAC_DERIVE, {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256, - {48, 48, CKF_DERIVE}, PR_FALSE}, - {CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE, - {48,128, CKF_DERIVE}, PR_FALSE}, - {CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH, - {48,128, CKF_DERIVE}, PR_FALSE}, - /* ---------------------- PBE Key Derivations ------------------------ */ - {CKM_PBE_MD2_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE}, - {CKM_PBE_MD5_DES_CBC, {8, 8, CKF_DERIVE}, PR_TRUE}, - /* ------------------ NETSCAPE PBE Key Derivations ------------------- */ - {CKM_NETSCAPE_PBE_SHA1_DES_CBC, { 8, 8, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_DES3_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_DES2_EDE_CBC, {24,24, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC2_40_CBC, {40,40, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC2_128_CBC, {128,128, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC4_40, {40,40, CKF_GENERATE}, PR_TRUE}, - {CKM_PBE_SHA1_RC4_128, {128,128, CKF_GENERATE}, PR_TRUE}, - {CKM_PBA_SHA1_WITH_SHA1_HMAC, {20,20, CKF_GENERATE}, PR_TRUE}, - {CKM_PKCS5_PBKD2, {1,256, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN, {20,20, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE}, - {CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN, {16,16, CKF_GENERATE}, PR_TRUE}, - /* ------------------ AES Key Wrap (also encrypt) ------------------- */ - {CKM_NETSCAPE_AES_KEY_WRAP, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - {CKM_NETSCAPE_AES_KEY_WRAP_PAD, {16, 32, CKF_EN_DE_WR_UN}, PR_TRUE}, - /* --------------------------- J-PAKE -------------------------------- */ - {CKM_NSS_JPAKE_ROUND1_SHA1, {0, 0, CKF_GENERATE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND1_SHA256, {0, 0, CKF_GENERATE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND1_SHA384, {0, 0, CKF_GENERATE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND1_SHA512, {0, 0, CKF_GENERATE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND2_SHA1, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND2_SHA256, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND2_SHA384, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_ROUND2_SHA512, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_FINAL_SHA1, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_FINAL_SHA256, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_FINAL_SHA384, {0, 0, CKF_DERIVE}, PR_TRUE}, - {CKM_NSS_JPAKE_FINAL_SHA512, {0, 0, CKF_DERIVE}, PR_TRUE}, - /* -------------------- Constant Time TLS MACs ----------------------- */ - {CKM_NSS_HMAC_CONSTANT_TIME, {0, 0, CKF_DIGEST}, PR_TRUE}, - {CKM_NSS_SSL3_MAC_CONSTANT_TIME, {0, 0, CKF_DIGEST}, PR_TRUE} + /* --------------------- Secret Key Operations ------------------------ */ + { CKM_GENERIC_SECRET_KEY_GEN, { 1, 32, CKF_GENERATE }, PR_TRUE }, + { CKM_CONCATENATE_BASE_AND_KEY, { 1, 32, CKF_GENERATE }, PR_FALSE }, + { CKM_CONCATENATE_BASE_AND_DATA, { 1, 32, CKF_GENERATE }, PR_FALSE }, + { CKM_CONCATENATE_DATA_AND_BASE, { 1, 32, CKF_GENERATE }, PR_FALSE }, + { CKM_XOR_BASE_AND_DATA, { 1, 32, CKF_GENERATE }, PR_FALSE }, + { CKM_EXTRACT_KEY_FROM_KEY, { 1, 32, CKF_DERIVE }, PR_FALSE }, + /* ---------------------- SSL Key Derivations ------------------------- */ + { CKM_SSL3_PRE_MASTER_KEY_GEN, { 48, 48, CKF_GENERATE }, PR_FALSE }, + { CKM_SSL3_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_SSL3_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE }, + { CKM_SSL3_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_SSL3_MD5_MAC, { 0, 16, CKF_DERIVE }, PR_FALSE }, + { CKM_SSL3_SHA1_MAC, { 0, 20, CKF_DERIVE }, PR_FALSE }, + { CKM_MD5_KEY_DERIVATION, { 0, 16, CKF_DERIVE }, PR_FALSE }, + { CKM_MD2_KEY_DERIVATION, { 0, 16, CKF_DERIVE }, PR_FALSE }, + { CKM_SHA1_KEY_DERIVATION, { 0, 20, CKF_DERIVE }, PR_FALSE }, + { CKM_SHA224_KEY_DERIVATION, { 0, 28, CKF_DERIVE }, PR_FALSE }, + { CKM_SHA256_KEY_DERIVATION, { 0, 32, CKF_DERIVE }, PR_FALSE }, + { CKM_SHA384_KEY_DERIVATION, { 0, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_SHA512_KEY_DERIVATION, { 0, 64, CKF_DERIVE }, PR_FALSE }, + { CKM_TLS_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_TLS12_MASTER_KEY_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256, + { 48, 48, CKF_DERIVE }, + PR_FALSE }, + { CKM_TLS_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE }, + { CKM_TLS12_MASTER_KEY_DERIVE_DH, { 8, 128, CKF_DERIVE }, PR_FALSE }, + { CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256, + { 8, 128, CKF_DERIVE }, + PR_FALSE }, + { CKM_TLS_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_TLS12_KEY_AND_MAC_DERIVE, { 48, 48, CKF_DERIVE }, PR_FALSE }, + { CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256, + { 48, 48, CKF_DERIVE }, + PR_FALSE }, + { CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE, + { 48, 128, CKF_DERIVE }, + PR_FALSE }, + { CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH, + { 48, 128, CKF_DERIVE }, + PR_FALSE }, + /* ---------------------- PBE Key Derivations ------------------------ */ + { CKM_PBE_MD2_DES_CBC, { 8, 8, CKF_DERIVE }, PR_TRUE }, + { CKM_PBE_MD5_DES_CBC, { 8, 8, CKF_DERIVE }, PR_TRUE }, + /* ------------------ NETSCAPE PBE Key Derivations ------------------- */ + { CKM_NETSCAPE_PBE_SHA1_DES_CBC, { 8, 8, CKF_GENERATE }, PR_TRUE }, + { CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_DES3_EDE_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_DES2_EDE_CBC, { 24, 24, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_RC2_40_CBC, { 40, 40, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_RC2_128_CBC, { 128, 128, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_RC4_40, { 40, 40, CKF_GENERATE }, PR_TRUE }, + { CKM_PBE_SHA1_RC4_128, { 128, 128, CKF_GENERATE }, PR_TRUE }, + { CKM_PBA_SHA1_WITH_SHA1_HMAC, { 20, 20, CKF_GENERATE }, PR_TRUE }, + { CKM_PKCS5_PBKD2, { 1, 256, CKF_GENERATE }, PR_TRUE }, + { CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN, { 20, 20, CKF_GENERATE }, PR_TRUE }, + { CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE }, + { CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN, { 16, 16, CKF_GENERATE }, PR_TRUE }, + /* ------------------ AES Key Wrap (also encrypt) ------------------- */ + { CKM_NETSCAPE_AES_KEY_WRAP, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + { CKM_NETSCAPE_AES_KEY_WRAP_PAD, { 16, 32, CKF_EN_DE_WR_UN }, PR_TRUE }, + /* --------------------------- J-PAKE -------------------------------- */ + { CKM_NSS_JPAKE_ROUND1_SHA1, { 0, 0, CKF_GENERATE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND1_SHA256, { 0, 0, CKF_GENERATE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND1_SHA384, { 0, 0, CKF_GENERATE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND1_SHA512, { 0, 0, CKF_GENERATE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND2_SHA1, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND2_SHA256, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND2_SHA384, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_ROUND2_SHA512, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_FINAL_SHA1, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_FINAL_SHA256, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_FINAL_SHA384, { 0, 0, CKF_DERIVE }, PR_TRUE }, + { CKM_NSS_JPAKE_FINAL_SHA512, { 0, 0, CKF_DERIVE }, PR_TRUE }, + /* -------------------- Constant Time TLS MACs ----------------------- */ + { CKM_NSS_HMAC_CONSTANT_TIME, { 0, 0, CKF_DIGEST }, PR_TRUE }, + { CKM_NSS_SSL3_MAC_CONSTANT_TIME, { 0, 0, CKF_DIGEST }, PR_TRUE } }; -static const CK_ULONG mechanismCount = sizeof(mechanisms)/sizeof(mechanisms[0]); +static const CK_ULONG mechanismCount = sizeof(mechanisms) / sizeof(mechanisms[0]); /* sigh global so fipstokn can read it */ PRBool nsc_init = PR_FALSE; @@ -524,7 +509,8 @@ PRBool nsc_init = PR_FALSE; #include <pthread.h> -static void ForkedChild(void) +static void +ForkedChild(void) { if (nsc_init || nsf_init) { forked = PR_TRUE; @@ -534,18 +520,18 @@ static void ForkedChild(void) #endif static char * -sftk_setStringName(const char *inString, char *buffer, int buffer_length, PRBool nullTerminate) +sftk_setStringName(const char *inString, char *buffer, int buffer_length, PRBool nullTerminate) { int full_length, string_length; - full_length = nullTerminate ? buffer_length -1 : buffer_length; + full_length = nullTerminate ? buffer_length - 1 : buffer_length; string_length = PORT_Strlen(inString); - /* + /* * shorten the string, respecting utf8 encoding - * to do so, we work backward from the end + * to do so, we work backward from the end * bytes looking from the end are either: * - ascii [0x00,0x7f] - * - the [2-n]th byte of a multibyte sequence + * - the [2-n]th byte of a multibyte sequence * [0x3F,0xBF], i.e, most significant 2 bits are '10' * - the first byte of a multibyte sequence [0xC0,0xFD], * i.e, most significant 2 bits are '11' @@ -556,32 +542,32 @@ sftk_setStringName(const char *inString, char *buffer, int buffer_length, PRBo * we'll be lopping a '11' byte (the first byte of the multibyte sequence), * otherwise we're lopping off an ascii character. * - * To test for '10' bytes, we first AND it with + * To test for '10' bytes, we first AND it with * 11000000 (0xc0) so that we get 10000000 (0x80) if and only if * the byte starts with 10. We test for equality. */ - while ( string_length > full_length ) { - /* need to shorten */ - while ( string_length > 0 && - ((inString[string_length-1]&(char)0xc0) == (char)0x80)) { - /* lop off '10' byte */ - string_length--; - } - /* - * test string_length in case bad data is received - * and string consisted of all '10' bytes, - * avoiding any infinite loop + while (string_length > full_length) { + /* need to shorten */ + while (string_length > 0 && + ((inString[string_length - 1] & (char)0xc0) == (char)0x80)) { + /* lop off '10' byte */ + string_length--; + } + /* + * test string_length in case bad data is received + * and string consisted of all '10' bytes, + * avoiding any infinite loop */ - if ( string_length ) { - /* remove either '11' byte or an asci byte */ - string_length--; - } + if (string_length) { + /* remove either '11' byte or an asci byte */ + string_length--; + } } - PORT_Memset(buffer,' ',full_length); + PORT_Memset(buffer, ' ', full_length); if (nullTerminate) { - buffer[full_length] = 0; + buffer[full_length] = 0; } - PORT_Memcpy(buffer,inString,string_length); + PORT_Memcpy(buffer, inString, string_length); return buffer; } /* @@ -593,13 +579,13 @@ sftk_configure(const char *man, const char *libdes) /* make sure the internationalization was done correctly... */ if (man) { - manufacturerID = sftk_setStringName(man,manufacturerID_space, - sizeof(manufacturerID_space), PR_TRUE); + manufacturerID = sftk_setStringName(man, manufacturerID_space, + sizeof(manufacturerID_space), PR_TRUE); } if (libdes) { - libraryDescription = sftk_setStringName(libdes, - libraryDescription_space, sizeof(libraryDescription_space), - PR_TRUE); + libraryDescription = sftk_setStringName(libdes, + libraryDescription_space, sizeof(libraryDescription_space), + PR_TRUE); } return CKR_OK; @@ -616,15 +602,15 @@ static PRBool sftk_hasNullPassword(SFTKSlot *slot, SFTKDBHandle *keydb) { PRBool pwenabled; - + pwenabled = PR_FALSE; if (sftkdb_HasPasswordSet(keydb) == SECSuccess) { - PRBool tokenRemoved = PR_FALSE; - SECStatus rv = sftkdb_CheckPassword(keydb, "", &tokenRemoved); - if (tokenRemoved) { - sftk_CloseAllSessions(slot, PR_FALSE); - } - return (rv == SECSuccess); + PRBool tokenRemoved = PR_FALSE; + SECStatus rv = sftkdb_CheckPassword(keydb, "", &tokenRemoved); + if (tokenRemoved) { + sftk_CloseAllSessions(slot, PR_FALSE); + } + return (rv == SECSuccess); } return pwenabled; @@ -634,246 +620,250 @@ sftk_hasNullPassword(SFTKSlot *slot, SFTKDBHandle *keydb) * ******************** Object Creation Utilities *************************** */ - /* Make sure a given attribute exists. If it doesn't, initialize it to * value and len */ CK_RV -sftk_defaultAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len) +sftk_defaultAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len) { - if ( !sftk_hasAttribute(object, type)) { - return sftk_AddAttributeType(object,type,value,len); + if (!sftk_hasAttribute(object, type)) { + return sftk_AddAttributeType(object, type, value, len); } return CKR_OK; } /* - * check the consistancy and initialize a Data Object + * check the consistancy and initialize a Data Object */ static CK_RV -sftk_handleDataObject(SFTKSession *session,SFTKObject *object) +sftk_handleDataObject(SFTKSession *session, SFTKObject *object) { CK_RV crv; /* first reject private and token data objects */ - if (sftk_isTrue(object,CKA_PRIVATE) || sftk_isTrue(object,CKA_TOKEN)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (sftk_isTrue(object, CKA_PRIVATE) || sftk_isTrue(object, CKA_TOKEN)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } /* now just verify the required date fields */ - crv = sftk_defaultAttribute(object,CKA_APPLICATION,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_VALUE,NULL,0); - if (crv != CKR_OK) return crv; + crv = sftk_defaultAttribute(object, CKA_APPLICATION, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_VALUE, NULL, 0); + if (crv != CKR_OK) + return crv; return CKR_OK; } /* - * check the consistancy and initialize a Certificate Object + * check the consistancy and initialize a Certificate Object */ static CK_RV -sftk_handleCertObject(SFTKSession *session,SFTKObject *object) +sftk_handleCertObject(SFTKSession *session, SFTKObject *object) { CK_CERTIFICATE_TYPE type; SFTKAttribute *attribute; CK_RV crv; /* certificates must have a type */ - if ( !sftk_hasAttribute(object,CKA_CERTIFICATE_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_CERTIFICATE_TYPE)) { + return CKR_TEMPLATE_INCOMPLETE; } /* we can't store any certs private */ - if (sftk_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (sftk_isTrue(object, CKA_PRIVATE)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } - + /* We only support X.509 Certs for now */ - attribute = sftk_FindAttribute(object,CKA_CERTIFICATE_TYPE); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + attribute = sftk_FindAttribute(object, CKA_CERTIFICATE_TYPE); + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; type = *(CK_CERTIFICATE_TYPE *)attribute->attrib.pValue; sftk_FreeAttribute(attribute); if (type != CKC_X_509) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } /* X.509 Certificate */ /* make sure we have a cert */ - if ( !sftk_hasAttribute(object,CKA_VALUE) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_VALUE)) { + return CKR_TEMPLATE_INCOMPLETE; } /* in PKCS #11, Subject is a required field */ - if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_SUBJECT)) { + return CKR_TEMPLATE_INCOMPLETE; } /* in PKCS #11, Issuer is a required field */ - if ( !sftk_hasAttribute(object,CKA_ISSUER) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_ISSUER)) { + return CKR_TEMPLATE_INCOMPLETE; } /* in PKCS #11, Serial is a required field */ - if ( !sftk_hasAttribute(object,CKA_SERIAL_NUMBER) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_SERIAL_NUMBER)) { + return CKR_TEMPLATE_INCOMPLETE; } /* add it to the object */ object->objectInfo = NULL; - object->infoFree = (SFTKFree) NULL; - + object->infoFree = (SFTKFree)NULL; + /* now just verify the required date fields */ crv = sftk_defaultAttribute(object, CKA_ID, NULL, 0); - if (crv != CKR_OK) { return crv; } + if (crv != CKR_OK) { + return crv; + } - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *certHandle = sftk_getCertDB(slot); + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *certHandle = sftk_getCertDB(slot); - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (certHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(certHandle, object, &object->handle); - sftk_freeDB(certHandle); - return crv; + crv = sftkdb_write(certHandle, object, &object->handle); + sftk_freeDB(certHandle); + return crv; } return CKR_OK; } - + /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV -sftk_handleTrustObject(SFTKSession *session,SFTKObject *object) +sftk_handleTrustObject(SFTKSession *session, SFTKObject *object) { /* we can't store any certs private */ - if (sftk_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (sftk_isTrue(object, CKA_PRIVATE)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } /* certificates must have a type */ - if ( !sftk_hasAttribute(object,CKA_ISSUER) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_ISSUER)) { + return CKR_TEMPLATE_INCOMPLETE; } - if ( !sftk_hasAttribute(object,CKA_SERIAL_NUMBER) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_SERIAL_NUMBER)) { + return CKR_TEMPLATE_INCOMPLETE; } - if ( !sftk_hasAttribute(object,CKA_CERT_SHA1_HASH) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_CERT_SHA1_HASH)) { + return CKR_TEMPLATE_INCOMPLETE; } - if ( !sftk_hasAttribute(object,CKA_CERT_MD5_HASH) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_CERT_MD5_HASH)) { + return CKR_TEMPLATE_INCOMPLETE; } - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *certHandle = sftk_getCertDB(slot); - CK_RV crv; + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *certHandle = sftk_getCertDB(slot); + CK_RV crv; - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (certHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(certHandle, object, &object->handle); - sftk_freeDB(certHandle); - return crv; + crv = sftkdb_write(certHandle, object, &object->handle); + sftk_freeDB(certHandle); + return crv; } return CKR_OK; } /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV -sftk_handleSMimeObject(SFTKSession *session,SFTKObject *object) +sftk_handleSMimeObject(SFTKSession *session, SFTKObject *object) { /* we can't store any certs private */ - if (sftk_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (sftk_isTrue(object, CKA_PRIVATE)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } /* certificates must have a type */ - if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_SUBJECT)) { + return CKR_TEMPLATE_INCOMPLETE; } - if ( !sftk_hasAttribute(object,CKA_NETSCAPE_EMAIL) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_NETSCAPE_EMAIL)) { + return CKR_TEMPLATE_INCOMPLETE; } - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *certHandle; - CK_RV crv; + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *certHandle; + CK_RV crv; - PORT_Assert(slot); - if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; - } + PORT_Assert(slot); + if (slot == NULL) { + return CKR_SESSION_HANDLE_INVALID; + } - certHandle = sftk_getCertDB(slot); - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + certHandle = sftk_getCertDB(slot); + if (certHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(certHandle, object, &object->handle); - sftk_freeDB(certHandle); - return crv; + crv = sftkdb_write(certHandle, object, &object->handle); + sftk_freeDB(certHandle); + return crv; } return CKR_OK; } /* - * check the consistancy and initialize a Trust Object + * check the consistancy and initialize a Trust Object */ static CK_RV -sftk_handleCrlObject(SFTKSession *session,SFTKObject *object) +sftk_handleCrlObject(SFTKSession *session, SFTKObject *object) { /* we can't store any certs private */ - if (sftk_isTrue(object,CKA_PRIVATE)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if (sftk_isTrue(object, CKA_PRIVATE)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } /* certificates must have a type */ - if ( !sftk_hasAttribute(object,CKA_SUBJECT) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_SUBJECT)) { + return CKR_TEMPLATE_INCOMPLETE; } - if ( !sftk_hasAttribute(object,CKA_VALUE) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_VALUE)) { + return CKR_TEMPLATE_INCOMPLETE; } - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *certHandle = sftk_getCertDB(slot); - CK_RV crv; + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *certHandle = sftk_getCertDB(slot); + CK_RV crv; - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (certHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(certHandle, object, &object->handle); - sftk_freeDB(certHandle); - return crv; + crv = sftkdb_write(certHandle, object, &object->handle); + sftk_freeDB(certHandle); + return crv; } return CKR_OK; } /* - * check the consistancy and initialize a Public Key Object + * check the consistancy and initialize a Public Key Object */ static CK_RV sftk_handlePublicKeyObject(SFTKSession *session, SFTKObject *object, - CK_KEY_TYPE key_type) + CK_KEY_TYPE key_type) { CK_BBOOL encrypt = CK_TRUE; CK_BBOOL recover = CK_TRUE; @@ -883,138 +873,144 @@ sftk_handlePublicKeyObject(SFTKSession *session, SFTKObject *object, CK_RV crv; switch (key_type) { - case CKK_RSA: - crv = sftk_ConstrainAttribute(object, CKA_MODULUS, - RSA_MIN_MODULUS_BITS, 0, 0); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_PUBLIC_EXPONENT, 2, 0, 0); - if (crv != CKR_OK) { - return crv; - } - break; - case CKK_DSA: - crv = sftk_ConstrainAttribute(object, CKA_SUBPRIME, - DSA_MIN_Q_BITS, DSA_MAX_Q_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_PRIME, - DSA_MIN_P_BITS, DSA_MAX_P_BITS, 64); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DSA_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DSA_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; - case CKK_DH: - crv = sftk_ConstrainAttribute(object, CKA_PRIME, - DH_MIN_P_BITS, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DH_MAX_P_BITS, 0); - if (crv != CKR_OK) { - return crv; - } - verify = CK_FALSE; - derive = CK_TRUE; - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; + case CKK_RSA: + crv = sftk_ConstrainAttribute(object, CKA_MODULUS, + RSA_MIN_MODULUS_BITS, 0, 0); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_PUBLIC_EXPONENT, 2, 0, 0); + if (crv != CKR_OK) { + return crv; + } + break; + case CKK_DSA: + crv = sftk_ConstrainAttribute(object, CKA_SUBPRIME, + DSA_MIN_Q_BITS, DSA_MAX_Q_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_PRIME, + DSA_MIN_P_BITS, DSA_MAX_P_BITS, 64); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DSA_MAX_P_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DSA_MAX_P_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + encrypt = CK_FALSE; + recover = CK_FALSE; + wrap = CK_FALSE; + break; + case CKK_DH: + crv = sftk_ConstrainAttribute(object, CKA_PRIME, + DH_MIN_P_BITS, DH_MAX_P_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_BASE, 2, DH_MAX_P_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_ConstrainAttribute(object, CKA_VALUE, 2, DH_MAX_P_BITS, 0); + if (crv != CKR_OK) { + return crv; + } + verify = CK_FALSE; + derive = CK_TRUE; + encrypt = CK_FALSE; + recover = CK_FALSE; + wrap = CK_FALSE; + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !sftk_hasAttribute(object, CKA_EC_POINT)) { - return CKR_TEMPLATE_INCOMPLETE; - } - derive = CK_TRUE; /* for ECDH */ - verify = CK_TRUE; /* for ECDSA */ - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; + case CKK_EC: + if (!sftk_hasAttribute(object, CKA_EC_PARAMS)) { + return CKR_TEMPLATE_INCOMPLETE; + } + if (!sftk_hasAttribute(object, CKA_EC_POINT)) { + return CKR_TEMPLATE_INCOMPLETE; + } + derive = CK_TRUE; /* for ECDH */ + verify = CK_TRUE; /* for ECDSA */ + encrypt = CK_FALSE; + recover = CK_FALSE; + wrap = CK_FALSE; + break; #endif /* NSS_DISABLE_ECC */ - default: - return CKR_ATTRIBUTE_VALUE_INVALID; + default: + return CKR_ATTRIBUTE_VALUE_INVALID; } /* make sure the required fields exist */ - crv = sftk_defaultAttribute(object,CKA_SUBJECT,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_ENCRYPT,&encrypt,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_VERIFY,&verify,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_VERIFY_RECOVER, - &recover,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_WRAP,&wrap,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - object->objectInfo = sftk_GetPubKey(object,key_type, &crv); + crv = sftk_defaultAttribute(object, CKA_SUBJECT, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_ENCRYPT, &encrypt, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_VERIFY, &verify, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_VERIFY_RECOVER, + &recover, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_WRAP, &wrap, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_DERIVE, &derive, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + + object->objectInfo = sftk_GetPubKey(object, key_type, &crv); if (object->objectInfo == NULL) { - return crv; + return crv; } - object->infoFree = (SFTKFree) nsslowkey_DestroyPublicKey; + object->infoFree = (SFTKFree)nsslowkey_DestroyPublicKey; /* Check that an imported EC key is valid */ if (key_type == CKK_EC) { - NSSLOWKEYPublicKey *pubKey = (NSSLOWKEYPublicKey*) object->objectInfo; - SECStatus rv = EC_ValidatePublicKey(&pubKey->u.ec.ecParams, - &pubKey->u.ec.publicValue); + NSSLOWKEYPublicKey *pubKey = (NSSLOWKEYPublicKey *)object->objectInfo; + SECStatus rv = EC_ValidatePublicKey(&pubKey->u.ec.ecParams, + &pubKey->u.ec.publicValue); - if (rv != SECSuccess) { - return CKR_TEMPLATE_INCONSISTENT; - } + if (rv != SECSuccess) { + return CKR_TEMPLATE_INCONSISTENT; + } } - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *certHandle = sftk_getCertDB(slot); + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *certHandle = sftk_getCertDB(slot); - if (certHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (certHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(certHandle, object, &object->handle); - sftk_freeDB(certHandle); - return crv; + crv = sftkdb_write(certHandle, object, &object->handle); + sftk_freeDB(certHandle); + return crv; } return CKR_OK; } -static NSSLOWKEYPrivateKey * -sftk_mkPrivKey(SFTKObject *object,CK_KEY_TYPE key, CK_RV *rvp); +static NSSLOWKEYPrivateKey * +sftk_mkPrivKey(SFTKObject *object, CK_KEY_TYPE key, CK_RV *rvp); static SECStatus sftk_verifyRSAPrivateKey(SFTKObject *object, PRBool fillIfNeeded); /* - * check the consistancy and initialize a Private Key Object + * check the consistancy and initialize a Private Key Object */ static CK_RV -sftk_handlePrivateKeyObject(SFTKSession *session,SFTKObject *object,CK_KEY_TYPE key_type) +sftk_handlePrivateKeyObject(SFTKSession *session, SFTKObject *object, CK_KEY_TYPE key_type) { CK_BBOOL cktrue = CK_TRUE; CK_BBOOL encrypt = CK_TRUE; @@ -1034,156 +1030,170 @@ sftk_handlePrivateKeyObject(SFTKSession *session,SFTKObject *object,CK_KEY_TYPE SECStatus rv; switch (key_type) { - case CKK_RSA: - if ( !sftk_hasAttribute(object, CKA_MODULUS)) { - missing_rsa_mod_component++; - } - if ( !sftk_hasAttribute(object, CKA_PUBLIC_EXPONENT)) { - missing_rsa_exp_component++; - } - if ( !sftk_hasAttribute(object, CKA_PRIVATE_EXPONENT)) { - missing_rsa_exp_component++; - } - if ( !sftk_hasAttribute(object, CKA_PRIME_1)) { - missing_rsa_mod_component++; - } - if ( !sftk_hasAttribute(object, CKA_PRIME_2)) { - missing_rsa_mod_component++; - } - if ( !sftk_hasAttribute(object, CKA_EXPONENT_1)) { - missing_rsa_crt_component++; - } - if ( !sftk_hasAttribute(object, CKA_EXPONENT_2)) { - missing_rsa_crt_component++; - } - if ( !sftk_hasAttribute(object, CKA_COEFFICIENT)) { - missing_rsa_crt_component++; - } - if (missing_rsa_mod_component || missing_rsa_exp_component || - missing_rsa_crt_component) { - /* we are missing a component, see if we have enough to rebuild - * the rest */ - int have_exp = 2- missing_rsa_exp_component; - int have_component = 5- - (missing_rsa_exp_component+missing_rsa_mod_component); - - if ((have_exp == 0) || (have_component < 3)) { - /* nope, not enough to reconstruct the private key */ - return CKR_TEMPLATE_INCOMPLETE; - } - fillPrivateKey = PR_TRUE; - } - /*verify the parameters for consistency*/ - rv = sftk_verifyRSAPrivateKey(object, fillPrivateKey); - if (rv != SECSuccess) { - return CKR_TEMPLATE_INCOMPLETE; - } - - /* make sure Netscape DB attribute is set correctly */ - crv = sftk_Attribute2SSecItem(NULL, &mod, object, CKA_MODULUS); - if (crv != CKR_OK) return crv; - crv = sftk_forceAttribute(object, CKA_NETSCAPE_DB, - sftk_item_expand(&mod)); - if (mod.data) PORT_Free(mod.data); - if (crv != CKR_OK) return crv; - - sign = CK_TRUE; - derive = CK_FALSE; - break; - case CKK_DSA: - if ( !sftk_hasAttribute(object, CKA_SUBPRIME)) { - return CKR_TEMPLATE_INCOMPLETE; - } - sign = CK_TRUE; - derive = CK_FALSE; - /* fall through */ - case CKK_DH: - if ( !sftk_hasAttribute(object, CKA_PRIME)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !sftk_hasAttribute(object, CKA_BASE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !sftk_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - encrypt = CK_FALSE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; + case CKK_RSA: + if (!sftk_hasAttribute(object, CKA_MODULUS)) { + missing_rsa_mod_component++; + } + if (!sftk_hasAttribute(object, CKA_PUBLIC_EXPONENT)) { + missing_rsa_exp_component++; + } + if (!sftk_hasAttribute(object, CKA_PRIVATE_EXPONENT)) { + missing_rsa_exp_component++; + } + if (!sftk_hasAttribute(object, CKA_PRIME_1)) { + missing_rsa_mod_component++; + } + if (!sftk_hasAttribute(object, CKA_PRIME_2)) { + missing_rsa_mod_component++; + } + if (!sftk_hasAttribute(object, CKA_EXPONENT_1)) { + missing_rsa_crt_component++; + } + if (!sftk_hasAttribute(object, CKA_EXPONENT_2)) { + missing_rsa_crt_component++; + } + if (!sftk_hasAttribute(object, CKA_COEFFICIENT)) { + missing_rsa_crt_component++; + } + if (missing_rsa_mod_component || missing_rsa_exp_component || + missing_rsa_crt_component) { + /* we are missing a component, see if we have enough to rebuild + * the rest */ + int have_exp = 2 - missing_rsa_exp_component; + int have_component = 5 - + (missing_rsa_exp_component + missing_rsa_mod_component); + + if ((have_exp == 0) || (have_component < 3)) { + /* nope, not enough to reconstruct the private key */ + return CKR_TEMPLATE_INCOMPLETE; + } + fillPrivateKey = PR_TRUE; + } + /*verify the parameters for consistency*/ + rv = sftk_verifyRSAPrivateKey(object, fillPrivateKey); + if (rv != SECSuccess) { + return CKR_TEMPLATE_INCOMPLETE; + } + + /* make sure Netscape DB attribute is set correctly */ + crv = sftk_Attribute2SSecItem(NULL, &mod, object, CKA_MODULUS); + if (crv != CKR_OK) + return crv; + crv = sftk_forceAttribute(object, CKA_NETSCAPE_DB, + sftk_item_expand(&mod)); + if (mod.data) + PORT_Free(mod.data); + if (crv != CKR_OK) + return crv; + + sign = CK_TRUE; + derive = CK_FALSE; + break; + case CKK_DSA: + if (!sftk_hasAttribute(object, CKA_SUBPRIME)) { + return CKR_TEMPLATE_INCOMPLETE; + } + sign = CK_TRUE; + derive = CK_FALSE; + /* fall through */ + case CKK_DH: + if (!sftk_hasAttribute(object, CKA_PRIME)) { + return CKR_TEMPLATE_INCOMPLETE; + } + if (!sftk_hasAttribute(object, CKA_BASE)) { + return CKR_TEMPLATE_INCOMPLETE; + } + if (!sftk_hasAttribute(object, CKA_VALUE)) { + return CKR_TEMPLATE_INCOMPLETE; + } + encrypt = CK_FALSE; + recover = CK_FALSE; + wrap = CK_FALSE; + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) { - return CKR_TEMPLATE_INCOMPLETE; - } - if ( !sftk_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; - } - encrypt = CK_FALSE; - sign = CK_TRUE; - recover = CK_FALSE; - wrap = CK_FALSE; - break; + case CKK_EC: + if (!sftk_hasAttribute(object, CKA_EC_PARAMS)) { + return CKR_TEMPLATE_INCOMPLETE; + } + if (!sftk_hasAttribute(object, CKA_VALUE)) { + return CKR_TEMPLATE_INCOMPLETE; + } + encrypt = CK_FALSE; + sign = CK_TRUE; + recover = CK_FALSE; + wrap = CK_FALSE; + break; #endif /* NSS_DISABLE_ECC */ - case CKK_NSS_JPAKE_ROUND1: - if (!sftk_hasAttribute(object, CKA_PRIME) || - !sftk_hasAttribute(object, CKA_SUBPRIME) || - !sftk_hasAttribute(object, CKA_BASE)) { - return CKR_TEMPLATE_INCOMPLETE; - } + case CKK_NSS_JPAKE_ROUND1: + if (!sftk_hasAttribute(object, CKA_PRIME) || + !sftk_hasAttribute(object, CKA_SUBPRIME) || + !sftk_hasAttribute(object, CKA_BASE)) { + return CKR_TEMPLATE_INCOMPLETE; + } /* fall through */ - case CKK_NSS_JPAKE_ROUND2: - /* CKA_NSS_JPAKE_SIGNERID and CKA_NSS_JPAKE_PEERID are checked in - the J-PAKE code. */ - encrypt = sign = recover = wrap = CK_FALSE; - derive = CK_TRUE; - createObjectInfo = PR_FALSE; - break; - default: - return CKR_ATTRIBUTE_VALUE_INVALID; - } - crv = sftk_defaultAttribute(object,CKA_SUBJECT,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_SENSITIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_DECRYPT,&encrypt,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_SIGN,&sign,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_SIGN_RECOVER,&recover, - sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_UNWRAP,&wrap,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_DERIVE,&derive,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + case CKK_NSS_JPAKE_ROUND2: + /* CKA_NSS_JPAKE_SIGNERID and CKA_NSS_JPAKE_PEERID are checked in + the J-PAKE code. */ + encrypt = sign = recover = wrap = CK_FALSE; + derive = CK_TRUE; + createObjectInfo = PR_FALSE; + break; + default: + return CKR_ATTRIBUTE_VALUE_INVALID; + } + crv = sftk_defaultAttribute(object, CKA_SUBJECT, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_SENSITIVE, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_EXTRACTABLE, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_DECRYPT, &encrypt, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_SIGN, &sign, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_SIGN_RECOVER, &recover, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_UNWRAP, &wrap, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_DERIVE, &derive, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* the next two bits get modified only in the key gen and token cases */ - crv = sftk_forceAttribute(object,CKA_ALWAYS_SENSITIVE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_forceAttribute(object,CKA_NEVER_EXTRACTABLE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + crv = sftk_forceAttribute(object, CKA_ALWAYS_SENSITIVE, + &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_forceAttribute(object, CKA_NEVER_EXTRACTABLE, + &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* should we check the non-token RSA private keys? */ - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); - if (keyHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (keyHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(keyHandle, object, &object->handle); - sftk_freeDB(keyHandle); - return crv; + crv = sftkdb_write(keyHandle, object, &object->handle); + sftk_freeDB(keyHandle); + return crv; } else if (createObjectInfo) { - object->objectInfo = sftk_mkPrivKey(object,key_type,&crv); - if (object->objectInfo == NULL) return crv; - object->infoFree = (SFTKFree) nsslowkey_DestroyPrivateKey; + object->objectInfo = sftk_mkPrivKey(object, key_type, &crv); + if (object->objectInfo == NULL) + return crv; + object->infoFree = (SFTKFree)nsslowkey_DestroyPrivateKey; } return CKR_OK; } @@ -1193,8 +1203,8 @@ void sftk_FormatDESKey(unsigned char *key, int length); /* Validate secret key data, and set defaults */ static CK_RV -validateSecretKey(SFTKSession *session, SFTKObject *object, - CK_KEY_TYPE key_type, PRBool isFIPS) +validateSecretKey(SFTKSession *session, SFTKObject *object, + CK_KEY_TYPE key_type, PRBool isFIPS) { CK_RV crv; CK_BBOOL cktrue = CK_TRUE; @@ -1202,127 +1212,139 @@ validateSecretKey(SFTKSession *session, SFTKObject *object, SFTKAttribute *attribute = NULL; unsigned long requiredLen; - crv = sftk_defaultAttribute(object,CKA_SENSITIVE, - isFIPS?&cktrue:&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_ENCRYPT,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_DECRYPT,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_SIGN,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_VERIFY,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_WRAP,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_UNWRAP,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - - if ( !sftk_hasAttribute(object, CKA_VALUE)) { - return CKR_TEMPLATE_INCOMPLETE; + crv = sftk_defaultAttribute(object, CKA_SENSITIVE, + isFIPS ? &cktrue : &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_EXTRACTABLE, + &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_ENCRYPT, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_DECRYPT, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_SIGN, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_VERIFY, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_WRAP, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_UNWRAP, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + + if (!sftk_hasAttribute(object, CKA_VALUE)) { + return CKR_TEMPLATE_INCOMPLETE; } /* the next two bits get modified only in the key gen and token cases */ - crv = sftk_forceAttribute(object,CKA_ALWAYS_SENSITIVE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_forceAttribute(object,CKA_NEVER_EXTRACTABLE, - &ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + crv = sftk_forceAttribute(object, CKA_ALWAYS_SENSITIVE, + &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_forceAttribute(object, CKA_NEVER_EXTRACTABLE, + &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* some types of keys have a value length */ crv = CKR_OK; switch (key_type) { - /* force CKA_VALUE_LEN to be set */ - case CKK_GENERIC_SECRET: - case CKK_RC2: - case CKK_RC4: + /* force CKA_VALUE_LEN to be set */ + case CKK_GENERIC_SECRET: + case CKK_RC2: + case CKK_RC4: #if NSS_SOFTOKEN_DOES_RC5 - case CKK_RC5: + case CKK_RC5: #endif #ifdef NSS_SOFTOKEN_DOES_CAST - case CKK_CAST: - case CKK_CAST3: - case CKK_CAST5: + case CKK_CAST: + case CKK_CAST3: + case CKK_CAST5: #endif #if NSS_SOFTOKEN_DOES_IDEA - case CKK_IDEA: + case CKK_IDEA: #endif - attribute = sftk_FindAttribute(object,CKA_VALUE); - /* shouldn't happen */ - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; - crv = sftk_forceAttribute(object, CKA_VALUE_LEN, - &attribute->attrib.ulValueLen, sizeof(CK_ULONG)); - sftk_FreeAttribute(attribute); - break; - /* force the value to have the correct parity */ - case CKK_DES: - case CKK_DES2: - case CKK_DES3: - case CKK_CDMF: - attribute = sftk_FindAttribute(object,CKA_VALUE); - /* shouldn't happen */ - if (attribute == NULL) - return CKR_TEMPLATE_INCOMPLETE; - requiredLen = sftk_MapKeySize(key_type); - if (attribute->attrib.ulValueLen != requiredLen) { - sftk_FreeAttribute(attribute); - return CKR_KEY_SIZE_RANGE; - } - sftk_FormatDESKey((unsigned char*)attribute->attrib.pValue, - attribute->attrib.ulValueLen); - sftk_FreeAttribute(attribute); - break; - case CKK_AES: - attribute = sftk_FindAttribute(object,CKA_VALUE); - /* shouldn't happen */ - if (attribute == NULL) - return CKR_TEMPLATE_INCOMPLETE; - if (attribute->attrib.ulValueLen != 16 && - attribute->attrib.ulValueLen != 24 && - attribute->attrib.ulValueLen != 32) { - sftk_FreeAttribute(attribute); - return CKR_KEY_SIZE_RANGE; - } - crv = sftk_forceAttribute(object, CKA_VALUE_LEN, - &attribute->attrib.ulValueLen, sizeof(CK_ULONG)); - sftk_FreeAttribute(attribute); - break; - default: - break; + attribute = sftk_FindAttribute(object, CKA_VALUE); + /* shouldn't happen */ + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; + crv = sftk_forceAttribute(object, CKA_VALUE_LEN, + &attribute->attrib.ulValueLen, sizeof(CK_ULONG)); + sftk_FreeAttribute(attribute); + break; + /* force the value to have the correct parity */ + case CKK_DES: + case CKK_DES2: + case CKK_DES3: + case CKK_CDMF: + attribute = sftk_FindAttribute(object, CKA_VALUE); + /* shouldn't happen */ + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; + requiredLen = sftk_MapKeySize(key_type); + if (attribute->attrib.ulValueLen != requiredLen) { + sftk_FreeAttribute(attribute); + return CKR_KEY_SIZE_RANGE; + } + sftk_FormatDESKey((unsigned char *)attribute->attrib.pValue, + attribute->attrib.ulValueLen); + sftk_FreeAttribute(attribute); + break; + case CKK_AES: + attribute = sftk_FindAttribute(object, CKA_VALUE); + /* shouldn't happen */ + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; + if (attribute->attrib.ulValueLen != 16 && + attribute->attrib.ulValueLen != 24 && + attribute->attrib.ulValueLen != 32) { + sftk_FreeAttribute(attribute); + return CKR_KEY_SIZE_RANGE; + } + crv = sftk_forceAttribute(object, CKA_VALUE_LEN, + &attribute->attrib.ulValueLen, sizeof(CK_ULONG)); + sftk_FreeAttribute(attribute); + break; + default: + break; } return crv; } /* - * check the consistancy and initialize a Secret Key Object + * check the consistancy and initialize a Secret Key Object */ static CK_RV -sftk_handleSecretKeyObject(SFTKSession *session,SFTKObject *object, - CK_KEY_TYPE key_type, PRBool isFIPS) +sftk_handleSecretKeyObject(SFTKSession *session, SFTKObject *object, + CK_KEY_TYPE key_type, PRBool isFIPS) { CK_RV crv; /* First validate and set defaults */ crv = validateSecretKey(session, object, key_type, isFIPS); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; /* If the object is a TOKEN object, store in the database */ - if (sftk_isTrue(object,CKA_TOKEN)) { - SFTKSlot *slot = session->slot; - SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); - CK_RV crv; + if (sftk_isTrue(object, CKA_TOKEN)) { + SFTKSlot *slot = session->slot; + SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); + CK_RV crv; - if (keyHandle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; - } + if (keyHandle == NULL) { + return CKR_TOKEN_WRITE_PROTECTED; + } - crv = sftkdb_write(keyHandle, object, &object->handle); - sftk_freeDB(keyHandle); - return crv; + crv = sftkdb_write(keyHandle, object, &object->handle); + sftk_freeDB(keyHandle); + return crv; } loser: @@ -1331,7 +1353,7 @@ loser: } /* - * check the consistancy and initialize a Key Object + * check the consistancy and initialize a Key Object */ static CK_RV sftk_handleKeyObject(SFTKSession *session, SFTKObject *object) @@ -1342,24 +1364,28 @@ sftk_handleKeyObject(SFTKSession *session, SFTKObject *object) CK_RV crv; /* verify the required fields */ - if ( !sftk_hasAttribute(object,CKA_KEY_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_KEY_TYPE)) { + return CKR_TEMPLATE_INCOMPLETE; } /* now verify the common fields */ - crv = sftk_defaultAttribute(object,CKA_ID,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_START_DATE,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_END_DATE,NULL,0); - if (crv != CKR_OK) return crv; + crv = sftk_defaultAttribute(object, CKA_ID, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_START_DATE, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_END_DATE, NULL, 0); + if (crv != CKR_OK) + return crv; /* CKA_DERIVE is common to all keys, but it's default value is * key dependent */ - crv = sftk_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + crv = sftk_defaultAttribute(object, CKA_LOCAL, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* get the key type */ - attribute = sftk_FindAttribute(object,CKA_KEY_TYPE); + attribute = sftk_FindAttribute(object, CKA_KEY_TYPE); if (!attribute) { return CKR_ATTRIBUTE_VALUE_INVALID; } @@ -1367,22 +1393,22 @@ sftk_handleKeyObject(SFTKSession *session, SFTKObject *object) sftk_FreeAttribute(attribute); switch (object->objclass) { - case CKO_PUBLIC_KEY: - return sftk_handlePublicKeyObject(session,object,key_type); - case CKO_PRIVATE_KEY: - return sftk_handlePrivateKeyObject(session,object,key_type); - case CKO_SECRET_KEY: - /* make sure the required fields exist */ - return sftk_handleSecretKeyObject(session,object,key_type, - (PRBool)(session->slot->slotID == FIPS_SLOT_ID)); - default: - break; + case CKO_PUBLIC_KEY: + return sftk_handlePublicKeyObject(session, object, key_type); + case CKO_PRIVATE_KEY: + return sftk_handlePrivateKeyObject(session, object, key_type); + case CKO_SECRET_KEY: + /* make sure the required fields exist */ + return sftk_handleSecretKeyObject(session, object, key_type, + (PRBool)(session->slot->slotID == FIPS_SLOT_ID)); + default: + break; } return CKR_ATTRIBUTE_VALUE_INVALID; } /* - * check the consistancy and Verify a DSA Parameter Object + * check the consistancy and Verify a DSA Parameter Object */ static CK_RV sftk_handleDSAParameterObject(SFTKSession *session, SFTKObject *object) @@ -1396,93 +1422,100 @@ sftk_handleDSAParameterObject(SFTKSession *session, SFTKObject *object) CK_RV crv = CKR_TEMPLATE_INCOMPLETE; PQGParams params; PQGVerify vfy, *verify = NULL; - SECStatus result,rv; + SECStatus result, rv; /* This bool keeps track of whether or not we need verify parameters. * If a P, Q and G or supplied, we dont' need verify parameters, as we - * have PQ and G. + * have PQ and G. * - If G is not supplied, the presumption is that we want to * verify P and Q only. * - If counter is supplied, it is presumed we want to verify PQ because * the counter is only used in verification. * - If H is supplied, is is presumed we want to verify G because H is * only used to verify G. - * - Any verification step must have the SEED (counter or H could be + * - Any verification step must have the SEED (counter or H could be * missing depending on exactly what we want to verify). If SEED is supplied, * the code just goes ahead and runs verify (other errors are parameter * errors are detected by the PQG_VerifyParams function). If SEED is not * supplied, but we determined that we are trying to verify (because needVfy * is set, go ahead and return CKR_TEMPLATE_INCOMPLETE. */ - PRBool needVfy = PR_FALSE; + PRBool needVfy = PR_FALSE; - primeAttr = sftk_FindAttribute(object,CKA_PRIME); - if (primeAttr == NULL) goto loser; + primeAttr = sftk_FindAttribute(object, CKA_PRIME); + if (primeAttr == NULL) + goto loser; params.prime.data = primeAttr->attrib.pValue; params.prime.len = primeAttr->attrib.ulValueLen; - subPrimeAttr = sftk_FindAttribute(object,CKA_SUBPRIME); - if (subPrimeAttr == NULL) goto loser; + subPrimeAttr = sftk_FindAttribute(object, CKA_SUBPRIME); + if (subPrimeAttr == NULL) + goto loser; params.subPrime.data = subPrimeAttr->attrib.pValue; params.subPrime.len = subPrimeAttr->attrib.ulValueLen; - baseAttr = sftk_FindAttribute(object,CKA_BASE); + baseAttr = sftk_FindAttribute(object, CKA_BASE); if (baseAttr != NULL) { - params.base.data = baseAttr->attrib.pValue; - params.base.len = baseAttr->attrib.ulValueLen; + params.base.data = baseAttr->attrib.pValue; + params.base.len = baseAttr->attrib.ulValueLen; } else { - params.base.data = NULL; - params.base.len = 0; - needVfy = PR_TRUE; /* presumably only including PQ so we can verify - * them. */ + params.base.data = NULL; + params.base.len = 0; + needVfy = PR_TRUE; /* presumably only including PQ so we can verify + * them. */ } attribute = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_COUNTER); if (attribute != NULL) { - vfy.counter = *(CK_ULONG *) attribute->attrib.pValue; - sftk_FreeAttribute(attribute); - needVfy = PR_TRUE; /* included a count so we can verify PQ */ + vfy.counter = *(CK_ULONG *)attribute->attrib.pValue; + sftk_FreeAttribute(attribute); + needVfy = PR_TRUE; /* included a count so we can verify PQ */ } else { - vfy.counter = -1; + vfy.counter = -1; } hAttr = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_H); if (hAttr != NULL) { - vfy.h.data = hAttr->attrib.pValue; - vfy.h.len = hAttr->attrib.ulValueLen; - needVfy = PR_TRUE; /* included H so we can verify G */ + vfy.h.data = hAttr->attrib.pValue; + vfy.h.len = hAttr->attrib.ulValueLen; + needVfy = PR_TRUE; /* included H so we can verify G */ } else { - vfy.h.data = NULL; - vfy.h.len = 0; + vfy.h.data = NULL; + vfy.h.len = 0; } seedAttr = sftk_FindAttribute(object, CKA_NETSCAPE_PQG_SEED); if (seedAttr != NULL) { - vfy.seed.data = seedAttr->attrib.pValue; - vfy.seed.len = seedAttr->attrib.ulValueLen; + vfy.seed.data = seedAttr->attrib.pValue; + vfy.seed.len = seedAttr->attrib.ulValueLen; - verify = &vfy; + verify = &vfy; } else if (needVfy) { - goto loser; /* Verify always needs seed, if we need verify and not seed - * then fail */ + goto loser; /* Verify always needs seed, if we need verify and not seed + * then fail */ } crv = CKR_FUNCTION_FAILED; - rv = PQG_VerifyParams(¶ms,verify,&result); + rv = PQG_VerifyParams(¶ms, verify, &result); if (rv == SECSuccess) { - crv = (result== SECSuccess) ? CKR_OK : CKR_ATTRIBUTE_VALUE_INVALID; + crv = (result == SECSuccess) ? CKR_OK : CKR_ATTRIBUTE_VALUE_INVALID; } loser: - if (hAttr) sftk_FreeAttribute(hAttr); - if (seedAttr) sftk_FreeAttribute(seedAttr); - if (baseAttr) sftk_FreeAttribute(baseAttr); - if (subPrimeAttr) sftk_FreeAttribute(subPrimeAttr); - if (primeAttr) sftk_FreeAttribute(primeAttr); + if (hAttr) + sftk_FreeAttribute(hAttr); + if (seedAttr) + sftk_FreeAttribute(seedAttr); + if (baseAttr) + sftk_FreeAttribute(baseAttr); + if (subPrimeAttr) + sftk_FreeAttribute(subPrimeAttr); + if (primeAttr) + sftk_FreeAttribute(primeAttr); return crv; } /* - * check the consistancy and initialize a Key Parameter Object + * check the consistancy and initialize a Key Parameter Object */ static CK_RV sftk_handleKeyParameterObject(SFTKSession *session, SFTKObject *object) @@ -1493,16 +1526,17 @@ sftk_handleKeyParameterObject(SFTKSession *session, SFTKObject *object) CK_RV crv; /* verify the required fields */ - if ( !sftk_hasAttribute(object,CKA_KEY_TYPE) ) { - return CKR_TEMPLATE_INCOMPLETE; + if (!sftk_hasAttribute(object, CKA_KEY_TYPE)) { + return CKR_TEMPLATE_INCOMPLETE; } /* now verify the common fields */ - crv = sftk_defaultAttribute(object,CKA_LOCAL,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + crv = sftk_defaultAttribute(object, CKA_LOCAL, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* get the key type */ - attribute = sftk_FindAttribute(object,CKA_KEY_TYPE); + attribute = sftk_FindAttribute(object, CKA_KEY_TYPE); if (!attribute) { return CKR_ATTRIBUTE_VALUE_INVALID; } @@ -1510,16 +1544,16 @@ sftk_handleKeyParameterObject(SFTKSession *session, SFTKObject *object) sftk_FreeAttribute(attribute); switch (key_type) { - case CKK_DSA: - return sftk_handleDSAParameterObject(session,object); - - default: - break; + case CKK_DSA: + return sftk_handleDSAParameterObject(session, object); + + default: + break; } return CKR_KEY_TYPE_INCONSISTENT; } -/* +/* * Handle Object does all the object consistancy checks, automatic attribute * generation, attribute defaulting, etc. If handleObject succeeds, the object * will be assigned an object handle, and the object installed in the session @@ -1538,104 +1572,107 @@ sftk_handleObject(SFTKObject *object, SFTKSession *session) /* make sure all the base object types are defined. If not set the * defaults */ - crv = sftk_defaultAttribute(object,CKA_TOKEN,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_PRIVATE,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_LABEL,NULL,0); - if (crv != CKR_OK) return crv; - crv = sftk_defaultAttribute(object,CKA_MODIFIABLE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) return crv; + crv = sftk_defaultAttribute(object, CKA_TOKEN, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_PRIVATE, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_LABEL, NULL, 0); + if (crv != CKR_OK) + return crv; + crv = sftk_defaultAttribute(object, CKA_MODIFIABLE, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + return crv; /* don't create a private object if we aren't logged in */ if ((!slot->isLoggedIn) && (slot->needLogin) && - (sftk_isTrue(object,CKA_PRIVATE))) { - return CKR_USER_NOT_LOGGED_IN; + (sftk_isTrue(object, CKA_PRIVATE))) { + return CKR_USER_NOT_LOGGED_IN; } - if (((session->info.flags & CKF_RW_SESSION) == 0) && - (sftk_isTrue(object,CKA_TOKEN))) { - return CKR_SESSION_READ_ONLY; + (sftk_isTrue(object, CKA_TOKEN))) { + return CKR_SESSION_READ_ONLY; } - + /* Assign a unique SESSION object handle to every new object, - * whether it is a session object or a token object. + * whether it is a session object or a token object. * At this point, all new objects are structured as session objects. - * Objects with the CKA_TOKEN attribute true will be turned into - * token objects and will have a token object handle assigned to - * them by a call to sftk_mkHandle in the handler for each object + * Objects with the CKA_TOKEN attribute true will be turned into + * token objects and will have a token object handle assigned to + * them by a call to sftk_mkHandle in the handler for each object * class, invoked below. * - * It may be helpful to note/remember that + * It may be helpful to note/remember that * sftk_narrowToXxxObject uses sftk_isToken, * sftk_isToken examines the sign bit of the object's handle, but * sftk_isTrue(...,CKA_TOKEN) examines the CKA_TOKEN attribute. */ do { - PRUint32 wrappedAround; - - duplicateObject = NULL; - PZ_Lock(slot->objectLock); - wrappedAround = slot->sessionObjectHandleCount & SFTK_TOKEN_MASK; - handle = slot->sessionObjectHandleCount & ~SFTK_TOKEN_MASK; - if (!handle) /* don't allow zero handle */ - handle = minSessionObjectHandle; - slot->sessionObjectHandleCount = (handle + 1U) | wrappedAround; - /* Is there already a session object with this handle? */ - if (wrappedAround) { - sftkqueue_find(duplicateObject, handle, slot->sessObjHashTable, \ - slot->sessObjHashSize); - } - PZ_Unlock(slot->objectLock); + PRUint32 wrappedAround; + + duplicateObject = NULL; + PZ_Lock(slot->objectLock); + wrappedAround = slot->sessionObjectHandleCount & SFTK_TOKEN_MASK; + handle = slot->sessionObjectHandleCount & ~SFTK_TOKEN_MASK; + if (!handle) /* don't allow zero handle */ + handle = minSessionObjectHandle; + slot->sessionObjectHandleCount = (handle + 1U) | wrappedAround; + /* Is there already a session object with this handle? */ + if (wrappedAround) { + sftkqueue_find(duplicateObject, handle, slot->sessObjHashTable, + slot->sessObjHashSize); + } + PZ_Unlock(slot->objectLock); } while (duplicateObject != NULL); object->handle = handle; /* get the object class */ - attribute = sftk_FindAttribute(object,CKA_CLASS); + attribute = sftk_FindAttribute(object, CKA_CLASS); if (attribute == NULL) { - return CKR_TEMPLATE_INCOMPLETE; + return CKR_TEMPLATE_INCOMPLETE; } object->objclass = *(CK_OBJECT_CLASS *)attribute->attrib.pValue; sftk_FreeAttribute(attribute); - /* Now handle the specific object class. + /* Now handle the specific object class. * At this point, all objects are session objects, and the session * number must be passed to the object class handlers. */ switch (object->objclass) { - case CKO_DATA: - crv = sftk_handleDataObject(session,object); - break; - case CKO_CERTIFICATE: - crv = sftk_handleCertObject(session,object); - break; - case CKO_NETSCAPE_TRUST: - crv = sftk_handleTrustObject(session,object); - break; - case CKO_NETSCAPE_CRL: - crv = sftk_handleCrlObject(session,object); - break; - case CKO_NETSCAPE_SMIME: - crv = sftk_handleSMimeObject(session,object); - break; - case CKO_PRIVATE_KEY: - case CKO_PUBLIC_KEY: - case CKO_SECRET_KEY: - crv = sftk_handleKeyObject(session,object); - break; - case CKO_KG_PARAMETERS: - crv = sftk_handleKeyParameterObject(session,object); - break; - default: - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; + case CKO_DATA: + crv = sftk_handleDataObject(session, object); + break; + case CKO_CERTIFICATE: + crv = sftk_handleCertObject(session, object); + break; + case CKO_NETSCAPE_TRUST: + crv = sftk_handleTrustObject(session, object); + break; + case CKO_NETSCAPE_CRL: + crv = sftk_handleCrlObject(session, object); + break; + case CKO_NETSCAPE_SMIME: + crv = sftk_handleSMimeObject(session, object); + break; + case CKO_PRIVATE_KEY: + case CKO_PUBLIC_KEY: + case CKO_SECRET_KEY: + crv = sftk_handleKeyObject(session, object); + break; + case CKO_KG_PARAMETERS: + crv = sftk_handleKeyParameterObject(session, object); + break; + default: + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; } /* can't fail from here on out unless the pk_handlXXX functions have * failed the request */ if (crv != CKR_OK) { - return crv; + return crv; } /* Now link the object into the slot and session structures. @@ -1644,10 +1681,10 @@ sftk_handleObject(SFTKObject *object, SFTKSession *session) * causing the following test to be true. */ if (sftk_isToken(object->handle)) { - sftk_convertSessionToToken(object); + sftk_convertSessionToToken(object); } else { - object->slot = slot; - sftk_AddObject(session,object); + object->slot = slot; + sftk_AddObject(session, object); } return CKR_OK; @@ -1657,152 +1694,158 @@ sftk_handleObject(SFTKObject *object, SFTKSession *session) * ******************** Public Key Utilities *************************** */ /* Generate a low public key structure from an object */ -NSSLOWKEYPublicKey *sftk_GetPubKey(SFTKObject *object,CK_KEY_TYPE key_type, - CK_RV *crvp) +NSSLOWKEYPublicKey * +sftk_GetPubKey(SFTKObject *object, CK_KEY_TYPE key_type, + CK_RV *crvp) { NSSLOWKEYPublicKey *pubKey; PLArenaPool *arena; CK_RV crv; if (object->objclass != CKO_PUBLIC_KEY) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; + *crvp = CKR_KEY_TYPE_INCONSISTENT; + return NULL; } if (sftk_isToken(object->handle)) { -/* ferret out the token object handle */ + /* ferret out the token object handle */ } /* If we already have a key, use it */ if (object->objectInfo) { - *crvp = CKR_OK; - return (NSSLOWKEYPublicKey *)object->objectInfo; + *crvp = CKR_OK; + return (NSSLOWKEYPublicKey *)object->objectInfo; } /* allocate the structure */ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - *crvp = CKR_HOST_MEMORY; - return NULL; + *crvp = CKR_HOST_MEMORY; + return NULL; } pubKey = (NSSLOWKEYPublicKey *) - PORT_ArenaAlloc(arena,sizeof(NSSLOWKEYPublicKey)); + PORT_ArenaAlloc(arena, sizeof(NSSLOWKEYPublicKey)); if (pubKey == NULL) { - PORT_FreeArena(arena,PR_FALSE); - *crvp = CKR_HOST_MEMORY; - return NULL; + PORT_FreeArena(arena, PR_FALSE); + *crvp = CKR_HOST_MEMORY; + return NULL; } /* fill in the structure */ pubKey->arena = arena; switch (key_type) { - case CKK_RSA: - pubKey->keyType = NSSLOWKEYRSAKey; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.rsa.modulus, - object,CKA_MODULUS); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.rsa.publicExponent, - object,CKA_PUBLIC_EXPONENT); - break; - case CKK_DSA: - pubKey->keyType = NSSLOWKEYDSAKey; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.subPrime, - object,CKA_SUBPRIME); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.params.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dsa.publicValue, - object,CKA_VALUE); - break; - case CKK_DH: - pubKey->keyType = NSSLOWKEYDHKey; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.prime, - object,CKA_PRIME); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.base, - object,CKA_BASE); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.publicValue, - object,CKA_VALUE); - break; + case CKK_RSA: + pubKey->keyType = NSSLOWKEYRSAKey; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.rsa.modulus, + object, CKA_MODULUS); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.rsa.publicExponent, + object, CKA_PUBLIC_EXPONENT); + break; + case CKK_DSA: + pubKey->keyType = NSSLOWKEYDSAKey; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.prime, + object, CKA_PRIME); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.subPrime, + object, CKA_SUBPRIME); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.params.base, + object, CKA_BASE); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dsa.publicValue, + object, CKA_VALUE); + break; + case CKK_DH: + pubKey->keyType = NSSLOWKEYDHKey; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.prime, + object, CKA_PRIME); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.base, + object, CKA_BASE); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.dh.publicValue, + object, CKA_VALUE); + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - pubKey->keyType = NSSLOWKEYECKey; - crv = sftk_Attribute2SSecItem(arena, - &pubKey->u.ec.ecParams.DEREncoding, - object,CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (EC_FillParams(arena, &pubKey->u.ec.ecParams.DEREncoding, - &pubKey->u.ec.ecParams) != SECSuccess) { - crv = CKR_DOMAIN_PARAMS_INVALID; - break; - } - - crv = sftk_Attribute2SSecItem(arena,&pubKey->u.ec.publicValue, - object,CKA_EC_POINT); - if (crv == CKR_OK) { - unsigned int keyLen,curveLen; - - curveLen = (pubKey->u.ec.ecParams.fieldID.size +7)/8; - keyLen = (2*curveLen)+1; - - /* special note: We can't just use the first byte to determine - * between these 2 cases because both EC_POINT_FORM_UNCOMPRESSED - * and SEC_ASN1_OCTET_STRING are 0x04 */ - - /* handle the non-DER encoded case (UNCOMPRESSED only) */ - if (pubKey->u.ec.publicValue.data[0] == EC_POINT_FORM_UNCOMPRESSED - && pubKey->u.ec.publicValue.len == keyLen) { - break; /* key was not DER encoded, no need to unwrap */ - } - - /* if we ever support compressed, handle it here */ - - /* handle the encoded case */ - if ((pubKey->u.ec.publicValue.data[0] == SEC_ASN1_OCTET_STRING) - && pubKey->u.ec.publicValue.len > keyLen) { - SECItem publicValue; - SECStatus rv; - - rv = SEC_QuickDERDecodeItem(arena, &publicValue, - SEC_ASN1_GET(SEC_OctetStringTemplate), - &pubKey->u.ec.publicValue); - /* nope, didn't decode correctly */ - if ((rv != SECSuccess) - || (publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) - || (publicValue.len != keyLen)) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - /* replace our previous with the decoded key */ - pubKey->u.ec.publicValue = publicValue; - break; - } - crv = CKR_ATTRIBUTE_VALUE_INVALID; - } - break; + case CKK_EC: + pubKey->keyType = NSSLOWKEYECKey; + crv = sftk_Attribute2SSecItem(arena, + &pubKey->u.ec.ecParams.DEREncoding, + object, CKA_EC_PARAMS); + if (crv != CKR_OK) + break; + + /* Fill out the rest of the ecParams structure + * based on the encoded params + */ + if (EC_FillParams(arena, &pubKey->u.ec.ecParams.DEREncoding, + &pubKey->u.ec.ecParams) != SECSuccess) { + crv = CKR_DOMAIN_PARAMS_INVALID; + break; + } + + crv = sftk_Attribute2SSecItem(arena, &pubKey->u.ec.publicValue, + object, CKA_EC_POINT); + if (crv == CKR_OK) { + unsigned int keyLen = pubKey->u.ec.ecParams.pointSize; + + /* special note: We can't just use the first byte to distinguish + * between EC_POINT_FORM_UNCOMPRESSED and SEC_ASN1_OCTET_STRING. + * Both are 0x04. */ + + /* Handle the non-DER encoded case. + * Some curves are always pressumed to be non-DER. + */ + if (pubKey->u.ec.publicValue.len == keyLen && + (pubKey->u.ec.ecParams.fieldID.type == ec_field_plain || + pubKey->u.ec.publicValue.data[0] == EC_POINT_FORM_UNCOMPRESSED)) { + break; /* key was not DER encoded, no need to unwrap */ + } + + PORT_Assert(pubKey->u.ec.ecParams.name != ECCurve25519); + + /* handle the encoded case */ + if ((pubKey->u.ec.publicValue.data[0] == SEC_ASN1_OCTET_STRING) && + pubKey->u.ec.publicValue.len > keyLen) { + SECItem publicValue; + SECStatus rv; + + rv = SEC_QuickDERDecodeItem(arena, &publicValue, + SEC_ASN1_GET(SEC_OctetStringTemplate), + &pubKey->u.ec.publicValue); + /* nope, didn't decode correctly */ + if ((rv != SECSuccess) || (publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) || (publicValue.len != keyLen)) { + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; + } + /* replace our previous with the decoded key */ + pubKey->u.ec.publicValue = publicValue; + break; + } + crv = CKR_ATTRIBUTE_VALUE_INVALID; + } + break; #endif /* NSS_DISABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; + default: + crv = CKR_KEY_TYPE_INCONSISTENT; + break; } *crvp = crv; if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } object->objectInfo = pubKey; - object->infoFree = (SFTKFree) nsslowkey_DestroyPublicKey; + object->infoFree = (SFTKFree)nsslowkey_DestroyPublicKey; return pubKey; } @@ -1819,144 +1862,148 @@ sftk_mkPrivKey(SFTKObject *object, CK_KEY_TYPE key_type, CK_RV *crvp) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - *crvp = CKR_HOST_MEMORY; - return NULL; + *crvp = CKR_HOST_MEMORY; + return NULL; } privKey = (NSSLOWKEYPrivateKey *) - PORT_ArenaZAlloc(arena,sizeof(NSSLOWKEYPrivateKey)); - if (privKey == NULL) { - PORT_FreeArena(arena,PR_FALSE); - *crvp = CKR_HOST_MEMORY; - return NULL; + PORT_ArenaZAlloc(arena, sizeof(NSSLOWKEYPrivateKey)); + if (privKey == NULL) { + PORT_FreeArena(arena, PR_FALSE); + *crvp = CKR_HOST_MEMORY; + return NULL; } /* in future this would be a switch on key_type */ privKey->arena = arena; switch (key_type) { - case CKK_RSA: - privKey->keyType = NSSLOWKEYRSAKey; - - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.modulus,CKA_MODULUS); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.publicExponent, CKA_PUBLIC_EXPONENT); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.privateExponent, CKA_PRIVATE_EXPONENT); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.prime1, CKA_PRIME_1); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.prime2, CKA_PRIME_2); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.exponent1, CKA_EXPONENT_1); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.exponent2, CKA_EXPONENT_2); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.rsa.coefficient, CKA_COEFFICIENT); - itemTemplateCount++; - rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version, - NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); - if (rv != SECSuccess) crv = CKR_HOST_MEMORY; - break; - - case CKK_DSA: - privKey->keyType = NSSLOWKEYDSAKey; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dsa.params.prime, CKA_PRIME); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dsa.params.subPrime, CKA_SUBPRIME); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dsa.params.base, CKA_BASE); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dsa.privateValue, CKA_VALUE); - itemTemplateCount++; - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - break; - - case CKK_DH: - privKey->keyType = NSSLOWKEYDHKey; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dh.prime, CKA_PRIME); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dh.base, CKA_BASE); - itemTemplateCount++; - SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, - &privKey->u.dh.privateValue, CKA_VALUE); - itemTemplateCount++; - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - break; + case CKK_RSA: + privKey->keyType = NSSLOWKEYRSAKey; + + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.modulus, CKA_MODULUS); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.publicExponent, CKA_PUBLIC_EXPONENT); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.privateExponent, CKA_PRIVATE_EXPONENT); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.prime1, CKA_PRIME_1); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.prime2, CKA_PRIME_2); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.exponent1, CKA_EXPONENT_1); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.exponent2, CKA_EXPONENT_2); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.rsa.coefficient, CKA_COEFFICIENT); + itemTemplateCount++; + rv = DER_SetUInteger(privKey->arena, &privKey->u.rsa.version, + NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); + if (rv != SECSuccess) + crv = CKR_HOST_MEMORY; + break; + + case CKK_DSA: + privKey->keyType = NSSLOWKEYDSAKey; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dsa.params.prime, CKA_PRIME); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dsa.params.subPrime, CKA_SUBPRIME); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dsa.params.base, CKA_BASE); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dsa.privateValue, CKA_VALUE); + itemTemplateCount++; + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + break; + + case CKK_DH: + privKey->keyType = NSSLOWKEYDHKey; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dh.prime, CKA_PRIME); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dh.base, CKA_BASE); + itemTemplateCount++; + SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount, + &privKey->u.dh.privateValue, CKA_VALUE); + itemTemplateCount++; + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - privKey->keyType = NSSLOWKEYECKey; - crv = sftk_Attribute2SSecItem(arena, - &privKey->u.ec.ecParams.DEREncoding, - object,CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - /* Fill out the rest of the ecParams structure - * based on the encoded params - */ - if (EC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding, - &privKey->u.ec.ecParams) != SECSuccess) { - crv = CKR_DOMAIN_PARAMS_INVALID; - break; - } - crv = sftk_Attribute2SSecItem(arena,&privKey->u.ec.privateValue, - object,CKA_VALUE); - if (crv != CKR_OK) break; - - if (sftk_hasAttribute(object, CKA_NETSCAPE_DB)) { - crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.publicValue, - object, CKA_NETSCAPE_DB); - if (crv != CKR_OK) break; - /* privKey was zero'd so public value is already set to NULL, 0 - * if we don't set it explicitly */ - } - rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version, - NSSLOWKEY_EC_PRIVATE_KEY_VERSION); - if (rv != SECSuccess) { - crv = CKR_HOST_MEMORY; - /* The following ifdef is needed for Linux arm distros and - * Android as gcc 4.6 has a bug when targeting arm (but not - * thumb). The bug has been fixed in gcc 4.7. - * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56561 - */ -#if defined (__arm__) && !defined(__thumb__) && defined (__GNUC__) - *crvp = CKR_HOST_MEMORY; - break; + case CKK_EC: + privKey->keyType = NSSLOWKEYECKey; + crv = sftk_Attribute2SSecItem(arena, + &privKey->u.ec.ecParams.DEREncoding, + object, CKA_EC_PARAMS); + if (crv != CKR_OK) + break; + + /* Fill out the rest of the ecParams structure + * based on the encoded params + */ + if (EC_FillParams(arena, &privKey->u.ec.ecParams.DEREncoding, + &privKey->u.ec.ecParams) != SECSuccess) { + crv = CKR_DOMAIN_PARAMS_INVALID; + break; + } + crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.privateValue, + object, CKA_VALUE); + if (crv != CKR_OK) + break; + + if (sftk_hasAttribute(object, CKA_NETSCAPE_DB)) { + crv = sftk_Attribute2SSecItem(arena, &privKey->u.ec.publicValue, + object, CKA_NETSCAPE_DB); + if (crv != CKR_OK) + break; + /* privKey was zero'd so public value is already set to NULL, 0 + * if we don't set it explicitly */ + } + rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version, + NSSLOWKEY_EC_PRIVATE_KEY_VERSION); + if (rv != SECSuccess) { + crv = CKR_HOST_MEMORY; +/* The following ifdef is needed for Linux arm distros and + * Android as gcc 4.6 has a bug when targeting arm (but not + * thumb). The bug has been fixed in gcc 4.7. + * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56561 + */ +#if defined(__arm__) && !defined(__thumb__) && defined(__GNUC__) + *crvp = CKR_HOST_MEMORY; + break; #endif - } - break; + } + break; #endif /* NSS_DISABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; + default: + crv = CKR_KEY_TYPE_INCONSISTENT; + break; } if (crv == CKR_OK && itemTemplateCount != 0) { - PORT_Assert(itemTemplateCount > 0); - PORT_Assert(itemTemplateCount <= SFTK_MAX_ITEM_TEMPLATE); - crv = sftk_MultipleAttribute2SecItem(arena, object, itemTemplate, - itemTemplateCount); + PORT_Assert(itemTemplateCount > 0); + PORT_Assert(itemTemplateCount <= SFTK_MAX_ITEM_TEMPLATE); + crv = sftk_MultipleAttribute2SecItem(arena, object, itemTemplate, + itemTemplateCount); } *crvp = crv; if (crv != CKR_OK) { - PORT_FreeArena(arena,PR_FALSE); - return NULL; + PORT_FreeArena(arena, PR_FALSE); + return NULL; } return privKey; } @@ -1985,156 +2032,164 @@ sftk_verifyRSAPrivateKey(SFTKObject *object, PRBool fillIfNeeded) tmpKey.arena = NULL; modulus = sftk_FindAttribute(object, CKA_MODULUS); if (modulus) { - tmpKey.modulus.data = modulus->attrib.pValue; - tmpKey.modulus.len = modulus->attrib.ulValueLen; - } + tmpKey.modulus.data = modulus->attrib.pValue; + tmpKey.modulus.len = modulus->attrib.ulValueLen; + } prime1 = sftk_FindAttribute(object, CKA_PRIME_1); if (prime1) { - tmpKey.prime1.data = prime1->attrib.pValue; - tmpKey.prime1.len = prime1->attrib.ulValueLen; - } + tmpKey.prime1.data = prime1->attrib.pValue; + tmpKey.prime1.len = prime1->attrib.ulValueLen; + } prime2 = sftk_FindAttribute(object, CKA_PRIME_2); if (prime2) { - tmpKey.prime2.data = prime2->attrib.pValue; - tmpKey.prime2.len = prime2->attrib.ulValueLen; - } + tmpKey.prime2.data = prime2->attrib.pValue; + tmpKey.prime2.len = prime2->attrib.ulValueLen; + } privateExponent = sftk_FindAttribute(object, CKA_PRIVATE_EXPONENT); if (privateExponent) { - tmpKey.privateExponent.data = privateExponent->attrib.pValue; - tmpKey.privateExponent.len = privateExponent->attrib.ulValueLen; - } + tmpKey.privateExponent.data = privateExponent->attrib.pValue; + tmpKey.privateExponent.len = privateExponent->attrib.ulValueLen; + } publicExponent = sftk_FindAttribute(object, CKA_PUBLIC_EXPONENT); if (publicExponent) { - tmpKey.publicExponent.data = publicExponent->attrib.pValue; - tmpKey.publicExponent.len = publicExponent->attrib.ulValueLen; + tmpKey.publicExponent.data = publicExponent->attrib.pValue; + tmpKey.publicExponent.len = publicExponent->attrib.ulValueLen; } exponent1 = sftk_FindAttribute(object, CKA_EXPONENT_1); if (exponent1) { - tmpKey.exponent1.data = exponent1->attrib.pValue; - tmpKey.exponent1.len = exponent1->attrib.ulValueLen; + tmpKey.exponent1.data = exponent1->attrib.pValue; + tmpKey.exponent1.len = exponent1->attrib.ulValueLen; } exponent2 = sftk_FindAttribute(object, CKA_EXPONENT_2); if (exponent2) { - tmpKey.exponent2.data = exponent2->attrib.pValue; - tmpKey.exponent2.len = exponent2->attrib.ulValueLen; + tmpKey.exponent2.data = exponent2->attrib.pValue; + tmpKey.exponent2.len = exponent2->attrib.ulValueLen; } coefficient = sftk_FindAttribute(object, CKA_COEFFICIENT); if (coefficient) { - tmpKey.coefficient.data = coefficient->attrib.pValue; - tmpKey.coefficient.len = coefficient->attrib.ulValueLen; + tmpKey.coefficient.data = coefficient->attrib.pValue; + tmpKey.coefficient.len = coefficient->attrib.ulValueLen; } if (fillIfNeeded) { - /* - * populate requires one exponent plus 2 other components to work. - * we expected our caller to check that first. If that didn't happen, - * populate will simply return an error here. - */ - rv = RSA_PopulatePrivateKey(&tmpKey); - if (rv != SECSuccess) { - goto loser; - } + /* + * populate requires one exponent plus 2 other components to work. + * we expected our caller to check that first. If that didn't happen, + * populate will simply return an error here. + */ + rv = RSA_PopulatePrivateKey(&tmpKey); + if (rv != SECSuccess) { + goto loser; + } } rv = RSA_PrivateKeyCheck(&tmpKey); if (rv != SECSuccess) { - goto loser; + goto loser; } /* now that we have a fully populated key, set all our attribute values */ rv = SECFailure; if (!modulus || modulus->attrib.pValue != tmpKey.modulus.data) { - crv = sftk_forceAttribute(object,CKA_MODULUS, + crv = sftk_forceAttribute(object, CKA_MODULUS, sftk_item_expand(&tmpKey.modulus)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!publicExponent || publicExponent->attrib.pValue != tmpKey.publicExponent.data) { crv = sftk_forceAttribute(object, CKA_PUBLIC_EXPONENT, sftk_item_expand(&tmpKey.publicExponent)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!privateExponent || privateExponent->attrib.pValue != tmpKey.privateExponent.data) { crv = sftk_forceAttribute(object, CKA_PRIVATE_EXPONENT, sftk_item_expand(&tmpKey.privateExponent)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!prime1 || prime1->attrib.pValue != tmpKey.prime1.data) { crv = sftk_forceAttribute(object, CKA_PRIME_1, sftk_item_expand(&tmpKey.prime1)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!prime2 || prime2->attrib.pValue != tmpKey.prime2.data) { crv = sftk_forceAttribute(object, CKA_PRIME_2, sftk_item_expand(&tmpKey.prime2)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!exponent1 || exponent1->attrib.pValue != tmpKey.exponent1.data) { crv = sftk_forceAttribute(object, CKA_EXPONENT_1, - sftk_item_expand(&tmpKey.exponent1)); - if (crv != CKR_OK) goto loser; + sftk_item_expand(&tmpKey.exponent1)); + if (crv != CKR_OK) + goto loser; } if (!exponent2 || exponent2->attrib.pValue != tmpKey.exponent2.data) { crv = sftk_forceAttribute(object, CKA_EXPONENT_2, sftk_item_expand(&tmpKey.exponent2)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } if (!coefficient || coefficient->attrib.pValue != tmpKey.coefficient.data) { crv = sftk_forceAttribute(object, CKA_COEFFICIENT, sftk_item_expand(&tmpKey.coefficient)); - if (crv != CKR_OK) goto loser; + if (crv != CKR_OK) + goto loser; } rv = SECSuccess; - /* we're done (one way or the other), clean up all our stuff */ +/* we're done (one way or the other), clean up all our stuff */ loser: if (tmpKey.arena) { - PORT_FreeArena(tmpKey.arena,PR_TRUE); + PORT_FreeArena(tmpKey.arena, PR_TRUE); } if (modulus) { - sftk_FreeAttribute(modulus); + sftk_FreeAttribute(modulus); } if (prime1) { - sftk_FreeAttribute(prime1); + sftk_FreeAttribute(prime1); } if (prime2) { - sftk_FreeAttribute(prime2); + sftk_FreeAttribute(prime2); } if (privateExponent) { - sftk_FreeAttribute(privateExponent); + sftk_FreeAttribute(privateExponent); } if (publicExponent) { - sftk_FreeAttribute(publicExponent); + sftk_FreeAttribute(publicExponent); } if (exponent1) { - sftk_FreeAttribute(exponent1); + sftk_FreeAttribute(exponent1); } if (exponent2) { - sftk_FreeAttribute(exponent2); + sftk_FreeAttribute(exponent2); } if (coefficient) { - sftk_FreeAttribute(coefficient); + sftk_FreeAttribute(coefficient); } return rv; } /* Generate a low private key structure from an object */ NSSLOWKEYPrivateKey * -sftk_GetPrivKey(SFTKObject *object,CK_KEY_TYPE key_type, CK_RV *crvp) +sftk_GetPrivKey(SFTKObject *object, CK_KEY_TYPE key_type, CK_RV *crvp) { NSSLOWKEYPrivateKey *priv = NULL; if (object->objclass != CKO_PRIVATE_KEY) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; + *crvp = CKR_KEY_TYPE_INCONSISTENT; + return NULL; } if (object->objectInfo) { - *crvp = CKR_OK; - return (NSSLOWKEYPrivateKey *)object->objectInfo; + *crvp = CKR_OK; + return (NSSLOWKEYPrivateKey *)object->objectInfo; } priv = sftk_mkPrivKey(object, key_type, crvp); object->objectInfo = priv; - object->infoFree = (SFTKFree) nsslowkey_DestroyPrivateKey; + object->infoFree = (SFTKFree)nsslowkey_DestroyPrivateKey; return priv; } @@ -2150,8 +2205,8 @@ sftk_FormatDESKey(unsigned char *key, int length) int i; /* format the des key */ - for (i=0; i < length; i++) { - key[i] = parityTable[key[i]>>1]; + for (i = 0; i < length; i++) { + key[i] = parityTable[key[i] >> 1]; } } @@ -2166,10 +2221,10 @@ sftk_CheckDESKey(unsigned char *key) /* format the des key with parity */ sftk_FormatDESKey(key, 8); - for (i=0; i < sftk_desWeakTableSize; i++) { - if (PORT_Memcmp(key,sftk_desWeakTable[i],8) == 0) { - return PR_TRUE; - } + for (i = 0; i < sftk_desWeakTableSize; i++) { + if (PORT_Memcmp(key, sftk_desWeakTable[i], 8) == 0) { + return PR_TRUE; + } } return PR_FALSE; } @@ -2178,47 +2233,46 @@ sftk_CheckDESKey(unsigned char *key) * check if a des or triple des key is weak. */ PRBool -sftk_IsWeakKey(unsigned char *key,CK_KEY_TYPE key_type) +sftk_IsWeakKey(unsigned char *key, CK_KEY_TYPE key_type) { - switch(key_type) { - case CKK_DES: - return sftk_CheckDESKey(key); - case CKM_DES2_KEY_GEN: - if (sftk_CheckDESKey(key)) return PR_TRUE; - return sftk_CheckDESKey(&key[8]); - case CKM_DES3_KEY_GEN: - if (sftk_CheckDESKey(key)) return PR_TRUE; - if (sftk_CheckDESKey(&key[8])) return PR_TRUE; - return sftk_CheckDESKey(&key[16]); - default: - break; + switch (key_type) { + case CKK_DES: + return sftk_CheckDESKey(key); + case CKM_DES2_KEY_GEN: + if (sftk_CheckDESKey(key)) + return PR_TRUE; + return sftk_CheckDESKey(&key[8]); + case CKM_DES3_KEY_GEN: + if (sftk_CheckDESKey(key)) + return PR_TRUE; + if (sftk_CheckDESKey(&key[8])) + return PR_TRUE; + return sftk_CheckDESKey(&key[16]); + default: + break; } return PR_FALSE; } - /********************************************************************** * - * Start of PKCS 11 functions + * Start of PKCS 11 functions * **********************************************************************/ - /* return the function list */ -CK_RV NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) +CK_RV +NSC_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) { - CHECK_FORK(); - - *pFunctionList = (CK_FUNCTION_LIST_PTR) &sftk_funcList; + *pFunctionList = (CK_FUNCTION_LIST_PTR)&sftk_funcList; return CKR_OK; } /* return the function list */ -CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) +CK_RV +C_GetFunctionList(CK_FUNCTION_LIST_PTR *pFunctionList) { - CHECK_FORK(); - return NSC_GetFunctionList(pFunctionList); } @@ -2239,16 +2293,16 @@ sftk_getDefTokName(CK_SLOT_ID slotID) static char buf[33]; switch (slotID) { - case NETSCAPE_SLOT_ID: - return "NSS Generic Crypto Services "; - case PRIVATE_KEY_SLOT_ID: - return "NSS Certificate DB "; - case FIPS_SLOT_ID: - return "NSS FIPS 140-2 Certificate DB "; - default: - break; - } - sprintf(buf,"NSS Application Token %08x ",(unsigned int) slotID); + case NETSCAPE_SLOT_ID: + return "NSS Generic Crypto Services "; + case PRIVATE_KEY_SLOT_ID: + return "NSS Certificate DB "; + case FIPS_SLOT_ID: + return "NSS FIPS 140-2 Certificate DB "; + default: + break; + } + sprintf(buf, "NSS Application Token %08x ", (unsigned int)slotID); return buf; } @@ -2258,34 +2312,31 @@ sftk_getDefSlotName(CK_SLOT_ID slotID) static char buf[65]; switch (slotID) { - case NETSCAPE_SLOT_ID: - return - "NSS Internal Cryptographic Services "; - case PRIVATE_KEY_SLOT_ID: - return - "NSS User Private Key and Certificate Services "; - case FIPS_SLOT_ID: - return - "NSS FIPS 140-2 User Private Key Services "; - default: - break; + case NETSCAPE_SLOT_ID: + return "NSS Internal Cryptographic Services "; + case PRIVATE_KEY_SLOT_ID: + return "NSS User Private Key and Certificate Services "; + case FIPS_SLOT_ID: + return "NSS FIPS 140-2 User Private Key Services "; + default: + break; } sprintf(buf, - "NSS Application Slot %08x ", - (unsigned int) slotID); + "NSS Application Slot %08x ", + (unsigned int)slotID); return buf; } -static CK_ULONG nscSlotCount[2] = {0 , 0}; -static CK_SLOT_ID_PTR nscSlotList[2] = {NULL, NULL}; -static CK_ULONG nscSlotListSize[2] = {0, 0}; -static PLHashTable *nscSlotHashTable[2] = {NULL, NULL}; +static CK_ULONG nscSlotCount[2] = { 0, 0 }; +static CK_SLOT_ID_PTR nscSlotList[2] = { NULL, NULL }; +static CK_ULONG nscSlotListSize[2] = { 0, 0 }; +static PLHashTable *nscSlotHashTable[2] = { NULL, NULL }; -static int +static unsigned int sftk_GetModuleIndex(CK_SLOT_ID slotID) { if ((slotID == FIPS_SLOT_ID) || (slotID >= SFTK_MIN_FIPS_USER_SLOT_ID)) { - return NSC_FIPS_MODULE; + return NSC_FIPS_MODULE; } return NSC_NON_FIPS_MODULE; } @@ -2299,12 +2350,14 @@ sftk_SlotFromID(CK_SLOT_ID slotID, PRBool all) { SFTKSlot *slot; int index = sftk_GetModuleIndex(slotID); - - if (nscSlotHashTable[index] == NULL) return NULL; - slot = (SFTKSlot *)PL_HashTableLookupConst(nscSlotHashTable[index], - (void *)slotID); + + if (nscSlotHashTable[index] == NULL) + return NULL; + slot = (SFTKSlot *)PL_HashTableLookupConst(nscSlotHashTable[index], + (void *)slotID); /* cleared slots shouldn't 'show up' */ - if (slot && !all && !slot->present) slot = NULL; + if (slot && !all && !slot->present) + slot = NULL; return slot; } @@ -2315,57 +2368,57 @@ sftk_SlotFromSessionHandle(CK_SESSION_HANDLE handle) CK_ULONG moduleIndex = (handle >> 31) & 1; if (slotIDIndex >= nscSlotCount[moduleIndex]) { - return NULL; + return NULL; } return sftk_SlotFromID(nscSlotList[moduleIndex][slotIDIndex], PR_FALSE); } - + static CK_RV sftk_RegisterSlot(SFTKSlot *slot, int moduleIndex) { PLHashEntry *entry; - int index; + unsigned int index; index = sftk_GetModuleIndex(slot->slotID); /* make sure the slotID for this module is valid */ if (moduleIndex != index) { - return CKR_SLOT_ID_INVALID; + return CKR_SLOT_ID_INVALID; } if (nscSlotList[index] == NULL) { - nscSlotListSize[index] = NSC_SLOT_LIST_BLOCK_SIZE; - nscSlotList[index] = (CK_SLOT_ID *) - PORT_ZAlloc(nscSlotListSize[index]*sizeof(CK_SLOT_ID)); - if (nscSlotList[index] == NULL) { - return CKR_HOST_MEMORY; - } + nscSlotListSize[index] = NSC_SLOT_LIST_BLOCK_SIZE; + nscSlotList[index] = (CK_SLOT_ID *) + PORT_ZAlloc(nscSlotListSize[index] * sizeof(CK_SLOT_ID)); + if (nscSlotList[index] == NULL) { + return CKR_HOST_MEMORY; + } } if (nscSlotCount[index] >= nscSlotListSize[index]) { - CK_SLOT_ID* oldNscSlotList = nscSlotList[index]; - CK_ULONG oldNscSlotListSize = nscSlotListSize[index]; - nscSlotListSize[index] += NSC_SLOT_LIST_BLOCK_SIZE; - nscSlotList[index] = (CK_SLOT_ID *) PORT_Realloc(oldNscSlotList, - nscSlotListSize[index]*sizeof(CK_SLOT_ID)); - if (nscSlotList[index] == NULL) { + CK_SLOT_ID *oldNscSlotList = nscSlotList[index]; + CK_ULONG oldNscSlotListSize = nscSlotListSize[index]; + nscSlotListSize[index] += NSC_SLOT_LIST_BLOCK_SIZE; + nscSlotList[index] = (CK_SLOT_ID *)PORT_Realloc(oldNscSlotList, + nscSlotListSize[index] * sizeof(CK_SLOT_ID)); + if (nscSlotList[index] == NULL) { nscSlotList[index] = oldNscSlotList; nscSlotListSize[index] = oldNscSlotListSize; return CKR_HOST_MEMORY; - } + } } if (nscSlotHashTable[index] == NULL) { - nscSlotHashTable[index] = PL_NewHashTable(64,sftk_HashNumber, - PL_CompareValues, PL_CompareValues, NULL, 0); - if (nscSlotHashTable[index] == NULL) { - return CKR_HOST_MEMORY; - } + nscSlotHashTable[index] = PL_NewHashTable(64, sftk_HashNumber, + PL_CompareValues, PL_CompareValues, NULL, 0); + if (nscSlotHashTable[index] == NULL) { + return CKR_HOST_MEMORY; + } } - entry = PL_HashTableAdd(nscSlotHashTable[index],(void *)slot->slotID,slot); + entry = PL_HashTableAdd(nscSlotHashTable[index], (void *)slot->slotID, slot); if (entry == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } slot->index = (nscSlotCount[index] & 0x7f) | ((index << 7) & 0x80); nscSlotList[index][nscSlotCount[index]++] = slot->slotID; @@ -2373,21 +2426,20 @@ sftk_RegisterSlot(SFTKSlot *slot, int moduleIndex) return CKR_OK; } - /* * ths function has all the common initialization that happens whenever we - * create a new slot or repurpose an old slot (only valid for slotID's 4 + * create a new slot or repurpose an old slot (only valid for slotID's 4 * and greater). * * things that are not reinitialized are: * slotID (can't change) - * slotDescription (can't change once defined) + * slotDescription (can't change once defined) * the locks and hash tables (difficult to change in running code, and * unnecessary. hash tables and list are cleared on shutdown, but they * are cleared in a 'friendly' way). * session and object ID counters -- so any old sessions and objects in the * application will get properly notified that the world has changed. - * + * * things that are reinitialized: * database (otherwise what would the point be;). * state variables related to databases. @@ -2398,8 +2450,8 @@ sftk_RegisterSlot(SFTKSlot *slot, int moduleIndex) * */ CK_RV -SFTK_SlotReInit(SFTKSlot *slot, char *configdir, char *updatedir, - char *updateID, sftk_token_parameters *params, int moduleIndex) +SFTK_SlotReInit(SFTKSlot *slot, char *configdir, char *updatedir, + char *updateID, sftk_token_parameters *params, int moduleIndex) { PRBool needLogin = !params->noKeyDB; CK_RV crv; @@ -2416,46 +2468,50 @@ SFTK_SlotReInit(SFTKSlot *slot, char *configdir, char *updatedir, slot->keyDB = NULL; slot->minimumPinLen = 0; slot->readOnly = params->readOnly; - sftk_setStringName(params->tokdes ? params->tokdes : - sftk_getDefTokName(slot->slotID), slot->tokDescription, - sizeof(slot->tokDescription),PR_TRUE); - sftk_setStringName(params->updtokdes ? params->updtokdes : " ", - slot->updateTokDescription, - sizeof(slot->updateTokDescription),PR_TRUE); + sftk_setStringName(params->tokdes ? params->tokdes : sftk_getDefTokName(slot->slotID), slot->tokDescription, + sizeof(slot->tokDescription), PR_TRUE); + sftk_setStringName(params->updtokdes ? params->updtokdes : " ", + slot->updateTokDescription, + sizeof(slot->updateTokDescription), PR_TRUE); if ((!params->noCertDB) || (!params->noKeyDB)) { - SFTKDBHandle * certHandle = NULL; - SFTKDBHandle *keyHandle = NULL; - crv = sftk_DBInit(params->configdir ? params->configdir : configdir, - params->certPrefix, params->keyPrefix, - params->updatedir ? params->updatedir : updatedir, - params->updCertPrefix, params->updKeyPrefix, - params->updateID ? params->updateID : updateID, - params->readOnly, params->noCertDB, params->noKeyDB, - params->forceOpen, - moduleIndex == NSC_FIPS_MODULE, - &certHandle, &keyHandle); - if (crv != CKR_OK) { - goto loser; - } - - slot->certDB = certHandle; - slot->keyDB = keyHandle; + SFTKDBHandle *certHandle = NULL; + SFTKDBHandle *keyHandle = NULL; + crv = sftk_DBInit(params->configdir ? params->configdir : configdir, + params->certPrefix, params->keyPrefix, + params->updatedir ? params->updatedir : updatedir, + params->updCertPrefix, params->updKeyPrefix, + params->updateID ? params->updateID : updateID, + params->readOnly, params->noCertDB, params->noKeyDB, + params->forceOpen, + moduleIndex == NSC_FIPS_MODULE, + &certHandle, &keyHandle); + if (crv != CKR_OK) { + goto loser; + } + + slot->certDB = certHandle; + slot->keyDB = keyHandle; } if (needLogin) { - /* if the data base is initialized with a null password,remember that */ - slot->needLogin = - (PRBool)!sftk_hasNullPassword(slot, slot->keyDB); - if ((params->minPW >= 0) && (params->minPW <= SFTK_MAX_PIN)) { - slot->minimumPinLen = params->minPW; - } - if ((slot->minimumPinLen == 0) && (params->pwRequired)) { - slot->minimumPinLen = 1; - } - if ((moduleIndex == NSC_FIPS_MODULE) && - (slot->minimumPinLen < FIPS_MIN_PIN)) { - slot->minimumPinLen = FIPS_MIN_PIN; - } + /* if the data base is initialized with a null password,remember that */ + slot->needLogin = + (PRBool)!sftk_hasNullPassword(slot, slot->keyDB); + if ((params->minPW >= 0) && (params->minPW <= SFTK_MAX_PIN)) { + slot->minimumPinLen = params->minPW; + } + if ((slot->minimumPinLen == 0) && (params->pwRequired)) { + slot->minimumPinLen = 1; + } + /* Make sure the pin len is set to the Minimum allowed value for fips + * when in FIPS mode. NOTE: we don't set it if the database has not + * been initialized yet so that we can init into level1 mode if needed + */ + if ((sftkdb_HasPasswordSet(slot->keyDB) == SECSuccess) && + (moduleIndex == NSC_FIPS_MODULE) && + (slot->minimumPinLen < FIPS_MIN_PIN)) { + slot->minimumPinLen = FIPS_MIN_PIN; + } } slot->present = PR_TRUE; @@ -2471,7 +2527,7 @@ loser: */ CK_RV SFTK_SlotInit(char *configdir, char *updatedir, char *updateID, - sftk_token_parameters *params, int moduleIndex) + sftk_token_parameters *params, int moduleIndex) { unsigned int i; CK_SLOT_ID slotID = params->slotID; @@ -2486,78 +2542,77 @@ SFTK_SlotInit(char *configdir, char *updatedir, char *updateID, slot = PORT_ZNew(SFTKSlot); if (slot == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } slot->optimizeSpace = params->optimizeSpace; if (slot->optimizeSpace) { - slot->sessObjHashSize = SPACE_SESSION_OBJECT_HASH_SIZE; - slot->sessHashSize = SPACE_SESSION_HASH_SIZE; - slot->numSessionLocks = 1; + slot->sessObjHashSize = SPACE_SESSION_OBJECT_HASH_SIZE; + slot->sessHashSize = SPACE_SESSION_HASH_SIZE; + slot->numSessionLocks = 1; } else { - slot->sessObjHashSize = TIME_SESSION_OBJECT_HASH_SIZE; - slot->sessHashSize = TIME_SESSION_HASH_SIZE; - slot->numSessionLocks = slot->sessHashSize/BUCKETS_PER_SESSION_LOCK; + slot->sessObjHashSize = TIME_SESSION_OBJECT_HASH_SIZE; + slot->sessHashSize = TIME_SESSION_HASH_SIZE; + slot->numSessionLocks = slot->sessHashSize / BUCKETS_PER_SESSION_LOCK; } - slot->sessionLockMask = slot->numSessionLocks-1; + slot->sessionLockMask = slot->numSessionLocks - 1; slot->slotLock = PZ_NewLock(nssILockSession); if (slot->slotLock == NULL) - goto mem_loser; + goto mem_loser; slot->sessionLock = PORT_ZNewArray(PZLock *, slot->numSessionLocks); if (slot->sessionLock == NULL) - goto mem_loser; - for (i=0; i < slot->numSessionLocks; i++) { + goto mem_loser; + for (i = 0; i < slot->numSessionLocks; i++) { slot->sessionLock[i] = PZ_NewLock(nssILockSession); - if (slot->sessionLock[i] == NULL) - goto mem_loser; + if (slot->sessionLock[i] == NULL) + goto mem_loser; } slot->objectLock = PZ_NewLock(nssILockObject); - if (slot->objectLock == NULL) - goto mem_loser; + if (slot->objectLock == NULL) + goto mem_loser; slot->pwCheckLock = PR_NewLock(); - if (slot->pwCheckLock == NULL) - goto mem_loser; + if (slot->pwCheckLock == NULL) + goto mem_loser; slot->head = PORT_ZNewArray(SFTKSession *, slot->sessHashSize); - if (slot->head == NULL) - goto mem_loser; + if (slot->head == NULL) + goto mem_loser; slot->sessObjHashTable = PORT_ZNewArray(SFTKObject *, slot->sessObjHashSize); - if (slot->sessObjHashTable == NULL) - goto mem_loser; - slot->tokObjHashTable = PL_NewHashTable(64,sftk_HashNumber,PL_CompareValues, - SECITEM_HashCompare, NULL, 0); - if (slot->tokObjHashTable == NULL) - goto mem_loser; + if (slot->sessObjHashTable == NULL) + goto mem_loser; + slot->tokObjHashTable = PL_NewHashTable(64, sftk_HashNumber, PL_CompareValues, + SECITEM_HashCompare, NULL, 0); + if (slot->tokObjHashTable == NULL) + goto mem_loser; slot->sessionIDCount = 0; slot->sessionObjectHandleCount = minSessionObjectHandle; slot->slotID = slotID; - sftk_setStringName(params->slotdes ? params->slotdes : - sftk_getDefSlotName(slotID), slot->slotDescription, - sizeof(slot->slotDescription), PR_TRUE); + sftk_setStringName(params->slotdes ? params->slotdes : sftk_getDefSlotName(slotID), slot->slotDescription, + sizeof(slot->slotDescription), PR_TRUE); /* call the reinit code to set everything that changes between token * init calls */ crv = SFTK_SlotReInit(slot, configdir, updatedir, updateID, - params, moduleIndex); + params, moduleIndex); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = sftk_RegisterSlot(slot, moduleIndex); if (crv != CKR_OK) { - goto loser; + goto loser; } return CKR_OK; mem_loser: crv = CKR_HOST_MEMORY; loser: - SFTK_DestroySlotData(slot); + SFTK_DestroySlotData(slot); return crv; } - -CK_RV sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout) +CK_RV +sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout) { SFTKSession *session; unsigned int i; @@ -2566,21 +2621,21 @@ CK_RV sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout) /* first log out the card */ /* special case - if we are in a middle of upgrade, we want to close the * sessions to fake a token removal to tell the upper level code we have - * switched from one database to another, but we don't want to - * explicity logout in case we can continue the upgrade with the - * existing password if possible. + * switched from one database to another, but we don't want to + * explicity logout in case we can continue the upgrade with the + * existing password if possible. */ if (logout) { - handle = sftk_getKeyDB(slot); - SKIP_AFTER_FORK(PZ_Lock(slot->slotLock)); - slot->isLoggedIn = PR_FALSE; - if (slot->needLogin && handle) { - sftkdb_ClearPassword(handle); - } - SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock)); - if (handle) { + handle = sftk_getKeyDB(slot); + SKIP_AFTER_FORK(PZ_Lock(slot->slotLock)); + slot->isLoggedIn = PR_FALSE; + if (slot->needLogin && handle) { + sftkdb_ClearPassword(handle); + } + SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock)); + if (handle) { sftk_freeDB(handle); - } + } } /* now close all the current sessions */ @@ -2588,31 +2643,33 @@ CK_RV sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout) * completes, some of those new sessions may or may not be closed by * NSC_CloseAllSessions... but any session running when this code starts * will guarrenteed be close, and no session will be partially closed */ - for (i=0; i < slot->sessHashSize; i++) { - PZLock *lock = SFTK_SESSION_LOCK(slot,i); - do { - SKIP_AFTER_FORK(PZ_Lock(lock)); - session = slot->head[i]; - /* hand deque */ - /* this duplicates function of NSC_close session functions, but - * because we know that we are freeing all the sessions, we can - * do more efficient processing */ - if (session) { - slot->head[i] = session->next; - if (session->next) session->next->prev = NULL; - session->next = session->prev = NULL; - SKIP_AFTER_FORK(PZ_Unlock(lock)); - SKIP_AFTER_FORK(PZ_Lock(slot->slotLock)); - --slot->sessionCount; - SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock)); - if (session->info.flags & CKF_RW_SESSION) { - (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount); - } - } else { - SKIP_AFTER_FORK(PZ_Unlock(lock)); - } - if (session) sftk_FreeSession(session); - } while (session != NULL); + for (i = 0; i < slot->sessHashSize; i++) { + PZLock *lock = SFTK_SESSION_LOCK(slot, i); + do { + SKIP_AFTER_FORK(PZ_Lock(lock)); + session = slot->head[i]; + /* hand deque */ + /* this duplicates function of NSC_close session functions, but + * because we know that we are freeing all the sessions, we can + * do more efficient processing */ + if (session) { + slot->head[i] = session->next; + if (session->next) + session->next->prev = NULL; + session->next = session->prev = NULL; + SKIP_AFTER_FORK(PZ_Unlock(lock)); + SKIP_AFTER_FORK(PZ_Lock(slot->slotLock)); + --slot->sessionCount; + SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock)); + if (session->info.flags & CKF_RW_SESSION) { + (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount); + } + } else { + SKIP_AFTER_FORK(PZ_Unlock(lock)); + } + if (session) + sftk_FreeSession(session); + } while (session != NULL); } return CKR_OK; } @@ -2631,7 +2688,7 @@ static void sftk_DBShutdown(SFTKSlot *slot) { SFTKDBHandle *certHandle; - SFTKDBHandle *keyHandle; + SFTKDBHandle *keyHandle; SKIP_AFTER_FORK(PZ_Lock(slot->slotLock)); certHandle = slot->certDB; slot->certDB = NULL; @@ -2639,10 +2696,10 @@ sftk_DBShutdown(SFTKSlot *slot) slot->keyDB = NULL; SKIP_AFTER_FORK(PZ_Unlock(slot->slotLock)); if (certHandle) { - sftk_freeDB(certHandle); + sftk_freeDB(certHandle); } if (keyHandle) { - sftk_freeDB(keyHandle); + sftk_freeDB(keyHandle); } } @@ -2656,15 +2713,15 @@ SFTK_ShutdownSlot(SFTKSlot *slot) * the sessHashSize variable guarentees we have all the session * mechanism set up */ if (slot->head) { - sftk_CloseAllSessions(slot, PR_TRUE); - } + sftk_CloseAllSessions(slot, PR_TRUE); + } /* clear all objects.. session objects are cleared as a result of * closing all the sessions. We just need to clear the token object - * cache. slot->tokObjHashTable guarentees we have the token + * cache. slot->tokObjHashTable guarentees we have the token * infrastructure set up. */ if (slot->tokObjHashTable) { - SFTK_ClearTokenKeyHashTable(slot); + SFTK_ClearTokenKeyHashTable(slot); } /* clear the slot description for the next guy */ @@ -2686,19 +2743,19 @@ SFTK_DestroySlotData(SFTKSlot *slot) SFTK_ShutdownSlot(slot); if (slot->tokObjHashTable) { - PL_HashTableDestroy(slot->tokObjHashTable); - slot->tokObjHashTable = NULL; + PL_HashTableDestroy(slot->tokObjHashTable); + slot->tokObjHashTable = NULL; } if (slot->sessObjHashTable) { - PORT_Free(slot->sessObjHashTable); - slot->sessObjHashTable = NULL; + PORT_Free(slot->sessObjHashTable); + slot->sessObjHashTable = NULL; } slot->sessObjHashSize = 0; if (slot->head) { - PORT_Free(slot->head); - slot->head = NULL; + PORT_Free(slot->head); + slot->head = NULL; } slot->sessHashSize = 0; @@ -2707,22 +2764,22 @@ SFTK_DestroySlotData(SFTKSlot *slot) SKIP_AFTER_FORK(PZ_DestroyLock(slot->slotLock)); slot->slotLock = NULL; if (slot->sessionLock) { - for (i=0; i < slot->numSessionLocks; i++) { - if (slot->sessionLock[i]) { - SKIP_AFTER_FORK(PZ_DestroyLock(slot->sessionLock[i])); - slot->sessionLock[i] = NULL; - } - } - PORT_Free(slot->sessionLock); - slot->sessionLock = NULL; + for (i = 0; i < slot->numSessionLocks; i++) { + if (slot->sessionLock[i]) { + SKIP_AFTER_FORK(PZ_DestroyLock(slot->sessionLock[i])); + slot->sessionLock[i] = NULL; + } + } + PORT_Free(slot->sessionLock); + slot->sessionLock = NULL; } if (slot->objectLock) { - SKIP_AFTER_FORK(PZ_DestroyLock(slot->objectLock)); - slot->objectLock = NULL; + SKIP_AFTER_FORK(PZ_DestroyLock(slot->objectLock)); + slot->objectLock = NULL; } if (slot->pwCheckLock) { - SKIP_AFTER_FORK(PR_DestroyLock(slot->pwCheckLock)); - slot->pwCheckLock = NULL; + SKIP_AFTER_FORK(PR_DestroyLock(slot->pwCheckLock)); + slot->pwCheckLock = NULL; } PORT_Free(slot); return CKR_OK; @@ -2732,105 +2789,121 @@ SFTK_DestroySlotData(SFTKSlot *slot) * handle the SECMOD.db */ char ** -NSC_ModuleDBFunc(unsigned long function,char *parameters, void *args) +NSC_ModuleDBFunc(unsigned long function, char *parameters, void *args) { char *secmod = NULL; char *appName = NULL; char *filename = NULL; NSSDBType dbType = NSS_DB_TYPE_NONE; PRBool rw; - static char *success="Success"; + static char *success = "Success"; char **rvstr = NULL; rvstr = NSSUTIL_DoModuleDBFunction(function, parameters, args); if (rvstr != NULL) { - return rvstr; + return rvstr; } if (PORT_GetError() != SEC_ERROR_LEGACY_DATABASE) { - return NULL; + return NULL; } - /* The legacy database uses the old dbm, which is only linked with the - * legacy DB handler, which is only callable from softoken */ + /* The legacy database uses the old dbm, which is only linked with the + * legacy DB handler, which is only callable from softoken */ secmod = _NSSUTIL_GetSecmodName(parameters, &dbType, &appName, - &filename, &rw); + &filename, &rw); switch (function) { - case SECMOD_MODULE_DB_FUNCTION_FIND: - if (secmod == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; - } - if (rw && (dbType != NSS_DB_TYPE_LEGACY) && - (dbType != NSS_DB_TYPE_MULTIACCESS)) { - /* if we get here, we are trying to update the local database */ - /* force data from the legacy DB */ - char *oldSecmod = NULL; - char *oldAppName = NULL; - char *oldFilename = NULL; - PRBool oldrw; - char **strings = NULL; - int i; - - dbType = NSS_DB_TYPE_LEGACY; - oldSecmod = _NSSUTIL_GetSecmodName(parameters,&dbType, &oldAppName, - &oldFilename, &oldrw); - strings = sftkdbCall_ReadSecmodDB(appName, oldFilename, oldSecmod, - (char *)parameters, oldrw); - if (strings) { - /* write out the strings */ - for (i=0; strings[i]; i++) { - NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD, - parameters, strings[i]); - } - sftkdbCall_ReleaseSecmodDBData(oldAppName,oldFilename,oldSecmod, - (char **)strings,oldrw); - } else { - /* write out a dummy record */ - NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD, - parameters, " "); - } - if (oldSecmod) { PR_smprintf_free(oldSecmod); } - if (oldAppName) { PORT_Free(oldAppName); } - if (oldFilename) { PORT_Free(oldFilename); } - rvstr = NSSUTIL_DoModuleDBFunction(function, parameters, args); - break; - } - rvstr = sftkdbCall_ReadSecmodDB(appName,filename,secmod, - (char *)parameters,rw); - break; - case SECMOD_MODULE_DB_FUNCTION_ADD: - if (secmod == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; - } - rvstr = (sftkdbCall_AddSecmodDB(appName,filename,secmod, - (char *)args,rw) == SECSuccess) ? &success: NULL; - break; - case SECMOD_MODULE_DB_FUNCTION_DEL: - if (secmod == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - goto loser; - } - rvstr = (sftkdbCall_DeleteSecmodDB(appName,filename,secmod, - (char *)args,rw) == SECSuccess) ? &success: NULL; - break; - case SECMOD_MODULE_DB_FUNCTION_RELEASE: - rvstr = (sftkdbCall_ReleaseSecmodDBData(appName,filename,secmod, - (char **)args,rw) == SECSuccess) ? &success: NULL; - break; + case SECMOD_MODULE_DB_FUNCTION_FIND: + if (secmod == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + if (rw && (dbType != NSS_DB_TYPE_LEGACY) && + (dbType != NSS_DB_TYPE_MULTIACCESS)) { + /* if we get here, we are trying to update the local database */ + /* force data from the legacy DB */ + char *oldSecmod = NULL; + char *oldAppName = NULL; + char *oldFilename = NULL; + PRBool oldrw; + char **strings = NULL; + int i; + + dbType = NSS_DB_TYPE_LEGACY; + oldSecmod = _NSSUTIL_GetSecmodName(parameters, &dbType, &oldAppName, + &oldFilename, &oldrw); + strings = sftkdbCall_ReadSecmodDB(appName, oldFilename, oldSecmod, + (char *)parameters, oldrw); + if (strings) { + /* write out the strings */ + for (i = 0; strings[i]; i++) { + NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD, + parameters, strings[i]); + } + sftkdbCall_ReleaseSecmodDBData(oldAppName, oldFilename, oldSecmod, + (char **)strings, oldrw); + } else { + /* write out a dummy record */ + NSSUTIL_DoModuleDBFunction(SECMOD_MODULE_DB_FUNCTION_ADD, + parameters, " "); + } + if (oldSecmod) { + PR_smprintf_free(oldSecmod); + } + if (oldAppName) { + PORT_Free(oldAppName); + } + if (oldFilename) { + PORT_Free(oldFilename); + } + rvstr = NSSUTIL_DoModuleDBFunction(function, parameters, args); + break; + } + rvstr = sftkdbCall_ReadSecmodDB(appName, filename, secmod, + (char *)parameters, rw); + break; + case SECMOD_MODULE_DB_FUNCTION_ADD: + if (secmod == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + rvstr = (sftkdbCall_AddSecmodDB(appName, filename, secmod, + (char *)args, rw) == SECSuccess) + ? &success + : NULL; + break; + case SECMOD_MODULE_DB_FUNCTION_DEL: + if (secmod == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + rvstr = (sftkdbCall_DeleteSecmodDB(appName, filename, secmod, + (char *)args, rw) == SECSuccess) + ? &success + : NULL; + break; + case SECMOD_MODULE_DB_FUNCTION_RELEASE: + rvstr = (sftkdbCall_ReleaseSecmodDBData(appName, filename, secmod, + (char **)args, rw) == SECSuccess) + ? &success + : NULL; + break; } loser: - if (secmod) PR_smprintf_free(secmod); - if (appName) PORT_Free(appName); - if (filename) PORT_Free(filename); + if (secmod) + PR_smprintf_free(secmod); + if (appName) + PORT_Free(appName); + if (filename) + PORT_Free(filename); return rvstr; } -static void nscFreeAllSlots(int moduleIndex) +static void +nscFreeAllSlots(int moduleIndex) { /* free all the slots */ SFTKSlot *slot = NULL; @@ -2838,82 +2911,84 @@ static void nscFreeAllSlots(int moduleIndex) int i; if (nscSlotList[moduleIndex]) { - CK_ULONG tmpSlotCount = nscSlotCount[moduleIndex]; - CK_SLOT_ID_PTR tmpSlotList = nscSlotList[moduleIndex]; - PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex]; - - /* first close all the session */ - for (i=0; i < (int) tmpSlotCount; i++) { - slotID = tmpSlotList[i]; - (void) NSC_CloseAllSessions(slotID); - } - - /* now clear out the statics */ - nscSlotList[moduleIndex] = NULL; - nscSlotCount[moduleIndex] = 0; - nscSlotHashTable[moduleIndex] = NULL; - nscSlotListSize[moduleIndex] = 0; - - for (i=0; i < (int) tmpSlotCount; i++) { - slotID = tmpSlotList[i]; - slot = (SFTKSlot *) - PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); - PORT_Assert(slot); - if (!slot) continue; - SFTK_DestroySlotData(slot); - PL_HashTableRemove(tmpSlotHashTable, (void *)slotID); - } - PORT_Free(tmpSlotList); - PL_HashTableDestroy(tmpSlotHashTable); + CK_ULONG tmpSlotCount = nscSlotCount[moduleIndex]; + CK_SLOT_ID_PTR tmpSlotList = nscSlotList[moduleIndex]; + PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex]; + + /* first close all the session */ + for (i = 0; i < (int)tmpSlotCount; i++) { + slotID = tmpSlotList[i]; + (void)NSC_CloseAllSessions(slotID); + } + + /* now clear out the statics */ + nscSlotList[moduleIndex] = NULL; + nscSlotCount[moduleIndex] = 0; + nscSlotHashTable[moduleIndex] = NULL; + nscSlotListSize[moduleIndex] = 0; + + for (i = 0; i < (int)tmpSlotCount; i++) { + slotID = tmpSlotList[i]; + slot = (SFTKSlot *) + PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); + PORT_Assert(slot); + if (!slot) + continue; + SFTK_DestroySlotData(slot); + PL_HashTableRemove(tmpSlotHashTable, (void *)slotID); + } + PORT_Free(tmpSlotList); + PL_HashTableDestroy(tmpSlotHashTable); } } static void sftk_closePeer(PRBool isFIPS) { - CK_SLOT_ID slotID = isFIPS ? PRIVATE_KEY_SLOT_ID: FIPS_SLOT_ID; + CK_SLOT_ID slotID = isFIPS ? PRIVATE_KEY_SLOT_ID : FIPS_SLOT_ID; SFTKSlot *slot; - int moduleIndex = isFIPS? NSC_NON_FIPS_MODULE : NSC_FIPS_MODULE; + int moduleIndex = isFIPS ? NSC_NON_FIPS_MODULE : NSC_FIPS_MODULE; PLHashTable *tmpSlotHashTable = nscSlotHashTable[moduleIndex]; - slot = (SFTKSlot *) PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); + slot = (SFTKSlot *)PL_HashTableLookup(tmpSlotHashTable, (void *)slotID); if (slot == NULL) { - return; + return; } sftk_DBShutdown(slot); return; } /* NSC_Initialize initializes the Cryptoki library. */ -CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS) +CK_RV +nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS) { CK_RV crv = CKR_OK; SECStatus rv; - CK_C_INITIALIZE_ARGS *init_args = (CK_C_INITIALIZE_ARGS *) pReserved; + CK_C_INITIALIZE_ARGS *init_args = (CK_C_INITIALIZE_ARGS *)pReserved; int i; - int moduleIndex = isFIPS? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE; + int moduleIndex = isFIPS ? NSC_FIPS_MODULE : NSC_NON_FIPS_MODULE; if (isFIPS) { - loginWaitTime = PR_SecondsToInterval(1); + loginWaitTime = PR_SecondsToInterval(1); } ENABLE_FORK_CHECK(); rv = SECOID_Init(); if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - return crv; + crv = CKR_DEVICE_ERROR; + return crv; } - rv = RNG_RNGInit(); /* initialize random number generator */ + rv = RNG_RNGInit(); /* initialize random number generator */ if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - return crv; + crv = CKR_DEVICE_ERROR; + return crv; } - rv = BL_Init(); /* initialize freebl engine */ + rv = BL_Init(); /* initialize freebl engine */ if (rv != SECSuccess) { - crv = CKR_DEVICE_ERROR; - return crv; + crv = CKR_DEVICE_ERROR; + return crv; } /* NOTE: @@ -2922,7 +2997,7 @@ CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS) * off from the rest on NSS. */ - /* initialize the key and cert db's */ + /* initialize the key and cert db's */ if (init_args && (!(init_args->flags & CKF_OS_LOCKING_OK))) { if (init_args->CreateMutex && init_args->DestroyMutex && init_args->LockMutex && init_args->UnlockMutex) { @@ -2943,44 +3018,43 @@ CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS) } crv = CKR_ARGUMENTS_BAD; if ((init_args && init_args->LibraryParameters)) { - sftk_parameters paramStrings; - - crv = sftk_parseParameters - ((char *)init_args->LibraryParameters, ¶mStrings, isFIPS); - if (crv != CKR_OK) { - return crv; - } - crv = sftk_configure(paramStrings.man, paramStrings.libdes); + sftk_parameters paramStrings; + + crv = sftk_parseParameters((char *)init_args->LibraryParameters, ¶mStrings, isFIPS); + if (crv != CKR_OK) { + return crv; + } + crv = sftk_configure(paramStrings.man, paramStrings.libdes); if (crv != CKR_OK) { - goto loser; - } - - /* if we have a peer already open, have him close his DB's so we - * don't clobber each other. */ - if ((isFIPS && nsc_init) || (!isFIPS && nsf_init)) { - sftk_closePeer(isFIPS); - if (sftk_audit_enabled) { - if (isFIPS && nsc_init) { - sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE, - "enabled FIPS mode"); - } else { - sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE, - "disabled FIPS mode"); - } - } - } - - for (i=0; i < paramStrings.token_count; i++) { - crv = SFTK_SlotInit(paramStrings.configdir, - paramStrings.updatedir, paramStrings.updateID, - ¶mStrings.tokens[i], moduleIndex); - if (crv != CKR_OK) { + goto loser; + } + + /* if we have a peer already open, have him close his DB's so we + * don't clobber each other. */ + if ((isFIPS && nsc_init) || (!isFIPS && nsf_init)) { + sftk_closePeer(isFIPS); + if (sftk_audit_enabled) { + if (isFIPS && nsc_init) { + sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE, + "enabled FIPS mode"); + } else { + sftk_LogAuditMessage(NSS_AUDIT_INFO, NSS_AUDIT_FIPS_STATE, + "disabled FIPS mode"); + } + } + } + + for (i = 0; i < paramStrings.token_count; i++) { + crv = SFTK_SlotInit(paramStrings.configdir, + paramStrings.updatedir, paramStrings.updateID, + ¶mStrings.tokens[i], moduleIndex); + if (crv != CKR_OK) { nscFreeAllSlots(moduleIndex); break; } - } -loser: - sftk_freeParams(¶mStrings); + } + loser: + sftk_freeParams(¶mStrings); } if (CKR_OK == crv) { sftk_InitFreeLists(); @@ -3000,7 +3074,7 @@ loser: if (rv > 0 && rv < sizeof(buf)) { if (2 == sscanf(buf, "%d.%d", &major, &minor)) { /* Are we on Solaris 10 or greater ? */ - if (major >5 || (5 == major && minor >= 10)) { + if (major > 5 || (5 == major && minor >= 10)) { /* we are safe to use pthread_atfork */ usePthread_atfork = PR_TRUE; } @@ -3024,24 +3098,25 @@ loser: return crv; } -CK_RV NSC_Initialize(CK_VOID_PTR pReserved) +CK_RV +NSC_Initialize(CK_VOID_PTR pReserved) { CK_RV crv; - + sftk_ForkReset(pReserved, &crv); if (nsc_init) { - return CKR_CRYPTOKI_ALREADY_INITIALIZED; + return CKR_CRYPTOKI_ALREADY_INITIALIZED; } - crv = nsc_CommonInitialize(pReserved,PR_FALSE); - nsc_init = (PRBool) (crv == CKR_OK); + crv = nsc_CommonInitialize(pReserved, PR_FALSE); + nsc_init = (PRBool)(crv == CKR_OK); return crv; } - -/* NSC_Finalize indicates that an application is done with the +/* NSC_Finalize indicates that an application is done with the * Cryptoki library.*/ -CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) +CK_RV +nsc_CommonFinalize(CK_VOID_PTR pReserved, PRBool isFIPS) { /* propagate the fork status to freebl and util */ BL_SetForkState(parentForkedAfterC_Initialize); @@ -3051,10 +3126,10 @@ CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) /* don't muck with the globals if our peer is still initialized */ if (isFIPS && nsc_init) { - return CKR_OK; + return CKR_OK; } if (!isFIPS && nsf_init) { - return CKR_OK; + return CKR_OK; } sftk_CleanupFreeLists(); @@ -3065,11 +3140,11 @@ CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) /* tell freeBL to clean up after itself */ BL_Cleanup(); - + /* reset fork status in freebl. We must do this before BL_Unload so that * this call doesn't force freebl to be reloaded. */ BL_SetForkState(PR_FALSE); - + /* unload freeBL shared library from memory. This may only decrement the * OS refcount if it's been loaded multiple times, eg. by libssl */ BL_Unload(); @@ -3091,7 +3166,7 @@ CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) } #elif defined(CHECK_FORK_GETPID) myPid = 0; /* allow reinitialization */ -#elif defined (CHECK_FORK_PTHREAD) +#elif defined(CHECK_FORK_PTHREAD) forked = PR_FALSE; /* allow reinitialization */ #endif return CKR_OK; @@ -3099,7 +3174,8 @@ CK_RV nsc_CommonFinalize (CK_VOID_PTR pReserved, PRBool isFIPS) /* Hard-reset the entire softoken PKCS#11 module if the parent process forked * while it was initialized. */ -PRBool sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV* crv) +PRBool +sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV *crv) { #ifndef NO_FORK_CHECK if (PARENT_FORKED()) { @@ -3123,9 +3199,10 @@ PRBool sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV* crv) return PR_FALSE; } -/* NSC_Finalize indicates that an application is done with the +/* NSC_Finalize indicates that an application is done with the * Cryptoki library.*/ -CK_RV NSC_Finalize (CK_VOID_PTR pReserved) +CK_RV +NSC_Finalize(CK_VOID_PTR pReserved) { CK_RV crv; @@ -3138,7 +3215,7 @@ CK_RV NSC_Finalize (CK_VOID_PTR pReserved) return CKR_OK; } - crv = nsc_CommonFinalize (pReserved, PR_FALSE); + crv = nsc_CommonFinalize(pReserved, PR_FALSE); nsc_init = (PRBool) !(crv == CKR_OK); @@ -3148,74 +3225,78 @@ CK_RV NSC_Finalize (CK_VOID_PTR pReserved) extern const char __nss_softokn_version[]; /* NSC_GetInfo returns general information about Cryptoki. */ -CK_RV NSC_GetInfo(CK_INFO_PTR pInfo) +CK_RV +NSC_GetInfo(CK_INFO_PTR pInfo) { #define NSS_VERSION_VARIABLE __nss_softokn_version #include "verref.h" CHECK_FORK(); - + pInfo->cryptokiVersion.major = 2; pInfo->cryptokiVersion.minor = 20; - PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32); + PORT_Memcpy(pInfo->manufacturerID, manufacturerID, 32); pInfo->libraryVersion.major = SOFTOKEN_VMAJOR; pInfo->libraryVersion.minor = SOFTOKEN_VMINOR; - PORT_Memcpy(pInfo->libraryDescription,libraryDescription,32); + PORT_Memcpy(pInfo->libraryDescription, libraryDescription, 32); pInfo->flags = 0; return CKR_OK; } - /* NSC_GetSlotList obtains a list of slots in the system. */ -CK_RV nsc_CommonGetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex) +CK_RV +nsc_CommonGetSlotList(CK_BBOOL tokenPresent, + CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex) { *pulCount = nscSlotCount[moduleIndex]; if (pSlotList != NULL) { - PORT_Memcpy(pSlotList,nscSlotList[moduleIndex], - nscSlotCount[moduleIndex]*sizeof(CK_SLOT_ID)); + PORT_Memcpy(pSlotList, nscSlotList[moduleIndex], + nscSlotCount[moduleIndex] * sizeof(CK_SLOT_ID)); } return CKR_OK; } /* NSC_GetSlotList obtains a list of slots in the system. */ -CK_RV NSC_GetSlotList(CK_BBOOL tokenPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) +CK_RV +NSC_GetSlotList(CK_BBOOL tokenPresent, + CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { CHECK_FORK(); - return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount, - NSC_NON_FIPS_MODULE); + return nsc_CommonGetSlotList(tokenPresent, pSlotList, pulCount, + NSC_NON_FIPS_MODULE); } - + /* NSC_GetSlotInfo obtains information about a particular slot in the system. */ -CK_RV NSC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) +CK_RV +NSC_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { SFTKSlot *slot = sftk_SlotFromID(slotID, PR_TRUE); CHECK_FORK(); - if (slot == NULL) return CKR_SLOT_ID_INVALID; + if (slot == NULL) + return CKR_SLOT_ID_INVALID; - PORT_Memcpy(pInfo->manufacturerID,manufacturerID, - sizeof(pInfo->manufacturerID)); - PORT_Memcpy(pInfo->slotDescription,slot->slotDescription, - sizeof(pInfo->slotDescription)); + PORT_Memcpy(pInfo->manufacturerID, manufacturerID, + sizeof(pInfo->manufacturerID)); + PORT_Memcpy(pInfo->slotDescription, slot->slotDescription, + sizeof(pInfo->slotDescription)); pInfo->flags = (slot->present) ? CKF_TOKEN_PRESENT : 0; /* all user defined slots are defined as removable */ if (slotID >= SFTK_MIN_USER_SLOT_ID) { - pInfo->flags |= CKF_REMOVABLE_DEVICE; + pInfo->flags |= CKF_REMOVABLE_DEVICE; } else { - /* In the case where we are doing a merge update, we need - * the DB slot to be removable so the token name can change - * appropriately. */ - SFTKDBHandle *handle = sftk_getKeyDB(slot); - if (handle) { - if (sftkdb_InUpdateMerge(handle)) { - pInfo->flags |= CKF_REMOVABLE_DEVICE; - } + /* In the case where we are doing a merge update, we need + * the DB slot to be removable so the token name can change + * appropriately. */ + SFTKDBHandle *handle = sftk_getKeyDB(slot); + if (handle) { + if (sftkdb_InUpdateMerge(handle)) { + pInfo->flags |= CKF_REMOVABLE_DEVICE; + } sftk_freeDB(handle); - } + } } /* ok we really should read it out of the keydb file. */ @@ -3235,7 +3316,7 @@ static PRBool sftk_checkNeedLogin(SFTKSlot *slot, SFTKDBHandle *keyHandle) { if (sftkdb_PWCached(keyHandle) == SECSuccess) { - return slot->needLogin; + return slot->needLogin; } slot->needLogin = (PRBool)!sftk_hasNullPassword(slot, keyHandle); return (slot->needLogin); @@ -3245,100 +3326,103 @@ static PRBool sftk_isBlank(const char *s, int len) { int i; - for (i=0; i < len; i++) { - if (s[i] != ' ') { - return PR_FALSE; - } + for (i = 0; i < len; i++) { + if (s[i] != ' ') { + return PR_FALSE; + } } return PR_TRUE; } -/* NSC_GetTokenInfo obtains information about a particular token in +/* NSC_GetTokenInfo obtains information about a particular token in * the system. */ -CK_RV NSC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) +CK_RV +NSC_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) { SFTKSlot *slot; SFTKDBHandle *handle; CHECK_FORK(); - - if (!nsc_init && !nsf_init) return CKR_CRYPTOKI_NOT_INITIALIZED; + + if (!nsc_init && !nsf_init) + return CKR_CRYPTOKI_NOT_INITIALIZED; slot = sftk_SlotFromID(slotID, PR_FALSE); - if (slot == NULL) return CKR_SLOT_ID_INVALID; + if (slot == NULL) + return CKR_SLOT_ID_INVALID; - PORT_Memcpy(pInfo->manufacturerID,manufacturerID,32); - PORT_Memcpy(pInfo->model,"NSS 3 ",16); - PORT_Memcpy(pInfo->serialNumber,"0000000000000000",16); - PORT_Memcpy(pInfo->utcTime,"0000000000000000",16); + PORT_Memcpy(pInfo->manufacturerID, manufacturerID, 32); + PORT_Memcpy(pInfo->model, "NSS 3 ", 16); + PORT_Memcpy(pInfo->serialNumber, "0000000000000000", 16); + PORT_Memcpy(pInfo->utcTime, "0000000000000000", 16); pInfo->ulMaxSessionCount = 0; /* arbitrarily large */ pInfo->ulSessionCount = slot->sessionCount; pInfo->ulMaxRwSessionCount = 0; /* arbitarily large */ pInfo->ulRwSessionCount = slot->rwSessionCount; pInfo->firmwareVersion.major = 0; pInfo->firmwareVersion.minor = 0; - PORT_Memcpy(pInfo->label,slot->tokDescription,sizeof(pInfo->label)); + PORT_Memcpy(pInfo->label, slot->tokDescription, sizeof(pInfo->label)); handle = sftk_getKeyDB(slot); pInfo->flags = CKF_RNG | CKF_DUAL_CRYPTO_OPERATIONS; if (handle == NULL) { - pInfo->flags |= CKF_WRITE_PROTECTED; - pInfo->ulMaxPinLen = 0; - pInfo->ulMinPinLen = 0; - pInfo->ulTotalPublicMemory = 0; - pInfo->ulFreePublicMemory = 0; - pInfo->ulTotalPrivateMemory = 0; - pInfo->ulFreePrivateMemory = 0; - pInfo->hardwareVersion.major = 4; - pInfo->hardwareVersion.minor = 0; + pInfo->flags |= CKF_WRITE_PROTECTED; + pInfo->ulMaxPinLen = 0; + pInfo->ulMinPinLen = 0; + pInfo->ulTotalPublicMemory = 0; + pInfo->ulFreePublicMemory = 0; + pInfo->ulTotalPrivateMemory = 0; + pInfo->ulFreePrivateMemory = 0; + pInfo->hardwareVersion.major = 4; + pInfo->hardwareVersion.minor = 0; } else { - /* - * we have three possible states which we may be in: - * (1) No DB password has been initialized. This also means we - * have no keys in the key db. - * (2) Password initialized to NULL. This means we have keys, but - * the user has chosen not use a password. - * (3) Finally we have an initialized password whicn is not NULL, and - * we will need to prompt for it. - */ - if (sftkdb_HasPasswordSet(handle) == SECFailure) { - pInfo->flags |= CKF_LOGIN_REQUIRED; - } else if (!sftk_checkNeedLogin(slot,handle)) { - pInfo->flags |= CKF_USER_PIN_INITIALIZED; - } else { - pInfo->flags |= CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED; - /* - * if we are doing a merge style update, and we need to get the password - * of our source database (the database we are updating from), make sure we - * return a token name that will match the database we are prompting for. - */ - if (sftkdb_NeedUpdateDBPassword(handle)) { - /* if we have an update tok description, use it. otherwise - * use the updateID for this database */ - if (!sftk_isBlank(slot->updateTokDescription, - sizeof(pInfo->label))) { - PORT_Memcpy(pInfo->label,slot->updateTokDescription, - sizeof(pInfo->label)); - } else { - /* build from updateID */ - const char *updateID = sftkdb_GetUpdateID(handle); - if (updateID) { - sftk_setStringName(updateID, (char *)pInfo->label, - sizeof(pInfo->label), PR_FALSE); - } - } - } - } - pInfo->ulMaxPinLen = SFTK_MAX_PIN; - pInfo->ulMinPinLen = (CK_ULONG)slot->minimumPinLen; - pInfo->ulTotalPublicMemory = 1; - pInfo->ulFreePublicMemory = 1; - pInfo->ulTotalPrivateMemory = 1; - pInfo->ulFreePrivateMemory = 1; + /* + * we have three possible states which we may be in: + * (1) No DB password has been initialized. This also means we + * have no keys in the key db. + * (2) Password initialized to NULL. This means we have keys, but + * the user has chosen not use a password. + * (3) Finally we have an initialized password whicn is not NULL, and + * we will need to prompt for it. + */ + if (sftkdb_HasPasswordSet(handle) == SECFailure) { + pInfo->flags |= CKF_LOGIN_REQUIRED; + } else if (!sftk_checkNeedLogin(slot, handle)) { + pInfo->flags |= CKF_USER_PIN_INITIALIZED; + } else { + pInfo->flags |= CKF_LOGIN_REQUIRED | CKF_USER_PIN_INITIALIZED; + /* + * if we are doing a merge style update, and we need to get the password + * of our source database (the database we are updating from), make sure we + * return a token name that will match the database we are prompting for. + */ + if (sftkdb_NeedUpdateDBPassword(handle)) { + /* if we have an update tok description, use it. otherwise + * use the updateID for this database */ + if (!sftk_isBlank(slot->updateTokDescription, + sizeof(pInfo->label))) { + PORT_Memcpy(pInfo->label, slot->updateTokDescription, + sizeof(pInfo->label)); + } else { + /* build from updateID */ + const char *updateID = sftkdb_GetUpdateID(handle); + if (updateID) { + sftk_setStringName(updateID, (char *)pInfo->label, + sizeof(pInfo->label), PR_FALSE); + } + } + } + } + pInfo->ulMaxPinLen = SFTK_MAX_PIN; + pInfo->ulMinPinLen = (CK_ULONG)slot->minimumPinLen; + pInfo->ulTotalPublicMemory = 1; + pInfo->ulFreePublicMemory = 1; + pInfo->ulTotalPrivateMemory = 1; + pInfo->ulFreePrivateMemory = 1; #ifdef SHDB_FIXME - pInfo->hardwareVersion.major = CERT_DB_FILE_VERSION; - pInfo->hardwareVersion.minor = handle->version; + pInfo->hardwareVersion.major = CERT_DB_FILE_VERSION; + pInfo->hardwareVersion.minor = handle->version; #else - pInfo->hardwareVersion.major = 0; - pInfo->hardwareVersion.minor = 0; + pInfo->hardwareVersion.major = 0; + pInfo->hardwareVersion.minor = 0; #endif sftk_freeDB(handle); } @@ -3351,107 +3435,129 @@ CK_RV NSC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) * 1 1 1 */ if (!(pInfo->flags & CKF_LOGIN_REQUIRED) || - (pInfo->flags & CKF_USER_PIN_INITIALIZED)) { - pInfo->flags |= CKF_TOKEN_INITIALIZED; + (pInfo->flags & CKF_USER_PIN_INITIALIZED)) { + pInfo->flags |= CKF_TOKEN_INITIALIZED; } return CKR_OK; } -/* NSC_GetMechanismList obtains a list of mechanism types +/* NSC_GetMechanismList obtains a list of mechanism types * supported by a token. */ -CK_RV NSC_GetMechanismList(CK_SLOT_ID slotID, - CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) +CK_RV +NSC_GetMechanismList(CK_SLOT_ID slotID, + CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { CK_ULONG i; CHECK_FORK(); switch (slotID) { - /* default: */ - case NETSCAPE_SLOT_ID: - *pulCount = mechanismCount; - if (pMechanismList != NULL) { - for (i=0; i < mechanismCount; i++) { - pMechanismList[i] = mechanisms[i].type; - } - } - break; - default: - *pulCount = 0; - for (i=0; i < mechanismCount; i++) { - if (mechanisms[i].privkey) { - (*pulCount)++; - if (pMechanismList != NULL) { - *pMechanismList++ = mechanisms[i].type; - } - } - } - break; + /* default: */ + case NETSCAPE_SLOT_ID: + *pulCount = mechanismCount; + if (pMechanismList != NULL) { + for (i = 0; i < mechanismCount; i++) { + pMechanismList[i] = mechanisms[i].type; + } + } + break; + default: + *pulCount = 0; + for (i = 0; i < mechanismCount; i++) { + if (mechanisms[i].privkey) { + (*pulCount)++; + if (pMechanismList != NULL) { + *pMechanismList++ = mechanisms[i].type; + } + } + } + break; } return CKR_OK; } - -/* NSC_GetMechanismInfo obtains information about a particular mechanism +/* NSC_GetMechanismInfo obtains information about a particular mechanism * possibly supported by a token. */ -CK_RV NSC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, - CK_MECHANISM_INFO_PTR pInfo) +CK_RV +NSC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, + CK_MECHANISM_INFO_PTR pInfo) { PRBool isPrivateKey; CK_ULONG i; CHECK_FORK(); - + switch (slotID) { - case NETSCAPE_SLOT_ID: - isPrivateKey = PR_FALSE; - break; - default: - isPrivateKey = PR_TRUE; - break; - } - for (i=0; i < mechanismCount; i++) { + case NETSCAPE_SLOT_ID: + isPrivateKey = PR_FALSE; + break; + default: + isPrivateKey = PR_TRUE; + break; + } + for (i = 0; i < mechanismCount; i++) { if (type == mechanisms[i].type) { - if (isPrivateKey && !mechanisms[i].privkey) { - return CKR_MECHANISM_INVALID; - } - PORT_Memcpy(pInfo,&mechanisms[i].info, sizeof(CK_MECHANISM_INFO)); - return CKR_OK; - } + if (isPrivateKey && !mechanisms[i].privkey) { + return CKR_MECHANISM_INVALID; + } + PORT_Memcpy(pInfo, &mechanisms[i].info, sizeof(CK_MECHANISM_INFO)); + return CKR_OK; + } } return CKR_MECHANISM_INVALID; } -CK_RV sftk_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op) +CK_RV +sftk_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op) { CK_ULONG i; CK_FLAGS flags; switch (op) { - case CKA_ENCRYPT: flags = CKF_ENCRYPT; break; - case CKA_DECRYPT: flags = CKF_DECRYPT; break; - case CKA_WRAP: flags = CKF_WRAP; break; - case CKA_UNWRAP: flags = CKF_UNWRAP; break; - case CKA_SIGN: flags = CKF_SIGN; break; - case CKA_SIGN_RECOVER: flags = CKF_SIGN_RECOVER; break; - case CKA_VERIFY: flags = CKF_VERIFY; break; - case CKA_VERIFY_RECOVER: flags = CKF_VERIFY_RECOVER; break; - case CKA_DERIVE: flags = CKF_DERIVE; break; - default: - return CKR_ARGUMENTS_BAD; - } - for (i=0; i < mechanismCount; i++) { + case CKA_ENCRYPT: + flags = CKF_ENCRYPT; + break; + case CKA_DECRYPT: + flags = CKF_DECRYPT; + break; + case CKA_WRAP: + flags = CKF_WRAP; + break; + case CKA_UNWRAP: + flags = CKF_UNWRAP; + break; + case CKA_SIGN: + flags = CKF_SIGN; + break; + case CKA_SIGN_RECOVER: + flags = CKF_SIGN_RECOVER; + break; + case CKA_VERIFY: + flags = CKF_VERIFY; + break; + case CKA_VERIFY_RECOVER: + flags = CKF_VERIFY_RECOVER; + break; + case CKA_DERIVE: + flags = CKF_DERIVE; + break; + default: + return CKR_ARGUMENTS_BAD; + } + for (i = 0; i < mechanismCount; i++) { if (type == mechanisms[i].type) { - return (flags & mechanisms[i].info.flags) ? CKR_OK - : CKR_MECHANISM_INVALID; - } + return (flags & mechanisms[i].info.flags) ? CKR_OK + : CKR_MECHANISM_INVALID; + } } return CKR_MECHANISM_INVALID; } /* NSC_InitToken initializes a token. */ -CK_RV NSC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, - CK_ULONG ulPinLen,CK_CHAR_PTR pLabel) { +CK_RV +NSC_InitToken(CK_SLOT_ID slotID, CK_CHAR_PTR pPin, + CK_ULONG ulPinLen, CK_CHAR_PTR pLabel) +{ SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE); SFTKDBHandle *handle; SFTKDBHandle *certHandle; @@ -3461,33 +3567,36 @@ CK_RV NSC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, CHECK_FORK(); - if (slot == NULL) return CKR_SLOT_ID_INVALID; + if (slot == NULL) + return CKR_SLOT_ID_INVALID; /* don't initialize the database if we aren't talking to a token * that uses the key database. */ if (slotID == NETSCAPE_SLOT_ID) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - /* first, delete all our loaded key and cert objects from our + /* first, delete all our loaded key and cert objects from our * internal list. */ PZ_Lock(slot->objectLock); - for (i=0; i < slot->sessObjHashSize; i++) { - do { - object = slot->sessObjHashTable[i]; - /* hand deque */ - /* this duplicates function of NSC_close session functions, but - * because we know that we are freeing all the sessions, we can - * do more efficient processing */ - if (object) { - slot->sessObjHashTable[i] = object->next; - - if (object->next) object->next->prev = NULL; - object->next = object->prev = NULL; - } - if (object) sftk_FreeObject(object); - } while (object != NULL); + for (i = 0; i < slot->sessObjHashSize; i++) { + do { + object = slot->sessObjHashTable[i]; + /* hand deque */ + /* this duplicates function of NSC_close session functions, but + * because we know that we are freeing all the sessions, we can + * do more efficient processing */ + if (object) { + slot->sessObjHashTable[i] = object->next; + + if (object->next) + object->next->prev = NULL; + object->next = object->prev = NULL; + } + if (object) + sftk_FreeObject(object); + } while (object != NULL); } slot->DB_loaded = PR_FALSE; PZ_Unlock(slot->objectLock); @@ -3495,59 +3604,59 @@ CK_RV NSC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin, /* then clear out the key database */ handle = sftk_getKeyDB(slot); if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } rv = sftkdb_ResetKeyDB(handle); sftk_freeDB(handle); if (rv != SECSuccess) { - return CKR_DEVICE_ERROR; + return CKR_DEVICE_ERROR; } /* finally mark all the user certs as non-user certs */ certHandle = sftk_getCertDB(slot); - if (certHandle == NULL) return CKR_OK; + if (certHandle == NULL) + return CKR_OK; sftk_freeDB(certHandle); return CKR_OK; /*is this the right function for not implemented*/ } - /* NSC_InitPIN initializes the normal user's PIN. */ -CK_RV NSC_InitPIN(CK_SESSION_HANDLE hSession, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) +CK_RV +NSC_InitPIN(CK_SESSION_HANDLE hSession, + CK_CHAR_PTR pPin, CK_ULONG ulPinLen) { SFTKSession *sp = NULL; SFTKSlot *slot; SFTKDBHandle *handle = NULL; - char newPinStr[SFTK_MAX_PIN+1]; + char newPinStr[SFTK_MAX_PIN + 1]; SECStatus rv; CK_RV crv = CKR_SESSION_HANDLE_INVALID; PRBool tokenRemoved = PR_FALSE; CHECK_FORK(); - + sp = sftk_SessionFromHandle(hSession); if (sp == NULL) { - goto loser; + goto loser; } slot = sftk_SlotFromSession(sp); if (slot == NULL) { - goto loser; + goto loser; } handle = sftk_getKeyDB(slot); if (handle == NULL) { - crv = CKR_PIN_LEN_RANGE; - goto loser; + crv = CKR_PIN_LEN_RANGE; + goto loser; } - if (sp->info.state != CKS_RW_SO_FUNCTIONS) { - crv = CKR_USER_NOT_LOGGED_IN; - goto loser; + crv = CKR_USER_NOT_LOGGED_IN; + goto loser; } sftk_FreeSession(sp); @@ -3555,85 +3664,94 @@ CK_RV NSC_InitPIN(CK_SESSION_HANDLE hSession, /* make sure the pins aren't too long */ if (ulPinLen > SFTK_MAX_PIN) { - crv = CKR_PIN_LEN_RANGE; - goto loser; + crv = CKR_PIN_LEN_RANGE; + goto loser; } if (ulPinLen < (CK_ULONG)slot->minimumPinLen) { - crv = CKR_PIN_LEN_RANGE; - goto loser; + crv = CKR_PIN_LEN_RANGE; + goto loser; } if (sftkdb_HasPasswordSet(handle) != SECFailure) { - crv = CKR_DEVICE_ERROR; - goto loser; + crv = CKR_DEVICE_ERROR; + goto loser; } /* convert to null terminated string */ PORT_Memcpy(newPinStr, pPin, ulPinLen); - newPinStr[ulPinLen] = 0; + newPinStr[ulPinLen] = 0; /* build the hashed pins which we pass around */ /* change the data base */ rv = sftkdb_ChangePassword(handle, NULL, newPinStr, &tokenRemoved); if (tokenRemoved) { - sftk_CloseAllSessions(slot, PR_FALSE); + sftk_CloseAllSessions(slot, PR_FALSE); } sftk_freeDB(handle); handle = NULL; /* Now update our local copy of the pin */ if (rv == SECSuccess) { - if (ulPinLen == 0) slot->needLogin = PR_FALSE; - return CKR_OK; + if (ulPinLen == 0) + slot->needLogin = PR_FALSE; + /* database has been initialized, now force min password in FIPS + * mode. NOTE: if we are in level1, we may not have a password, but + * forcing it now will prevent an insufficient password from being set. + */ + if ((sftk_GetModuleIndex(slot->slotID) == NSC_FIPS_MODULE) && + (slot->minimumPinLen < FIPS_MIN_PIN)) { + slot->minimumPinLen = FIPS_MIN_PIN; + } + return CKR_OK; } crv = CKR_PIN_INCORRECT; loser: if (sp) { - sftk_FreeSession(sp); + sftk_FreeSession(sp); } if (handle) { - sftk_freeDB(handle); + sftk_freeDB(handle); } return crv; } - /* NSC_SetPIN modifies the PIN of user that is currently logged in. */ /* NOTE: This is only valid for the PRIVATE_KEY_SLOT */ -CK_RV NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, - CK_ULONG ulOldLen, CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen) +CK_RV +NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, + CK_ULONG ulOldLen, CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen) { SFTKSession *sp = NULL; SFTKSlot *slot; SFTKDBHandle *handle = NULL; - char newPinStr[SFTK_MAX_PIN+1],oldPinStr[SFTK_MAX_PIN+1]; + char newPinStr[SFTK_MAX_PIN + 1], oldPinStr[SFTK_MAX_PIN + 1]; SECStatus rv; CK_RV crv = CKR_SESSION_HANDLE_INVALID; PRBool tokenRemoved = PR_FALSE; CHECK_FORK(); - + sp = sftk_SessionFromHandle(hSession); if (sp == NULL) { - goto loser; + goto loser; } slot = sftk_SlotFromSession(sp); if (!slot) { - goto loser; + goto loser; } handle = sftk_getKeyDB(slot); if (handle == NULL) { - sftk_FreeSession(sp); - return CKR_PIN_LEN_RANGE; /* XXX FIXME wrong return value */ + sftk_FreeSession(sp); + return CKR_PIN_LEN_RANGE; /* XXX FIXME wrong return value */ } if (slot->needLogin && sp->info.state != CKS_RW_USER_FUNCTIONS) { - crv = CKR_USER_NOT_LOGGED_IN; - goto loser; + crv = CKR_USER_NOT_LOGGED_IN; + goto loser; } sftk_FreeSession(sp); @@ -3641,35 +3759,34 @@ CK_RV NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, /* make sure the pins aren't too long */ if ((ulNewLen > SFTK_MAX_PIN) || (ulOldLen > SFTK_MAX_PIN)) { - crv = CKR_PIN_LEN_RANGE; - goto loser; + crv = CKR_PIN_LEN_RANGE; + goto loser; } if (ulNewLen < (CK_ULONG)slot->minimumPinLen) { - crv = CKR_PIN_LEN_RANGE; - goto loser; + crv = CKR_PIN_LEN_RANGE; + goto loser; } - /* convert to null terminated string */ - PORT_Memcpy(newPinStr,pNewPin,ulNewLen); - newPinStr[ulNewLen] = 0; - PORT_Memcpy(oldPinStr,pOldPin,ulOldLen); - oldPinStr[ulOldLen] = 0; + PORT_Memcpy(newPinStr, pNewPin, ulNewLen); + newPinStr[ulNewLen] = 0; + PORT_Memcpy(oldPinStr, pOldPin, ulOldLen); + oldPinStr[ulOldLen] = 0; /* change the data base password */ PR_Lock(slot->pwCheckLock); rv = sftkdb_ChangePassword(handle, oldPinStr, newPinStr, &tokenRemoved); if (tokenRemoved) { - sftk_CloseAllSessions(slot, PR_FALSE); + sftk_CloseAllSessions(slot, PR_FALSE); } if ((rv != SECSuccess) && (slot->slotID == FIPS_SLOT_ID)) { - PR_Sleep(loginWaitTime); + PR_Sleep(loginWaitTime); } PR_Unlock(slot->pwCheckLock); /* Now update our local copy of the pin */ if (rv == SECSuccess) { - slot->needLogin = (PRBool)(ulNewLen != 0); + slot->needLogin = (PRBool)(ulNewLen != 0); /* Reset login flags. */ if (ulNewLen == 0) { PRBool tokenRemoved = PR_FALSE; @@ -3685,22 +3802,23 @@ CK_RV NSC_SetPIN(CK_SESSION_HANDLE hSession, CK_CHAR_PTR pOldPin, } sftk_update_all_states(slot); sftk_freeDB(handle); - return CKR_OK; + return CKR_OK; } crv = CKR_PIN_INCORRECT; loser: if (sp) { - sftk_FreeSession(sp); + sftk_FreeSession(sp); } if (handle) { - sftk_freeDB(handle); + sftk_freeDB(handle); } return crv; } /* NSC_OpenSession opens a session between an application and a token. */ -CK_RV NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, - CK_VOID_PTR pApplication,CK_NOTIFY Notify,CK_SESSION_HANDLE_PTR phSession) +CK_RV +NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, + CK_VOID_PTR pApplication, CK_NOTIFY Notify, CK_SESSION_HANDLE_PTR phSession) { SFTKSlot *slot; CK_SESSION_HANDLE sessionID; @@ -3708,41 +3826,42 @@ CK_RV NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, SFTKSession *sameID; CHECK_FORK(); - + slot = sftk_SlotFromID(slotID, PR_FALSE); - if (slot == NULL) return CKR_SLOT_ID_INVALID; + if (slot == NULL) + return CKR_SLOT_ID_INVALID; /* new session (we only have serial sessions) */ session = sftk_NewSession(slotID, Notify, pApplication, - flags | CKF_SERIAL_SESSION); - if (session == NULL) return CKR_HOST_MEMORY; + flags | CKF_SERIAL_SESSION); + if (session == NULL) + return CKR_HOST_MEMORY; if (slot->readOnly && (flags & CKF_RW_SESSION)) { - /* NETSCAPE_SLOT_ID is Read ONLY */ - session->info.flags &= ~CKF_RW_SESSION; + /* NETSCAPE_SLOT_ID is Read ONLY */ + session->info.flags &= ~CKF_RW_SESSION; } PZ_Lock(slot->slotLock); ++slot->sessionCount; PZ_Unlock(slot->slotLock); if (session->info.flags & CKF_RW_SESSION) { - (void)PR_ATOMIC_INCREMENT(&slot->rwSessionCount); + (void)PR_ATOMIC_INCREMENT(&slot->rwSessionCount); } do { PZLock *lock; do { - sessionID = (PR_ATOMIC_INCREMENT(&slot->sessionIDCount) & 0xffffff) - | (slot->index << 24); + sessionID = (PR_ATOMIC_INCREMENT(&slot->sessionIDCount) & 0xffffff) | (slot->index << 24); } while (sessionID == CK_INVALID_HANDLE); - lock = SFTK_SESSION_LOCK(slot,sessionID); + lock = SFTK_SESSION_LOCK(slot, sessionID); PZ_Lock(lock); sftkqueue_find(sameID, sessionID, slot->head, slot->sessHashSize); if (sameID == NULL) { session->handle = sessionID; sftk_update_state(slot, session); - sftkqueue_add(session, sessionID, slot->head,slot->sessHashSize); + sftkqueue_add(session, sessionID, slot->head, slot->sessHashSize); } else { - slot->sessionIDConflict++; /* for debugging */ + slot->sessionIDConflict++; /* for debugging */ } PZ_Unlock(lock); } while (sameID != NULL); @@ -3751,9 +3870,9 @@ CK_RV NSC_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, return CKR_OK; } - /* NSC_CloseSession closes a session between an application and a token. */ -CK_RV NSC_CloseSession(CK_SESSION_HANDLE hSession) +CK_RV +NSC_CloseSession(CK_SESSION_HANDLE hSession) { SFTKSlot *slot; SFTKSession *session; @@ -3763,47 +3882,48 @@ CK_RV NSC_CloseSession(CK_SESSION_HANDLE hSession) CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; slot = sftk_SlotFromSession(session); sessionFound = PR_FALSE; /* lock */ - lock = SFTK_SESSION_LOCK(slot,hSession); + lock = SFTK_SESSION_LOCK(slot, hSession); PZ_Lock(lock); - if (sftkqueue_is_queued(session,hSession,slot->head,slot->sessHashSize)) { - sessionFound = PR_TRUE; - sftkqueue_delete(session,hSession,slot->head,slot->sessHashSize); - session->refCount--; /* can't go to zero while we hold the reference */ - PORT_Assert(session->refCount > 0); + if (sftkqueue_is_queued(session, hSession, slot->head, slot->sessHashSize)) { + sessionFound = PR_TRUE; + sftkqueue_delete(session, hSession, slot->head, slot->sessHashSize); + session->refCount--; /* can't go to zero while we hold the reference */ + PORT_Assert(session->refCount > 0); } PZ_Unlock(lock); if (sessionFound) { - SFTKDBHandle *handle; - handle = sftk_getKeyDB(slot); - PZ_Lock(slot->slotLock); - if (--slot->sessionCount == 0) { - slot->isLoggedIn = PR_FALSE; - if (slot->needLogin && handle) { - sftkdb_ClearPassword(handle); - } - } - PZ_Unlock(slot->slotLock); - if (handle) { - sftk_freeDB(handle); - } - if (session->info.flags & CKF_RW_SESSION) { - (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount); - } + SFTKDBHandle *handle; + handle = sftk_getKeyDB(slot); + PZ_Lock(slot->slotLock); + if (--slot->sessionCount == 0) { + slot->isLoggedIn = PR_FALSE; + if (slot->needLogin && handle) { + sftkdb_ClearPassword(handle); + } + } + PZ_Unlock(slot->slotLock); + if (handle) { + sftk_freeDB(handle); + } + if (session->info.flags & CKF_RW_SESSION) { + (void)PR_ATOMIC_DECREMENT(&slot->rwSessionCount); + } } sftk_FreeSession(session); return CKR_OK; } - /* NSC_CloseAllSessions closes all sessions with a token. */ -CK_RV NSC_CloseAllSessions (CK_SLOT_ID slotID) +CK_RV +NSC_CloseAllSessions(CK_SLOT_ID slotID) { SFTKSlot *slot; @@ -3815,32 +3935,34 @@ CK_RV NSC_CloseAllSessions (CK_SLOT_ID slotID) #endif slot = sftk_SlotFromID(slotID, PR_FALSE); - if (slot == NULL) return CKR_SLOT_ID_INVALID; + if (slot == NULL) + return CKR_SLOT_ID_INVALID; return sftk_CloseAllSessions(slot, PR_TRUE); } - - /* NSC_GetSessionInfo obtains information about the session. */ -CK_RV NSC_GetSessionInfo(CK_SESSION_HANDLE hSession, - CK_SESSION_INFO_PTR pInfo) +CK_RV +NSC_GetSessionInfo(CK_SESSION_HANDLE hSession, + CK_SESSION_INFO_PTR pInfo) { SFTKSession *session; CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; - PORT_Memcpy(pInfo,&session->info,sizeof(CK_SESSION_INFO)); + PORT_Memcpy(pInfo, &session->info, sizeof(CK_SESSION_INFO)); sftk_FreeSession(session); return CKR_OK; } /* NSC_Login logs a user into a token. */ -CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, - CK_CHAR_PTR pPin, CK_ULONG ulPinLen) +CK_RV +NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, + CK_CHAR_PTR pPin, CK_ULONG ulPinLen) { SFTKSlot *slot; SFTKSession *session; @@ -3848,7 +3970,7 @@ CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_FLAGS sessionFlags; SECStatus rv; CK_RV crv; - char pinStr[SFTK_MAX_PIN+1]; + char pinStr[SFTK_MAX_PIN + 1]; PRBool tokenRemoved = PR_FALSE; CHECK_FORK(); @@ -3856,13 +3978,13 @@ CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, /* get the slot */ slot = sftk_SlotFromSessionHandle(hSession); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* make sure the session is valid */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } sessionFlags = session->info.flags; sftk_FreeSession(session); @@ -3870,24 +3992,28 @@ CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, /* can't log into the Netscape Slot */ if (slot->slotID == NETSCAPE_SLOT_ID) { - return CKR_USER_TYPE_INVALID; + return CKR_USER_TYPE_INVALID; } - if (slot->isLoggedIn) return CKR_USER_ALREADY_LOGGED_IN; + if (slot->isLoggedIn) + return CKR_USER_ALREADY_LOGGED_IN; if (!slot->needLogin) { return ulPinLen ? CKR_PIN_INCORRECT : CKR_OK; } slot->ssoLoggedIn = PR_FALSE; - if (ulPinLen > SFTK_MAX_PIN) return CKR_PIN_LEN_RANGE; + if (ulPinLen > SFTK_MAX_PIN) + return CKR_PIN_LEN_RANGE; /* convert to null terminated string */ - PORT_Memcpy(pinStr,pPin,ulPinLen); - pinStr[ulPinLen] = 0; + if (ulPinLen) { + PORT_Memcpy(pinStr, pPin, ulPinLen); + } + pinStr[ulPinLen] = 0; handle = sftk_getKeyDB(slot); if (handle == NULL) { - return CKR_USER_TYPE_INVALID; + return CKR_USER_TYPE_INVALID; } /* @@ -3897,72 +4023,71 @@ CK_RV NSC_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, */ rv = sftkdb_HasPasswordSet(handle); if (rv == SECFailure) { - /* allow SSO's to log in only if there is not password on the - * key database */ - if (((userType == CKU_SO) && (sessionFlags & CKF_RW_SESSION)) - /* fips always needs to authenticate, even if there isn't a db */ - || (slot->slotID == FIPS_SLOT_ID)) { - /* should this be a fixed password? */ - if (ulPinLen == 0) { - sftkdb_ClearPassword(handle); - PZ_Lock(slot->slotLock); - slot->isLoggedIn = PR_TRUE; - slot->ssoLoggedIn = (PRBool)(userType == CKU_SO); - PZ_Unlock(slot->slotLock); - sftk_update_all_states(slot); - crv = CKR_OK; - goto done; - } - crv = CKR_PIN_INCORRECT; - goto done; - } - crv = CKR_USER_TYPE_INVALID; - goto done; - } + /* allow SSO's to log in only if there is not password on the + * key database */ + if (((userType == CKU_SO) && (sessionFlags & CKF_RW_SESSION)) + /* fips always needs to authenticate, even if there isn't a db */ + || (slot->slotID == FIPS_SLOT_ID)) { + /* should this be a fixed password? */ + if (ulPinLen == 0) { + sftkdb_ClearPassword(handle); + PZ_Lock(slot->slotLock); + slot->isLoggedIn = PR_TRUE; + slot->ssoLoggedIn = (PRBool)(userType == CKU_SO); + PZ_Unlock(slot->slotLock); + sftk_update_all_states(slot); + crv = CKR_OK; + goto done; + } + crv = CKR_PIN_INCORRECT; + goto done; + } + crv = CKR_USER_TYPE_INVALID; + goto done; + } /* don't allow the SSO to log in if the user is already initialized */ - if (userType != CKU_USER) { - crv = CKR_USER_TYPE_INVALID; - goto done; + if (userType != CKU_USER) { + crv = CKR_USER_TYPE_INVALID; + goto done; } - /* build the hashed pins which we pass around */ PR_Lock(slot->pwCheckLock); - rv = sftkdb_CheckPassword(handle,pinStr, &tokenRemoved); + rv = sftkdb_CheckPassword(handle, pinStr, &tokenRemoved); if (tokenRemoved) { - sftk_CloseAllSessions(slot, PR_FALSE); + sftk_CloseAllSessions(slot, PR_FALSE); } if ((rv != SECSuccess) && (slot->slotID == FIPS_SLOT_ID)) { - PR_Sleep(loginWaitTime); + PR_Sleep(loginWaitTime); } PR_Unlock(slot->pwCheckLock); if (rv == SECSuccess) { - PZ_Lock(slot->slotLock); - /* make sure the login state matches the underlying - * database state */ - slot->isLoggedIn = sftkdb_PWCached(handle) == SECSuccess ? - PR_TRUE : PR_FALSE; - PZ_Unlock(slot->slotLock); + PZ_Lock(slot->slotLock); + /* make sure the login state matches the underlying + * database state */ + slot->isLoggedIn = sftkdb_PWCached(handle) == SECSuccess ? PR_TRUE : PR_FALSE; + PZ_Unlock(slot->slotLock); - sftk_freeDB(handle); - handle = NULL; + sftk_freeDB(handle); + handle = NULL; - /* update all sessions */ - sftk_update_all_states(slot); - return CKR_OK; + /* update all sessions */ + sftk_update_all_states(slot); + return CKR_OK; } crv = CKR_PIN_INCORRECT; done: if (handle) { - sftk_freeDB(handle); + sftk_freeDB(handle); } return crv; } /* NSC_Logout logs a user out from a token. */ -CK_RV NSC_Logout(CK_SESSION_HANDLE hSession) +CK_RV +NSC_Logout(CK_SESSION_HANDLE hSession) { SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); SFTKSession *session; @@ -3971,25 +4096,27 @@ CK_RV NSC_Logout(CK_SESSION_HANDLE hSession) CHECK_FORK(); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; sftk_FreeSession(session); session = NULL; - if (!slot->isLoggedIn) return CKR_USER_NOT_LOGGED_IN; + if (!slot->isLoggedIn) + return CKR_USER_NOT_LOGGED_IN; handle = sftk_getKeyDB(slot); PZ_Lock(slot->slotLock); slot->isLoggedIn = PR_FALSE; slot->ssoLoggedIn = PR_FALSE; if (slot->needLogin && handle) { - sftkdb_ClearPassword(handle); + sftkdb_ClearPassword(handle); } PZ_Unlock(slot->slotLock); if (handle) { - sftk_freeDB(handle); + sftk_freeDB(handle); } sftk_update_all_states(slot); @@ -4004,8 +4131,9 @@ CK_RV NSC_Logout(CK_SESSION_HANDLE hSession) * "object" is the creation object that specifies the module spec for the slot * to add or remove. */ -static CK_RV sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class, - SFTKObject *object) +static CK_RV +sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class, + SFTKObject *object) { PRBool isValidUserSlot = PR_FALSE; PRBool isValidFIPSUserSlot = PR_FALSE; @@ -4020,25 +4148,25 @@ static CK_RV sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class, CK_RV crv = CKR_OK; if (class != CKO_NETSCAPE_DELSLOT && class != CKO_NETSCAPE_NEWSLOT) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } if (class == CKO_NETSCAPE_NEWSLOT && slot->slotID == FIPS_SLOT_ID) { - isFIPS = PR_TRUE; + isFIPS = PR_TRUE; } attribute = sftk_FindAttribute(object, CKA_NETSCAPE_MODULE_SPEC); if (attribute == NULL) { - return CKR_TEMPLATE_INCOMPLETE; + return CKR_TEMPLATE_INCOMPLETE; } paramString = (char *)attribute->attrib.pValue; crv = sftk_parseParameters(paramString, ¶mStrings, isFIPS); if (crv != CKR_OK) { - goto loser; + goto loser; } /* enforce only one at a time */ if (paramStrings.token_count != 1) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } slotID = paramStrings.tokens[0].slotID; @@ -4050,50 +4178,50 @@ static CK_RV sftk_CreateNewSlot(SFTKSlot *slot, CK_OBJECT_CLASS class, slotID <= SFTK_MAX_FIPS_USER_SLOT_ID); if (class == CKO_NETSCAPE_DELSLOT) { - if (slot->slotID == slotID) { - isValidSlot = isValidUserSlot || isValidFIPSUserSlot; - } + if (slot->slotID == slotID) { + isValidSlot = isValidUserSlot || isValidFIPSUserSlot; + } } else { - /* only the crypto or FIPS slots can create new slot objects */ - if (slot->slotID == NETSCAPE_SLOT_ID) { - isValidSlot = isValidUserSlot; - moduleIndex = NSC_NON_FIPS_MODULE; - } else if (slot->slotID == FIPS_SLOT_ID) { - isValidSlot = isValidFIPSUserSlot; - moduleIndex = NSC_FIPS_MODULE; - } + /* only the crypto or FIPS slots can create new slot objects */ + if (slot->slotID == NETSCAPE_SLOT_ID) { + isValidSlot = isValidUserSlot; + moduleIndex = NSC_NON_FIPS_MODULE; + } else if (slot->slotID == FIPS_SLOT_ID) { + isValidSlot = isValidFIPSUserSlot; + moduleIndex = NSC_FIPS_MODULE; + } } if (!isValidSlot) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } /* unload any existing slot at this id */ newSlot = sftk_SlotFromID(slotID, PR_TRUE); if (newSlot && newSlot->present) { - crv = SFTK_ShutdownSlot(newSlot); - if (crv != CKR_OK) { - goto loser; - } + crv = SFTK_ShutdownSlot(newSlot); + if (crv != CKR_OK) { + goto loser; + } } /* if we were just planning on deleting the slot, then do so now */ if (class == CKO_NETSCAPE_DELSLOT) { - /* sort of a unconventional use of this error code, be we are - * overusing CKR_ATTRIBUTE_VALUE_INVALID, and it does apply */ - crv = newSlot ? CKR_OK : CKR_SLOT_ID_INVALID; - goto loser; /* really exit */ + /* sort of a unconventional use of this error code, be we are + * overusing CKR_ATTRIBUTE_VALUE_INVALID, and it does apply */ + crv = newSlot ? CKR_OK : CKR_SLOT_ID_INVALID; + goto loser; /* really exit */ } if (newSlot) { - crv = SFTK_SlotReInit(newSlot, paramStrings.configdir, - paramStrings.updatedir, paramStrings.updateID, - ¶mStrings.tokens[0], moduleIndex); + crv = SFTK_SlotReInit(newSlot, paramStrings.configdir, + paramStrings.updatedir, paramStrings.updateID, + ¶mStrings.tokens[0], moduleIndex); } else { - crv = SFTK_SlotInit(paramStrings.configdir, - paramStrings.updatedir, paramStrings.updateID, - ¶mStrings.tokens[0], moduleIndex); + crv = SFTK_SlotInit(paramStrings.configdir, + paramStrings.updatedir, paramStrings.updateID, + ¶mStrings.tokens[0], moduleIndex); } loser: @@ -4103,11 +4231,11 @@ loser: return crv; } - /* NSC_CreateObject creates a new object. */ -CK_RV NSC_CreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject) +CK_RV +NSC_CreateObject(CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject) { SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); SFTKSession *session; @@ -4123,49 +4251,49 @@ CK_RV NSC_CreateObject(CK_SESSION_HANDLE hSession, *phObject = CK_INVALID_HANDLE; if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* * now lets create an object to hang the attributes off of */ object = sftk_NewObject(slot); /* fill in the handle later */ if (object == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* * load the template values into the object */ - for (i=0; i < (int) ulCount; i++) { - crv = sftk_AddAttributeType(object,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) { - sftk_FreeObject(object); - return crv; - } - if ((pTemplate[i].type == CKA_CLASS) && pTemplate[i].pValue) { - class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; - } + for (i = 0; i < (int)ulCount; i++) { + crv = sftk_AddAttributeType(object, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) { + sftk_FreeObject(object); + return crv; + } + if ((pTemplate[i].type == CKA_CLASS) && pTemplate[i].pValue) { + class = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; + } } /* get the session */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { - sftk_FreeObject(object); + sftk_FreeObject(object); return CKR_SESSION_HANDLE_INVALID; } /* * handle pseudo objects (CKO_NEWSLOT) */ - if ((class == CKO_NETSCAPE_NEWSLOT) || (class == CKO_NETSCAPE_DELSLOT)) { - crv = sftk_CreateNewSlot(slot, class, object); - goto done; - } + if ((class == CKO_NETSCAPE_NEWSLOT) || (class == CKO_NETSCAPE_DELSLOT)) { + crv = sftk_CreateNewSlot(slot, class, object); + goto done; + } /* * handle the base object stuff */ - crv = sftk_handleObject(object,session); + crv = sftk_handleObject(object, session); *phObject = object->handle; done: sftk_FreeSession(session); @@ -4174,14 +4302,13 @@ done: return crv; } - - /* NSC_CopyObject copies an object, creating a new object for the copy. */ -CK_RV NSC_CopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject) +CK_RV +NSC_CopyObject(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject) { - SFTKObject *destObject,*srcObject; + SFTKObject *destObject, *srcObject; SFTKSession *session; CK_RV crv = CKR_OK; SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); @@ -4190,54 +4317,56 @@ CK_RV NSC_CopyObject(CK_SESSION_HANDLE hSession, CHECK_FORK(); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* Get srcObject so we can find the class */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { return CKR_SESSION_HANDLE_INVALID; } - srcObject = sftk_ObjectFromHandle(hObject,session); + srcObject = sftk_ObjectFromHandle(hObject, session); if (srcObject == NULL) { - sftk_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; + sftk_FreeSession(session); + return CKR_OBJECT_HANDLE_INVALID; } /* * create an object to hang the attributes off of */ destObject = sftk_NewObject(slot); /* fill in the handle later */ if (destObject == NULL) { - sftk_FreeSession(session); + sftk_FreeSession(session); sftk_FreeObject(srcObject); - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* * load the template values into the object */ - for (i=0; i < (int) ulCount; i++) { - if (sftk_modifyType(pTemplate[i].type,srcObject->objclass) == SFTK_NEVER) { - crv = CKR_ATTRIBUTE_READ_ONLY; - break; - } - crv = sftk_AddAttributeType(destObject,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) { break; } + for (i = 0; i < (int)ulCount; i++) { + if (sftk_modifyType(pTemplate[i].type, srcObject->objclass) == SFTK_NEVER) { + crv = CKR_ATTRIBUTE_READ_ONLY; + break; + } + crv = sftk_AddAttributeType(destObject, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) { + break; + } } if (crv != CKR_OK) { - sftk_FreeSession(session); + sftk_FreeSession(session); sftk_FreeObject(srcObject); - sftk_FreeObject(destObject); - return crv; + sftk_FreeObject(destObject); + return crv; } /* sensitive can only be changed to CK_TRUE */ - if (sftk_hasAttribute(destObject,CKA_SENSITIVE)) { - if (!sftk_isTrue(destObject,CKA_SENSITIVE)) { - sftk_FreeSession(session); + if (sftk_hasAttribute(destObject, CKA_SENSITIVE)) { + if (!sftk_isTrue(destObject, CKA_SENSITIVE)) { + sftk_FreeSession(session); sftk_FreeObject(srcObject); - sftk_FreeObject(destObject); - return CKR_ATTRIBUTE_READ_ONLY; - } + sftk_FreeObject(destObject); + return CKR_ATTRIBUTE_READ_ONLY; + } } /* @@ -4246,28 +4375,28 @@ CK_RV NSC_CopyObject(CK_SESSION_HANDLE hSession, /* don't create a token object if we aren't in a rw session */ /* we need to hold the lock to copy a consistant version of * the object. */ - crv = sftk_CopyObject(destObject,srcObject); + crv = sftk_CopyObject(destObject, srcObject); destObject->objclass = srcObject->objclass; sftk_FreeObject(srcObject); if (crv != CKR_OK) { - sftk_FreeObject(destObject); - sftk_FreeSession(session); + sftk_FreeObject(destObject); + sftk_FreeSession(session); return crv; } - crv = sftk_handleObject(destObject,session); + crv = sftk_handleObject(destObject, session); *phNewObject = destObject->handle; sftk_FreeSession(session); sftk_FreeObject(destObject); - + return crv; } - /* NSC_GetObjectSize gets the size of an object in bytes. */ -CK_RV NSC_GetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) +CK_RV +NSC_GetObjectSize(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { CHECK_FORK(); @@ -4275,10 +4404,10 @@ CK_RV NSC_GetObjectSize(CK_SESSION_HANDLE hSession, return CKR_OK; } - /* NSC_GetAttributeValue obtains the value of one or more object attributes. */ -CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) +CK_RV +NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); SFTKSession *session; @@ -4291,7 +4420,7 @@ CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, CHECK_FORK(); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* * make sure we're allowed @@ -4303,75 +4432,75 @@ CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, /* short circuit everything for token objects */ if (sftk_isToken(hObject)) { - SFTKSlot *slot = sftk_SlotFromSession(session); - SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, hObject); - SFTKDBHandle *keydb = NULL; - - if (dbHandle == NULL) { - sftk_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; - } - - crv = sftkdb_GetAttributeValue(dbHandle, hObject, pTemplate, ulCount); - - /* make sure we don't export any sensitive information */ - keydb = sftk_getKeyDB(slot); - if (dbHandle == keydb) { - for (i=0; i < (int) ulCount; i++) { - if (sftk_isSensitive(pTemplate[i].type,CKO_PRIVATE_KEY)) { - crv = CKR_ATTRIBUTE_SENSITIVE; - if (pTemplate[i].pValue && (pTemplate[i].ulValueLen!= -1)){ - PORT_Memset(pTemplate[i].pValue, 0, - pTemplate[i].ulValueLen); - } - pTemplate[i].ulValueLen = -1; - } - } - } - - sftk_FreeSession(session); - sftk_freeDB(dbHandle); - if (keydb) { - sftk_freeDB(keydb); - } - return crv; + SFTKSlot *slot = sftk_SlotFromSession(session); + SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, hObject); + SFTKDBHandle *keydb = NULL; + + if (dbHandle == NULL) { + sftk_FreeSession(session); + return CKR_OBJECT_HANDLE_INVALID; + } + + crv = sftkdb_GetAttributeValue(dbHandle, hObject, pTemplate, ulCount); + + /* make sure we don't export any sensitive information */ + keydb = sftk_getKeyDB(slot); + if (dbHandle == keydb) { + for (i = 0; i < (int)ulCount; i++) { + if (sftk_isSensitive(pTemplate[i].type, CKO_PRIVATE_KEY)) { + crv = CKR_ATTRIBUTE_SENSITIVE; + if (pTemplate[i].pValue && (pTemplate[i].ulValueLen != -1)) { + PORT_Memset(pTemplate[i].pValue, 0, + pTemplate[i].ulValueLen); + } + pTemplate[i].ulValueLen = -1; + } + } + } + + sftk_FreeSession(session); + sftk_freeDB(dbHandle); + if (keydb) { + sftk_freeDB(keydb); + } + return crv; } /* handle the session object */ - object = sftk_ObjectFromHandle(hObject,session); + object = sftk_ObjectFromHandle(hObject, session); sftk_FreeSession(session); if (object == NULL) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } /* don't read a private object if we aren't logged in */ if ((!slot->isLoggedIn) && (slot->needLogin) && - (sftk_isTrue(object,CKA_PRIVATE))) { - sftk_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; + (sftk_isTrue(object, CKA_PRIVATE))) { + sftk_FreeObject(object); + return CKR_USER_NOT_LOGGED_IN; } crv = CKR_OK; - sensitive = sftk_isTrue(object,CKA_SENSITIVE); - for (i=0; i < (int) ulCount; i++) { - /* Make sure that this attribute is retrievable */ - if (sensitive && sftk_isSensitive(pTemplate[i].type,object->objclass)) { - crv = CKR_ATTRIBUTE_SENSITIVE; - pTemplate[i].ulValueLen = -1; - continue; - } - attribute = sftk_FindAttribute(object,pTemplate[i].type); - if (attribute == NULL) { - crv = CKR_ATTRIBUTE_TYPE_INVALID; - pTemplate[i].ulValueLen = -1; - continue; - } - if (pTemplate[i].pValue != NULL) { - PORT_Memcpy(pTemplate[i].pValue,attribute->attrib.pValue, - attribute->attrib.ulValueLen); - } - pTemplate[i].ulValueLen = attribute->attrib.ulValueLen; - sftk_FreeAttribute(attribute); + sensitive = sftk_isTrue(object, CKA_SENSITIVE); + for (i = 0; i < (int)ulCount; i++) { + /* Make sure that this attribute is retrievable */ + if (sensitive && sftk_isSensitive(pTemplate[i].type, object->objclass)) { + crv = CKR_ATTRIBUTE_SENSITIVE; + pTemplate[i].ulValueLen = -1; + continue; + } + attribute = sftk_FindAttribute(object, pTemplate[i].type); + if (attribute == NULL) { + crv = CKR_ATTRIBUTE_TYPE_INVALID; + pTemplate[i].ulValueLen = -1; + continue; + } + if (pTemplate[i].pValue != NULL) { + PORT_Memcpy(pTemplate[i].pValue, attribute->attrib.pValue, + attribute->attrib.ulValueLen); + } + pTemplate[i].ulValueLen = attribute->attrib.ulValueLen; + sftk_FreeAttribute(attribute); } sftk_FreeObject(object); @@ -4379,8 +4508,9 @@ CK_RV NSC_GetAttributeValue(CK_SESSION_HANDLE hSession, } /* NSC_SetAttributeValue modifies the value of one or more object attributes */ -CK_RV NSC_SetAttributeValue (CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) +CK_RV +NSC_SetAttributeValue(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); SFTKSession *session; @@ -4394,7 +4524,7 @@ CK_RV NSC_SetAttributeValue (CK_SESSION_HANDLE hSession, CHECK_FORK(); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* * make sure we're allowed @@ -4404,65 +4534,66 @@ CK_RV NSC_SetAttributeValue (CK_SESSION_HANDLE hSession, return CKR_SESSION_HANDLE_INVALID; } - object = sftk_ObjectFromHandle(hObject,session); + object = sftk_ObjectFromHandle(hObject, session); if (object == NULL) { sftk_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } /* don't modify a private object if we aren't logged in */ if ((!slot->isLoggedIn) && (slot->needLogin) && - (sftk_isTrue(object,CKA_PRIVATE))) { - sftk_FreeSession(session); - sftk_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; + (sftk_isTrue(object, CKA_PRIVATE))) { + sftk_FreeSession(session); + sftk_FreeObject(object); + return CKR_USER_NOT_LOGGED_IN; } /* don't modify a token object if we aren't in a rw session */ - isToken = sftk_isTrue(object,CKA_TOKEN); + isToken = sftk_isTrue(object, CKA_TOKEN); if (((session->info.flags & CKF_RW_SESSION) == 0) && isToken) { - sftk_FreeSession(session); - sftk_FreeObject(object); - return CKR_SESSION_READ_ONLY; + sftk_FreeSession(session); + sftk_FreeObject(object); + return CKR_SESSION_READ_ONLY; } sftk_FreeSession(session); /* only change modifiable objects */ - if (!sftk_isTrue(object,CKA_MODIFIABLE)) { - sftk_FreeObject(object); - return CKR_ATTRIBUTE_READ_ONLY; - } - - for (i=0; i < (int) ulCount; i++) { - /* Make sure that this attribute is changeable */ - switch (sftk_modifyType(pTemplate[i].type,object->objclass)) { - case SFTK_NEVER: - case SFTK_ONCOPY: - default: - crv = CKR_ATTRIBUTE_READ_ONLY; - break; - - case SFTK_SENSITIVE: - legal = (pTemplate[i].type == CKA_EXTRACTABLE) ? CK_FALSE : CK_TRUE; - if ((*(CK_BBOOL *)pTemplate[i].pValue) != legal) { - crv = CKR_ATTRIBUTE_READ_ONLY; - } - break; - case SFTK_ALWAYS: - break; - } - if (crv != CKR_OK) break; - - /* find the old attribute */ - attribute = sftk_FindAttribute(object,pTemplate[i].type); - if (attribute == NULL) { - crv =CKR_ATTRIBUTE_TYPE_INVALID; - break; - } - sftk_FreeAttribute(attribute); - crv = sftk_forceAttribute(object,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; + if (!sftk_isTrue(object, CKA_MODIFIABLE)) { + sftk_FreeObject(object); + return CKR_ATTRIBUTE_READ_ONLY; + } + + for (i = 0; i < (int)ulCount; i++) { + /* Make sure that this attribute is changeable */ + switch (sftk_modifyType(pTemplate[i].type, object->objclass)) { + case SFTK_NEVER: + case SFTK_ONCOPY: + default: + crv = CKR_ATTRIBUTE_READ_ONLY; + break; + case SFTK_SENSITIVE: + legal = (pTemplate[i].type == CKA_EXTRACTABLE) ? CK_FALSE : CK_TRUE; + if ((*(CK_BBOOL *)pTemplate[i].pValue) != legal) { + crv = CKR_ATTRIBUTE_READ_ONLY; + } + break; + case SFTK_ALWAYS: + break; + } + if (crv != CKR_OK) + break; + + /* find the old attribute */ + attribute = sftk_FindAttribute(object, pTemplate[i].type); + if (attribute == NULL) { + crv = CKR_ATTRIBUTE_TYPE_INVALID; + break; + } + sftk_FreeAttribute(attribute); + crv = sftk_forceAttribute(object, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) + break; } sftk_FreeObject(object); @@ -4474,36 +4605,34 @@ sftk_expandSearchList(SFTKSearchResults *search, int count) { search->array_size += count; search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles, - sizeof(CK_OBJECT_HANDLE)*search->array_size); + sizeof(CK_OBJECT_HANDLE) * search->array_size); return search->handles ? CKR_OK : CKR_HOST_MEMORY; } - - static CK_RV sftk_searchDatabase(SFTKDBHandle *handle, SFTKSearchResults *search, - const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) + const CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) { CK_RV crv; - int objectListSize = search->array_size-search->size; + int objectListSize = search->array_size - search->size; CK_OBJECT_HANDLE *array = &search->handles[search->size]; SDBFind *find; CK_ULONG count; crv = sftkdb_FindObjectsInit(handle, pTemplate, ulCount, &find); if (crv != CKR_OK) - return crv; + return crv; do { - crv = sftkdb_FindObjects(handle, find, array, objectListSize, &count); - if ((crv != CKR_OK) || (count == 0)) - break; - search->size += count; - objectListSize -= count; - if (objectListSize > 0) - break; - crv = sftk_expandSearchList(search,NSC_SEARCH_BLOCK_SIZE); - objectListSize = NSC_SEARCH_BLOCK_SIZE; - array = &search->handles[search->size]; + crv = sftkdb_FindObjects(handle, find, array, objectListSize, &count); + if ((crv != CKR_OK) || (count == 0)) + break; + search->size += count; + objectListSize -= count; + if (objectListSize > 0) + break; + crv = sftk_expandSearchList(search, NSC_SEARCH_BLOCK_SIZE); + objectListSize = NSC_SEARCH_BLOCK_SIZE; + array = &search->handles[search->size]; } while (crv == CKR_OK); sftkdb_FindObjectsFinal(handle, find); @@ -4515,8 +4644,8 @@ sftk_searchDatabase(SFTKDBHandle *handle, SFTKSearchResults *search, * pk11wrap so that it will work with other tokens other than softoken. */ CK_RV -sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle, - SFTKSearchResults *search, CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) +sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle, + SFTKSearchResults *search, CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount) { PRBool isCert = PR_FALSE; int emailIndex = -1; @@ -4528,28 +4657,27 @@ sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle, SFTKObject *object = NULL; CK_RV crv = CKR_OK; - smime_search.handles = NULL; /* paranoia, some one is bound to add a goto - * loser before this gets initialized */ + * loser before this gets initialized */ /* see if we are looking for email certs */ - for (i=0; i < ulCount; i++) { - if (pTemplate[i].type == CKA_CLASS) { - if ((pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS) || - (*(CK_OBJECT_CLASS *)pTemplate[i].pValue) != CKO_CERTIFICATE)) { - /* not a cert, skip out */ - break; - } - isCert = PR_TRUE; - } else if (pTemplate[i].type == CKA_NETSCAPE_EMAIL) { - emailIndex = i; - - } - if (isCert && (emailIndex != -1)) break; + for (i = 0; i < ulCount; i++) { + if (pTemplate[i].type == CKA_CLASS) { + if ((pTemplate[i].ulValueLen != sizeof(CK_OBJECT_CLASS) || + (*(CK_OBJECT_CLASS *)pTemplate[i].pValue) != CKO_CERTIFICATE)) { + /* not a cert, skip out */ + break; + } + isCert = PR_TRUE; + } else if (pTemplate[i].type == CKA_NETSCAPE_EMAIL) { + emailIndex = i; + } + if (isCert && (emailIndex != -1)) + break; } if (!isCert || (emailIndex == -1)) { - return CKR_OK; + return CKR_OK; } /* we are doing a cert and email search, find the SMimeEntry */ @@ -4559,30 +4687,30 @@ sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle, smime_template[1] = pTemplate[emailIndex]; smime_search.handles = (CK_OBJECT_HANDLE *) - PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE); + PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE); if (smime_search.handles == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } smime_search.index = 0; smime_search.size = 0; smime_search.array_size = NSC_SEARCH_BLOCK_SIZE; - + crv = sftk_searchDatabase(handle, &smime_search, smime_template, 2); if (crv != CKR_OK || smime_search.size == 0) { - goto loser; + goto loser; } /* get the SMime subject */ object = sftk_NewTokenObject(slot, NULL, smime_search.handles[0]); if (object == NULL) { - crv = CKR_HOST_MEMORY; /* is there any other reason for this failure? */ - goto loser; + crv = CKR_HOST_MEMORY; /* is there any other reason for this failure? */ + goto loser; } - attribute = sftk_FindAttribute(object,CKA_SUBJECT); + attribute = sftk_FindAttribute(object, CKA_SUBJECT); if (attribute == NULL) { - crv = CKR_ATTRIBUTE_TYPE_INVALID; - goto loser; + crv = CKR_ATTRIBUTE_TYPE_INVALID; + goto loser; } /* now find the certs with that subject */ @@ -4593,70 +4721,73 @@ sftk_emailhack(SFTKSlot *slot, SFTKDBHandle *handle, loser: if (attribute) { - sftk_FreeAttribute(attribute); + sftk_FreeAttribute(attribute); } if (object) { - sftk_FreeObject(object); + sftk_FreeObject(object); } if (smime_search.handles) { - PORT_Free(smime_search.handles); + PORT_Free(smime_search.handles); } return crv; } - + static void sftk_pruneSearch(CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount, - PRBool *searchCertDB, PRBool *searchKeyDB) { + PRBool *searchCertDB, PRBool *searchKeyDB) +{ CK_ULONG i; *searchCertDB = PR_TRUE; *searchKeyDB = PR_TRUE; for (i = 0; i < ulCount; i++) { - if (pTemplate[i].type == CKA_CLASS && pTemplate[i].pValue != NULL) { - CK_OBJECT_CLASS class = *((CK_OBJECT_CLASS*)pTemplate[i].pValue); - if (class == CKO_PRIVATE_KEY || class == CKO_SECRET_KEY) { - *searchCertDB = PR_FALSE; - } else { - *searchKeyDB = PR_FALSE; - } - break; - } + if (pTemplate[i].type == CKA_CLASS && pTemplate[i].pValue != NULL) { + CK_OBJECT_CLASS class = *((CK_OBJECT_CLASS *)pTemplate[i].pValue); + if (class == CKO_PRIVATE_KEY || class == CKO_SECRET_KEY) { + *searchCertDB = PR_FALSE; + } else { + *searchKeyDB = PR_FALSE; + } + break; + } } } static CK_RV sftk_searchTokenList(SFTKSlot *slot, SFTKSearchResults *search, - CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount, - PRBool *tokenOnly, PRBool isLoggedIn) + CK_ATTRIBUTE *pTemplate, CK_ULONG ulCount, + PRBool *tokenOnly, PRBool isLoggedIn) { CK_RV crv = CKR_OK; CK_RV crv2; PRBool searchCertDB; PRBool searchKeyDB; - + sftk_pruneSearch(pTemplate, ulCount, &searchCertDB, &searchKeyDB); if (searchCertDB) { - SFTKDBHandle *certHandle = sftk_getCertDB(slot); - crv = sftk_searchDatabase(certHandle, search, pTemplate, ulCount); - crv2 = sftk_emailhack(slot, certHandle, search, pTemplate, ulCount); - if (crv == CKR_OK) crv = crv2; - sftk_freeDB(certHandle); + SFTKDBHandle *certHandle = sftk_getCertDB(slot); + crv = sftk_searchDatabase(certHandle, search, pTemplate, ulCount); + crv2 = sftk_emailhack(slot, certHandle, search, pTemplate, ulCount); + if (crv == CKR_OK) + crv = crv2; + sftk_freeDB(certHandle); } if (crv == CKR_OK && isLoggedIn && searchKeyDB) { - SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); - crv = sftk_searchDatabase(keyHandle, search, pTemplate, ulCount); - sftk_freeDB(keyHandle); + SFTKDBHandle *keyHandle = sftk_getKeyDB(slot); + crv = sftk_searchDatabase(keyHandle, search, pTemplate, ulCount); + sftk_freeDB(keyHandle); } return crv; } -/* NSC_FindObjectsInit initializes a search for token and session objects +/* NSC_FindObjectsInit initializes a search for token and session objects * that match a template. */ -CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount) +CK_RV +NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { SFTKSearchResults *search = NULL, *freeSearch = NULL; SFTKSession *session = NULL; @@ -4666,26 +4797,26 @@ CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, PRBool isLoggedIn; CHECK_FORK(); - + if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } session = sftk_SessionFromHandle(hSession); if (session == NULL) { - crv = CKR_SESSION_HANDLE_INVALID; - goto loser; + crv = CKR_SESSION_HANDLE_INVALID; + goto loser; } - + search = (SFTKSearchResults *)PORT_Alloc(sizeof(SFTKSearchResults)); if (search == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } search->handles = (CK_OBJECT_HANDLE *) - PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE); + PORT_Alloc(sizeof(CK_OBJECT_HANDLE) * NSC_SEARCH_BLOCK_SIZE); if (search->handles == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } search->index = 0; search->size = 0; @@ -4693,24 +4824,24 @@ CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, isLoggedIn = (PRBool)((!slot->needLogin) || slot->isLoggedIn); crv = sftk_searchTokenList(slot, search, pTemplate, ulCount, &tokenOnly, - isLoggedIn); + isLoggedIn); if (crv != CKR_OK) { - goto loser; + goto loser; } - + /* build list of found objects in the session */ if (!tokenOnly) { - crv = sftk_searchObjectList(search, slot->sessObjHashTable, - slot->sessObjHashSize, slot->objectLock, - pTemplate, ulCount, isLoggedIn); + crv = sftk_searchObjectList(search, slot->sessObjHashTable, + slot->sessObjHashSize, slot->objectLock, + pTemplate, ulCount, isLoggedIn); } if (crv != CKR_OK) { - goto loser; + goto loser; } if ((freeSearch = session->search) != NULL) { - session->search = NULL; - sftk_FreeSearch(freeSearch); + session->search = NULL; + sftk_FreeSearch(freeSearch); } session->search = search; sftk_FreeSession(session); @@ -4718,49 +4849,50 @@ CK_RV NSC_FindObjectsInit(CK_SESSION_HANDLE hSession, loser: if (search) { - sftk_FreeSearch(search); + sftk_FreeSearch(search); } if (session) { - sftk_FreeSession(session); + sftk_FreeSession(session); } return crv; } - -/* NSC_FindObjects continues a search for token and session objects +/* NSC_FindObjects continues a search for token and session objects * that match a template, obtaining additional object handles. */ -CK_RV NSC_FindObjects(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE_PTR phObject,CK_ULONG ulMaxObjectCount, - CK_ULONG_PTR pulObjectCount) +CK_RV +NSC_FindObjects(CK_SESSION_HANDLE hSession, + CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, + CK_ULONG_PTR pulObjectCount) { SFTKSession *session; SFTKSearchResults *search; - int transfer; + int transfer; int left; CHECK_FORK(); *pulObjectCount = 0; session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; if (session->search == NULL) { - sftk_FreeSession(session); - return CKR_OK; + sftk_FreeSession(session); + return CKR_OK; } search = session->search; left = session->search->size - session->search->index; transfer = ((int)ulMaxObjectCount > left) ? left : ulMaxObjectCount; if (transfer > 0) { - PORT_Memcpy(phObject,&search->handles[search->index], - transfer*sizeof(CK_OBJECT_HANDLE)); + PORT_Memcpy(phObject, &search->handles[search->index], + transfer * sizeof(CK_OBJECT_HANDLE)); } else { - *phObject = CK_INVALID_HANDLE; + *phObject = CK_INVALID_HANDLE; } search->index += transfer; if (search->index == search->size) { - session->search = NULL; - sftk_FreeSearch(search); + session->search = NULL; + sftk_FreeSearch(search); } *pulObjectCount = transfer; sftk_FreeSession(session); @@ -4768,7 +4900,8 @@ CK_RV NSC_FindObjects(CK_SESSION_HANDLE hSession, } /* NSC_FindObjectsFinal finishes a search for token and session objects. */ -CK_RV NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession) +CK_RV +NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession) { SFTKSession *session; SFTKSearchResults *search; @@ -4776,23 +4909,22 @@ CK_RV NSC_FindObjectsFinal(CK_SESSION_HANDLE hSession) CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; search = session->search; session->search = NULL; sftk_FreeSession(session); if (search != NULL) { - sftk_FreeSearch(search); + sftk_FreeSearch(search); } return CKR_OK; } - - -CK_RV NSC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, - CK_VOID_PTR pReserved) +CK_RV +NSC_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, + CK_VOID_PTR pReserved) { CHECK_FORK(); return CKR_FUNCTION_NOT_SUPPORTED; } - diff --git a/nss/lib/softoken/pkcs11c.c b/nss/lib/softoken/pkcs11c.c index 8755f24..d7b4bb9 100644 --- a/nss/lib/softoken/pkcs11c.c +++ b/nss/lib/softoken/pkcs11c.c @@ -6,11 +6,11 @@ * * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does + * slot 1 is our generic crypto support. It does not require login. + * It supports Public Key ops, and all they bulk ciphers and hashes. + * It can also support Private Key ops for imported Private keys. It does * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It + * slot 2 is our private key support. It requires a login before use. It * can store Private Keys and Certs as token objects. Currently only private * keys and their associated Certificates are saved on the token. * @@ -27,7 +27,7 @@ #include "lowkeyi.h" #include "secder.h" #include "secdig.h" -#include "lowpbe.h" /* We do PBE below */ +#include "lowpbe.h" /* We do PBE below */ #include "pkcs11t.h" #include "secoid.h" #include "alghmac.h" @@ -36,21 +36,22 @@ #include "secerr.h" #include "prprf.h" +#include "prenv.h" -#define __PASTE(x,y) x##y +#define __PASTE(x, y) x##y /* * we renamed all our internal functions, get the correct * definitions for them... - */ + */ #undef CK_PKCS11_FUNCTION_INFO #undef CK_NEED_ARG_LIST #define CK_EXTERN extern #define CK_PKCS11_FUNCTION_INFO(func) \ - CK_RV __PASTE(NS,func) -#define CK_NEED_ARG_LIST 1 - + CK_RV __PASTE(NS, func) +#define CK_NEED_ARG_LIST 1 + #include "pkcs11f.h" typedef struct { @@ -58,23 +59,24 @@ typedef struct { PRUint8 random[46]; } SSL3RSAPreMasterSecret; -static void sftk_Null(void *data, PRBool freeit) +static void +sftk_Null(void *data, PRBool freeit) { return; -} +} #ifndef NSS_DISABLE_ECC #ifdef EC_DEBUG -#define SEC_PRINT(str1, str2, num, sitem) \ +#define SEC_PRINT(str1, str2, num, sitem) \ printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \ - str1, str2, num, sitem->len); \ - for (i = 0; i < sitem->len; i++) { \ - printf("%02x:", sitem->data[i]); \ - } \ - printf("\n") + str1, str2, num, sitem->len); \ + for (i = 0; i < sitem->len; i++) { \ + printf("%02x:", sitem->data[i]); \ + } \ + printf("\n") #else #undef EC_DEBUG -#define SEC_PRINT(a, b, c, d) +#define SEC_PRINT(a, b, c, d) #endif #endif /* NSS_DISABLE_ECC */ @@ -92,7 +94,7 @@ static void sftk_Space(void *data, PRBool freeit) { PORT_Free(data); -} +} /* * map all the SEC_ERROR_xxx error codes that may be returned by freebl @@ -103,33 +105,33 @@ static CK_RV sftk_MapCryptError(int error) { switch (error) { - case SEC_ERROR_INVALID_ARGS: - case SEC_ERROR_BAD_DATA: /* MP_RANGE gets mapped to this */ - return CKR_ARGUMENTS_BAD; - case SEC_ERROR_INPUT_LEN: - return CKR_DATA_LEN_RANGE; - case SEC_ERROR_OUTPUT_LEN: - return CKR_BUFFER_TOO_SMALL; - case SEC_ERROR_LIBRARY_FAILURE: - return CKR_GENERAL_ERROR; - case SEC_ERROR_NO_MEMORY: - return CKR_HOST_MEMORY; - case SEC_ERROR_BAD_SIGNATURE: - return CKR_SIGNATURE_INVALID; - case SEC_ERROR_INVALID_KEY: - return CKR_KEY_SIZE_RANGE; - case SEC_ERROR_BAD_KEY: /* an EC public key that fails validation */ - return CKR_KEY_SIZE_RANGE; /* the closest error code */ - case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM: - return CKR_TEMPLATE_INCONSISTENT; - /* EC functions set this error if NSS_DISABLE_ECC is defined */ - case SEC_ERROR_UNSUPPORTED_KEYALG: - return CKR_MECHANISM_INVALID; - case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE: - return CKR_DOMAIN_PARAMS_INVALID; - /* key pair generation failed after max number of attempts */ - case SEC_ERROR_NEED_RANDOM: - return CKR_FUNCTION_FAILED; + case SEC_ERROR_INVALID_ARGS: + case SEC_ERROR_BAD_DATA: /* MP_RANGE gets mapped to this */ + return CKR_ARGUMENTS_BAD; + case SEC_ERROR_INPUT_LEN: + return CKR_DATA_LEN_RANGE; + case SEC_ERROR_OUTPUT_LEN: + return CKR_BUFFER_TOO_SMALL; + case SEC_ERROR_LIBRARY_FAILURE: + return CKR_GENERAL_ERROR; + case SEC_ERROR_NO_MEMORY: + return CKR_HOST_MEMORY; + case SEC_ERROR_BAD_SIGNATURE: + return CKR_SIGNATURE_INVALID; + case SEC_ERROR_INVALID_KEY: + return CKR_KEY_SIZE_RANGE; + case SEC_ERROR_BAD_KEY: /* an EC public key that fails validation */ + return CKR_KEY_SIZE_RANGE; /* the closest error code */ + case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM: + return CKR_TEMPLATE_INCONSISTENT; + /* EC functions set this error if NSS_DISABLE_ECC is defined */ + case SEC_ERROR_UNSUPPORTED_KEYALG: + return CKR_MECHANISM_INVALID; + case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE: + return CKR_DOMAIN_PARAMS_INVALID; + /* key pair generation failed after max number of attempts */ + case SEC_ERROR_NEED_RANDOM: + return CKR_FUNCTION_FAILED; } return CKR_DEVICE_ERROR; } @@ -139,10 +141,10 @@ static CK_RV sftk_MapDecryptError(int error) { switch (error) { - case SEC_ERROR_BAD_DATA: - return CKR_ENCRYPTED_DATA_INVALID; - default: - return sftk_MapCryptError(error); + case SEC_ERROR_BAD_DATA: + return CKR_ENCRYPTED_DATA_INVALID; + default: + return sftk_MapCryptError(error); } } @@ -155,11 +157,10 @@ sftk_MapVerifyError(int error) { CK_RV crv = sftk_MapCryptError(error); if (crv == CKR_DEVICE_ERROR) - crv = CKR_SIGNATURE_INVALID; + crv = CKR_SIGNATURE_INVALID; return crv; } - /* * turn a CDMF key into a des key. CDMF is an old IBM scheme to export DES by * Deprecating a full des key to 40 bit key strenth. @@ -171,45 +172,47 @@ sftk_cdmf2des(unsigned char *cdmfkey, unsigned char *deskey) unsigned char key2[8] = { 0xef, 0x2c, 0x04, 0x1c, 0xe6, 0x38, 0x2f, 0xe6 }; unsigned char enc_src[8]; unsigned char enc_dest[8]; - unsigned int leng,i; + unsigned int leng, i; DESContext *descx; SECStatus rv; - - + /* zero the parity bits */ - for (i=0; i < 8; i++) { - enc_src[i] = cdmfkey[i] & 0xfe; + for (i = 0; i < 8; i++) { + enc_src[i] = cdmfkey[i] & 0xfe; } /* encrypt with key 1 */ descx = DES_CreateContext(key1, NULL, NSS_DES, PR_TRUE); - if (descx == NULL) return CKR_HOST_MEMORY; + if (descx == NULL) + return CKR_HOST_MEMORY; rv = DES_Encrypt(descx, enc_dest, &leng, 8, enc_src, 8); - DES_DestroyContext(descx,PR_TRUE); - if (rv != SECSuccess) return sftk_MapCryptError(PORT_GetError()); + DES_DestroyContext(descx, PR_TRUE); + if (rv != SECSuccess) + return sftk_MapCryptError(PORT_GetError()); /* xor source with des, zero the parity bits and deprecate the key*/ - for (i=0; i < 8; i++) { - if (i & 1) { - enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0xfe; - } else { - enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0x0e; - } + for (i = 0; i < 8; i++) { + if (i & 1) { + enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0xfe; + } else { + enc_src[i] = (enc_src[i] ^ enc_dest[i]) & 0x0e; + } } /* encrypt with key 2 */ descx = DES_CreateContext(key2, NULL, NSS_DES, PR_TRUE); - if (descx == NULL) return CKR_HOST_MEMORY; + if (descx == NULL) + return CKR_HOST_MEMORY; rv = DES_Encrypt(descx, deskey, &leng, 8, enc_src, 8); - DES_DestroyContext(descx,PR_TRUE); - if (rv != SECSuccess) return sftk_MapCryptError(PORT_GetError()); + DES_DestroyContext(descx, PR_TRUE); + if (rv != SECSuccess) + return sftk_MapCryptError(PORT_GetError()); - /* set the corret parity on our new des key */ + /* set the corret parity on our new des key */ sftk_FormatDESKey(deskey, 8); return CKR_OK; } - /* NSC_DestroyObject destroys an object. */ CK_RV NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) @@ -222,7 +225,7 @@ NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) CHECK_FORK(); if (slot == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } /* * This whole block just makes sure we really can destroy the @@ -233,30 +236,30 @@ NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) return CKR_SESSION_HANDLE_INVALID; } - object = sftk_ObjectFromHandle(hObject,session); + object = sftk_ObjectFromHandle(hObject, session); if (object == NULL) { - sftk_FreeSession(session); - return CKR_OBJECT_HANDLE_INVALID; + sftk_FreeSession(session); + return CKR_OBJECT_HANDLE_INVALID; } /* don't destroy a private object if we aren't logged in */ if ((!slot->isLoggedIn) && (slot->needLogin) && - (sftk_isTrue(object,CKA_PRIVATE))) { - sftk_FreeSession(session); - sftk_FreeObject(object); - return CKR_USER_NOT_LOGGED_IN; + (sftk_isTrue(object, CKA_PRIVATE))) { + sftk_FreeSession(session); + sftk_FreeObject(object); + return CKR_USER_NOT_LOGGED_IN; } /* don't destroy a token object if we aren't in a rw session */ if (((session->info.flags & CKF_RW_SESSION) == 0) && - (sftk_isTrue(object,CKA_TOKEN))) { - sftk_FreeSession(session); - sftk_FreeObject(object); - return CKR_SESSION_READ_ONLY; + (sftk_isTrue(object, CKA_TOKEN))) { + sftk_FreeSession(session); + sftk_FreeObject(object); + return CKR_SESSION_READ_ONLY; } - sftk_DeleteObject(session,object); + sftk_DeleteObject(session, object); sftk_FreeSession(session); @@ -272,7 +275,6 @@ NSC_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) return (status != SFTK_DestroyFailure) ? CKR_OK : CKR_DEVICE_ERROR; } - /* ************** Crypto Functions: Utilities ************************ */ @@ -344,48 +346,48 @@ sftk_ValidateOaepParams(const CK_RSA_PKCS_OAEP_PARAMS *params) return PR_TRUE; } -/* +/* * return a context based on the SFTKContext type. */ SFTKSessionContext * sftk_ReturnContextByType(SFTKSession *session, SFTKContextType type) { switch (type) { - case SFTK_ENCRYPT: - case SFTK_DECRYPT: - return session->enc_context; - case SFTK_HASH: - return session->hash_context; - case SFTK_SIGN: - case SFTK_SIGN_RECOVER: - case SFTK_VERIFY: - case SFTK_VERIFY_RECOVER: - return session->hash_context; + case SFTK_ENCRYPT: + case SFTK_DECRYPT: + return session->enc_context; + case SFTK_HASH: + return session->hash_context; + case SFTK_SIGN: + case SFTK_SIGN_RECOVER: + case SFTK_VERIFY: + case SFTK_VERIFY_RECOVER: + return session->hash_context; } return NULL; } -/* +/* * change a context based on the SFTKContext type. */ void -sftk_SetContextByType(SFTKSession *session, SFTKContextType type, - SFTKSessionContext *context) +sftk_SetContextByType(SFTKSession *session, SFTKContextType type, + SFTKSessionContext *context) { switch (type) { - case SFTK_ENCRYPT: - case SFTK_DECRYPT: - session->enc_context = context; - break; - case SFTK_HASH: - session->hash_context = context; - break; - case SFTK_SIGN: - case SFTK_SIGN_RECOVER: - case SFTK_VERIFY: - case SFTK_VERIFY_RECOVER: - session->hash_context = context; - break; + case SFTK_ENCRYPT: + case SFTK_DECRYPT: + session->enc_context = context; + break; + case SFTK_HASH: + session->hash_context = context; + break; + case SFTK_SIGN: + case SFTK_SIGN_RECOVER: + case SFTK_VERIFY: + case SFTK_VERIFY_RECOVER: + session->hash_context = context; + break; } return; } @@ -398,25 +400,26 @@ sftk_SetContextByType(SFTKSession *session, SFTKContextType type, * pointer is returned, the caller is responsible for freeing it. */ static CK_RV -sftk_GetContext(CK_SESSION_HANDLE handle,SFTKSessionContext **contextPtr, - SFTKContextType type, PRBool needMulti, SFTKSession **sessionPtr) +sftk_GetContext(CK_SESSION_HANDLE handle, SFTKSessionContext **contextPtr, + SFTKContextType type, PRBool needMulti, SFTKSession **sessionPtr) { SFTKSession *session; SFTKSessionContext *context; session = sftk_SessionFromHandle(handle); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - context = sftk_ReturnContextByType(session,type); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + context = sftk_ReturnContextByType(session, type); /* make sure the context is valid */ - if((context==NULL)||(context->type!=type)||(needMulti&&!(context->multi))){ + if ((context == NULL) || (context->type != type) || (needMulti && !(context->multi))) { sftk_FreeSession(session); - return CKR_OPERATION_NOT_INITIALIZED; + return CKR_OPERATION_NOT_INITIALIZED; } *contextPtr = context; if (sessionPtr != NULL) { - *sessionPtr = session; + *sessionPtr = session; } else { - sftk_FreeSession(session); + sftk_FreeSession(session); } return CKR_OK; } @@ -425,11 +428,11 @@ sftk_GetContext(CK_SESSION_HANDLE handle,SFTKSessionContext **contextPtr, * Intuitive name for FreeContext/SetNullContext pair. */ static void -sftk_TerminateOp( SFTKSession *session, SFTKContextType ctype, - SFTKSessionContext *context ) +sftk_TerminateOp(SFTKSession *session, SFTKContextType ctype, + SFTKSessionContext *context) { - sftk_FreeContext( context ); - sftk_SetContextByType( session, ctype, NULL ); + sftk_FreeContext(context); + sftk_SetContextByType(session, ctype, NULL); } /* @@ -441,55 +444,55 @@ sftk_TerminateOp( SFTKSession *session, SFTKContextType ctype, * all need to do at the beginning. This is done here. */ static CK_RV -sftk_InitGeneric(SFTKSession *session,SFTKSessionContext **contextPtr, - SFTKContextType ctype,SFTKObject **keyPtr, - CK_OBJECT_HANDLE hKey, CK_KEY_TYPE *keyTypePtr, - CK_OBJECT_CLASS pubKeyType, CK_ATTRIBUTE_TYPE operation) +sftk_InitGeneric(SFTKSession *session, SFTKSessionContext **contextPtr, + SFTKContextType ctype, SFTKObject **keyPtr, + CK_OBJECT_HANDLE hKey, CK_KEY_TYPE *keyTypePtr, + CK_OBJECT_CLASS pubKeyType, CK_ATTRIBUTE_TYPE operation) { SFTKObject *key = NULL; SFTKAttribute *att; SFTKSessionContext *context; /* We can only init if there is not current context active */ - if (sftk_ReturnContextByType(session,ctype) != NULL) { - return CKR_OPERATION_ACTIVE; + if (sftk_ReturnContextByType(session, ctype) != NULL) { + return CKR_OPERATION_ACTIVE; } /* find the key */ if (keyPtr) { - key = sftk_ObjectFromHandle(hKey,session); + key = sftk_ObjectFromHandle(hKey, session); if (key == NULL) { - return CKR_KEY_HANDLE_INVALID; - } - - /* make sure it's a valid key for this operation */ - if (((key->objclass != CKO_SECRET_KEY) && (key->objclass != pubKeyType)) - || !sftk_isTrue(key,operation)) { - sftk_FreeObject(key); - return CKR_KEY_TYPE_INCONSISTENT; - } - /* get the key type */ - att = sftk_FindAttribute(key,CKA_KEY_TYPE); - if (att == NULL) { - sftk_FreeObject(key); - return CKR_KEY_TYPE_INCONSISTENT; - } - PORT_Assert(att->attrib.ulValueLen == sizeof(CK_KEY_TYPE)); - if (att->attrib.ulValueLen != sizeof(CK_KEY_TYPE)) { - sftk_FreeAttribute(att); - sftk_FreeObject(key); - return CKR_ATTRIBUTE_VALUE_INVALID; - } - PORT_Memcpy(keyTypePtr, att->attrib.pValue, sizeof(CK_KEY_TYPE)); - sftk_FreeAttribute(att); - *keyPtr = key; + return CKR_KEY_HANDLE_INVALID; + } + + /* make sure it's a valid key for this operation */ + if (((key->objclass != CKO_SECRET_KEY) && (key->objclass != pubKeyType)) || !sftk_isTrue(key, operation)) { + sftk_FreeObject(key); + return CKR_KEY_TYPE_INCONSISTENT; + } + /* get the key type */ + att = sftk_FindAttribute(key, CKA_KEY_TYPE); + if (att == NULL) { + sftk_FreeObject(key); + return CKR_KEY_TYPE_INCONSISTENT; + } + PORT_Assert(att->attrib.ulValueLen == sizeof(CK_KEY_TYPE)); + if (att->attrib.ulValueLen != sizeof(CK_KEY_TYPE)) { + sftk_FreeAttribute(att); + sftk_FreeObject(key); + return CKR_ATTRIBUTE_VALUE_INVALID; + } + PORT_Memcpy(keyTypePtr, att->attrib.pValue, sizeof(CK_KEY_TYPE)); + sftk_FreeAttribute(att); + *keyPtr = key; } /* allocate the context structure */ context = (SFTKSessionContext *)PORT_Alloc(sizeof(SFTKSessionContext)); if (context == NULL) { - if (key) sftk_FreeObject(key); - return CKR_HOST_MEMORY; + if (key) + sftk_FreeObject(key); + return CKR_HOST_MEMORY; } context->type = ctype; context->multi = PR_TRUE; @@ -510,17 +513,17 @@ static int sftk_aes_mode(CK_MECHANISM_TYPE mechanism) { switch (mechanism) { - case CKM_AES_CBC_PAD: - case CKM_AES_CBC: - return NSS_AES_CBC; - case CKM_AES_ECB: - return NSS_AES; - case CKM_AES_CTS: - return NSS_AES_CTS; - case CKM_AES_CTR: - return NSS_AES_CTR; - case CKM_AES_GCM: - return NSS_AES_GCM; + case CKM_AES_CBC_PAD: + case CKM_AES_CBC: + return NSS_AES_CBC; + case CKM_AES_ECB: + return NSS_AES; + case CKM_AES_CTS: + return NSS_AES_CTS; + case CKM_AES_CTR: + return NSS_AES_CTR; + case CKM_AES_GCM: + return NSS_AES_GCM; } return -1; } @@ -631,7 +634,7 @@ sftk_RSAEncryptOAEP(SFTKOAEPEncryptInfo *info, unsigned char *output, maskHashAlg = GetHashTypeFromMechanism(info->params->mgf); return RSA_EncryptOAEP(&info->key->u.rsa, hashAlg, maskHashAlg, - (const unsigned char*)info->params->pSourceData, + (const unsigned char *)info->params->pSourceData, info->params->ulSourceDataLen, NULL, 0, output, outputLen, maxLen, input, inputLen); } @@ -655,15 +658,111 @@ sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo *info, unsigned char *output, maskHashAlg = GetHashTypeFromMechanism(info->params->mgf); rv = RSA_DecryptOAEP(&info->key->u.rsa, hashAlg, maskHashAlg, - (const unsigned char*)info->params->pSourceData, + (const unsigned char *)info->params->pSourceData, info->params->ulSourceDataLen, output, outputLen, maxLen, input, inputLen); - if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { sftk_fatalError = PR_TRUE; } return rv; } +static SFTKChaCha20Poly1305Info * +sftk_ChaCha20Poly1305_CreateContext(const unsigned char *key, + unsigned int keyLen, + const CK_NSS_AEAD_PARAMS *params) +{ + SFTKChaCha20Poly1305Info *ctx; + + if (params->ulNonceLen != sizeof(ctx->nonce)) { + PORT_SetError(SEC_ERROR_INPUT_LEN); + return NULL; + } + + ctx = PORT_New(SFTKChaCha20Poly1305Info); + if (ctx == NULL) { + return NULL; + } + + if (ChaCha20Poly1305_InitContext(&ctx->freeblCtx, key, keyLen, + params->ulTagLen) != SECSuccess) { + PORT_Free(ctx); + return NULL; + } + + PORT_Memcpy(ctx->nonce, params->pNonce, sizeof(ctx->nonce)); + + /* AAD data and length must both be null, or both non-null. */ + PORT_Assert((params->pAAD == NULL) == (params->ulAADLen == 0)); + + if (params->ulAADLen > sizeof(ctx->ad)) { + /* Need to allocate an overflow buffer for the additional data. */ + ctx->adOverflow = (unsigned char *)PORT_Alloc(params->ulAADLen); + if (!ctx->adOverflow) { + PORT_Free(ctx); + return NULL; + } + PORT_Memcpy(ctx->adOverflow, params->pAAD, params->ulAADLen); + } else { + ctx->adOverflow = NULL; + if (params->pAAD) { + PORT_Memcpy(ctx->ad, params->pAAD, params->ulAADLen); + } + } + ctx->adLen = params->ulAADLen; + + return ctx; +} + +static void +sftk_ChaCha20Poly1305_DestroyContext(SFTKChaCha20Poly1305Info *ctx, + PRBool freeit) +{ + ChaCha20Poly1305_DestroyContext(&ctx->freeblCtx, PR_FALSE); + if (ctx->adOverflow != NULL) { + PORT_Free(ctx->adOverflow); + ctx->adOverflow = NULL; + } + ctx->adLen = 0; + if (freeit) { + PORT_Free(ctx); + } +} + +static SECStatus +sftk_ChaCha20Poly1305_Encrypt(const SFTKChaCha20Poly1305Info *ctx, + unsigned char *output, unsigned int *outputLen, + unsigned int maxOutputLen, + const unsigned char *input, unsigned int inputLen) +{ + const unsigned char *ad = ctx->adOverflow; + + if (ad == NULL) { + ad = ctx->ad; + } + + return ChaCha20Poly1305_Seal(&ctx->freeblCtx, output, outputLen, + maxOutputLen, input, inputLen, ctx->nonce, + sizeof(ctx->nonce), ad, ctx->adLen); +} + +static SECStatus +sftk_ChaCha20Poly1305_Decrypt(const SFTKChaCha20Poly1305Info *ctx, + unsigned char *output, unsigned int *outputLen, + unsigned int maxOutputLen, + const unsigned char *input, unsigned int inputLen) +{ + const unsigned char *ad = ctx->adOverflow; + + if (ad == NULL) { + ad = ctx->ad; + } + + return ChaCha20Poly1305_Open(&ctx->freeblCtx, output, outputLen, + maxOutputLen, input, inputLen, ctx->nonce, + sizeof(ctx->nonce), ad, ctx->adLen); +} + /** NSC_CryptInit initializes an encryption/Decryption operation. * * Always called by NSC_EncryptInit, NSC_DecryptInit, NSC_WrapKey,NSC_UnwrapKey. @@ -672,9 +771,9 @@ sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo *info, unsigned char *output, */ static CK_RV sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey, - CK_ATTRIBUTE_TYPE mechUsage, CK_ATTRIBUTE_TYPE keyUsage, - SFTKContextType contextType, PRBool isEncrypt) + CK_OBJECT_HANDLE hKey, + CK_ATTRIBUTE_TYPE mechUsage, CK_ATTRIBUTE_TYPE keyUsage, + SFTKContextType contextType, PRBool isEncrypt) { SFTKSession *session; SFTKObject *key; @@ -689,412 +788,439 @@ sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_RV crv = CKR_OK; unsigned effectiveKeyLength; unsigned char newdeskey[24]; - PRBool useNewKey=PR_FALSE; + PRBool useNewKey = PR_FALSE; int t; - crv = sftk_MechAllowsOperation(pMechanism->mechanism, mechUsage ); - if (crv != CKR_OK) - return crv; + crv = sftk_MechAllowsOperation(pMechanism->mechanism, mechUsage); + if (crv != CKR_OK) + return crv; session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + + crv = sftk_InitGeneric(session, &context, contextType, &key, hKey, &key_type, + isEncrypt ? CKO_PUBLIC_KEY : CKO_PRIVATE_KEY, keyUsage); - crv = sftk_InitGeneric(session,&context,contextType,&key,hKey,&key_type, - isEncrypt ?CKO_PUBLIC_KEY:CKO_PRIVATE_KEY, keyUsage); - if (crv != CKR_OK) { - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } context->doPad = PR_FALSE; - switch(pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->multi = PR_FALSE; - context->rsa = PR_TRUE; - if (isEncrypt) { - NSSLOWKEYPublicKey *pubKey = sftk_GetPubKey(key,CKK_RSA,&crv); - if (pubKey == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->maxLen = nsslowkey_PublicModulusLen(pubKey); - context->cipherInfo = (void *)pubKey; - context->update = (SFTKCipher) - (pMechanism->mechanism == CKM_RSA_X_509 - ? sftk_RSAEncryptRaw : sftk_RSAEncrypt); - } else { - NSSLOWKEYPrivateKey *privKey = sftk_GetPrivKey(key,CKK_RSA,&crv); - if (privKey == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->maxLen = nsslowkey_PrivateModulusLen(privKey); - context->cipherInfo = (void *)privKey; - context->update = (SFTKCipher) - (pMechanism->mechanism == CKM_RSA_X_509 - ? sftk_RSADecryptRaw : sftk_RSADecrypt); - } - context->destroy = sftk_Null; - break; - case CKM_RSA_PKCS_OAEP: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_OAEP_PARAMS) || - !sftk_ValidateOaepParams((CK_RSA_PKCS_OAEP_PARAMS*)pMechanism->pParameter)) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - context->multi = PR_FALSE; - context->rsa = PR_TRUE; - if (isEncrypt) { - SFTKOAEPEncryptInfo *info = PORT_New(SFTKOAEPEncryptInfo); - if (info == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - info->params = pMechanism->pParameter; - info->key = sftk_GetPubKey(key, CKK_RSA, &crv); - if (info->key == NULL) { - PORT_Free(info); - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->update = (SFTKCipher) sftk_RSAEncryptOAEP; - context->maxLen = nsslowkey_PublicModulusLen(info->key); - context->cipherInfo = info; - } else { - SFTKOAEPDecryptInfo *info = PORT_New(SFTKOAEPDecryptInfo); - if (info == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - info->params = pMechanism->pParameter; - info->key = sftk_GetPrivKey(key, CKK_RSA, &crv); - if (info->key == NULL) { - PORT_Free(info); - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->update = (SFTKCipher) sftk_RSADecryptOAEP; - context->maxLen = nsslowkey_PrivateModulusLen(info->key); - context->cipherInfo = info; - } - context->destroy = (SFTKDestroy) sftk_Space; - break; - case CKM_RC2_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_RC2_ECB: - case CKM_RC2_CBC: - context->blockSize = 8; - if (key_type != CKK_RC2) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - rc2_param = (CK_RC2_CBC_PARAMS *)pMechanism->pParameter; - effectiveKeyLength = (rc2_param->ulEffectiveBits+7)/8; - context->cipherInfo = - RC2_CreateContext((unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen, rc2_param->iv, - pMechanism->mechanism == CKM_RC2_ECB ? NSS_RC2 : - NSS_RC2_CBC,effectiveKeyLength); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? RC2_Encrypt : RC2_Decrypt); - context->destroy = (SFTKDestroy) RC2_DestroyContext; - break; + switch (pMechanism->mechanism) { + case CKM_RSA_PKCS: + case CKM_RSA_X_509: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->multi = PR_FALSE; + context->rsa = PR_TRUE; + if (isEncrypt) { + NSSLOWKEYPublicKey *pubKey = sftk_GetPubKey(key, CKK_RSA, &crv); + if (pubKey == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->maxLen = nsslowkey_PublicModulusLen(pubKey); + context->cipherInfo = (void *)pubKey; + context->update = (SFTKCipher)(pMechanism->mechanism == CKM_RSA_X_509 + ? sftk_RSAEncryptRaw + : sftk_RSAEncrypt); + } else { + NSSLOWKEYPrivateKey *privKey = sftk_GetPrivKey(key, CKK_RSA, &crv); + if (privKey == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->maxLen = nsslowkey_PrivateModulusLen(privKey); + context->cipherInfo = (void *)privKey; + context->update = (SFTKCipher)(pMechanism->mechanism == CKM_RSA_X_509 + ? sftk_RSADecryptRaw + : sftk_RSADecrypt); + } + context->destroy = sftk_Null; + break; + case CKM_RSA_PKCS_OAEP: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_OAEP_PARAMS) || + !sftk_ValidateOaepParams((CK_RSA_PKCS_OAEP_PARAMS *)pMechanism->pParameter)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + context->multi = PR_FALSE; + context->rsa = PR_TRUE; + if (isEncrypt) { + SFTKOAEPEncryptInfo *info = PORT_New(SFTKOAEPEncryptInfo); + if (info == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + info->params = pMechanism->pParameter; + info->key = sftk_GetPubKey(key, CKK_RSA, &crv); + if (info->key == NULL) { + PORT_Free(info); + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->update = (SFTKCipher)sftk_RSAEncryptOAEP; + context->maxLen = nsslowkey_PublicModulusLen(info->key); + context->cipherInfo = info; + } else { + SFTKOAEPDecryptInfo *info = PORT_New(SFTKOAEPDecryptInfo); + if (info == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + info->params = pMechanism->pParameter; + info->key = sftk_GetPrivKey(key, CKK_RSA, &crv); + if (info->key == NULL) { + PORT_Free(info); + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->update = (SFTKCipher)sftk_RSADecryptOAEP; + context->maxLen = nsslowkey_PrivateModulusLen(info->key); + context->cipherInfo = info; + } + context->destroy = (SFTKDestroy)sftk_Space; + break; + case CKM_RC2_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_RC2_ECB: + case CKM_RC2_CBC: + context->blockSize = 8; + if (key_type != CKK_RC2) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + rc2_param = (CK_RC2_CBC_PARAMS *)pMechanism->pParameter; + effectiveKeyLength = (rc2_param->ulEffectiveBits + 7) / 8; + context->cipherInfo = + RC2_CreateContext((unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen, rc2_param->iv, + pMechanism->mechanism == CKM_RC2_ECB ? NSS_RC2 : NSS_RC2_CBC, effectiveKeyLength); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? RC2_Encrypt : RC2_Decrypt); + context->destroy = (SFTKDestroy)RC2_DestroyContext; + break; #if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_RC5_ECB: - case CKM_RC5_CBC: - if (key_type != CKK_RC5) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - rc5_param = (CK_RC5_CBC_PARAMS *)pMechanism->pParameter; - context->blockSize = rc5_param->ulWordsize*2; - rc5Key.data = (unsigned char*)att->attrib.pValue; - rc5Key.len = att->attrib.ulValueLen; - context->cipherInfo = RC5_CreateContext(&rc5Key,rc5_param->ulRounds, - rc5_param->ulWordsize,rc5_param->pIv, - pMechanism->mechanism == CKM_RC5_ECB ? NSS_RC5 : NSS_RC5_CBC); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? RC5_Encrypt : RC5_Decrypt); - context->destroy = (SFTKDestroy) RC5_DestroyContext; - break; + case CKM_RC5_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_RC5_ECB: + case CKM_RC5_CBC: + if (key_type != CKK_RC5) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + rc5_param = (CK_RC5_CBC_PARAMS *)pMechanism->pParameter; + context->blockSize = rc5_param->ulWordsize * 2; + rc5Key.data = (unsigned char *)att->attrib.pValue; + rc5Key.len = att->attrib.ulValueLen; + context->cipherInfo = RC5_CreateContext(&rc5Key, rc5_param->ulRounds, + rc5_param->ulWordsize, rc5_param->pIv, + pMechanism->mechanism == CKM_RC5_ECB ? NSS_RC5 : NSS_RC5_CBC); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? RC5_Encrypt : RC5_Decrypt); + context->destroy = (SFTKDestroy)RC5_DestroyContext; + break; #endif - case CKM_RC4: - if (key_type != CKK_RC4) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = - RC4_CreateContext((unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; /* WRONG !!! */ - break; - } - context->update = (SFTKCipher) (isEncrypt ? RC4_Encrypt : RC4_Decrypt); - context->destroy = (SFTKDestroy) RC4_DestroyContext; - break; - case CKM_CDMF_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_CDMF_ECB: - case CKM_CDMF_CBC: - if (key_type != CKK_CDMF) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = (pMechanism->mechanism == CKM_CDMF_ECB) ? NSS_DES : NSS_DES_CBC; - if (crv != CKR_OK) break; - goto finish_des; - case CKM_DES_ECB: - if (key_type != CKK_DES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES; - goto finish_des; - case CKM_DES_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_DES_CBC: - if (key_type != CKK_DES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_CBC; - goto finish_des; - case CKM_DES3_ECB: - if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_EDE3; - goto finish_des; - case CKM_DES3_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_DES3_CBC: - if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - t = NSS_DES_EDE3_CBC; -finish_des: - context->blockSize = 8; - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - if (key_type == CKK_DES2 && - (t == NSS_DES_EDE3_CBC || t == NSS_DES_EDE3)) { - /* extend DES2 key to DES3 key. */ - memcpy(newdeskey, att->attrib.pValue, 16); - memcpy(newdeskey + 16, newdeskey, 8); - useNewKey=PR_TRUE; - } else if (key_type == CKK_CDMF) { - crv = sftk_cdmf2des((unsigned char*)att->attrib.pValue,newdeskey); - if (crv != CKR_OK) { - sftk_FreeAttribute(att); - break; - } - useNewKey=PR_TRUE; - } - context->cipherInfo = DES_CreateContext( - useNewKey ? newdeskey : (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter,t, isEncrypt); - if (useNewKey) - memset(newdeskey, 0, sizeof newdeskey); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? DES_Encrypt : DES_Decrypt); - context->destroy = (SFTKDestroy) DES_DestroyContext; - break; - case CKM_SEED_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_SEED_CBC: - if (!pMechanism->pParameter || - pMechanism->ulParameterLen != 16) { - crv = CKR_MECHANISM_PARAM_INVALID; + case CKM_RC4: + if (key_type != CKK_RC4) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = + RC4_CreateContext((unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; /* WRONG !!! */ + break; + } + context->update = (SFTKCipher)(isEncrypt ? RC4_Encrypt : RC4_Decrypt); + context->destroy = (SFTKDestroy)RC4_DestroyContext; break; - } + case CKM_CDMF_CBC_PAD: + context->doPad = PR_TRUE; /* fall thru */ - case CKM_SEED_ECB: - context->blockSize = 16; - if (key_type != CKK_SEED) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = SEED_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - pMechanism->mechanism == CKM_SEED_ECB ? NSS_SEED : NSS_SEED_CBC, - isEncrypt); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher)(isEncrypt ? SEED_Encrypt : SEED_Decrypt); - context->destroy = (SFTKDestroy) SEED_DestroyContext; - break; - - case CKM_CAMELLIA_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_CAMELLIA_CBC: - if (!pMechanism->pParameter || - pMechanism->ulParameterLen != 16) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - /* fall thru */ - case CKM_CAMELLIA_ECB: - context->blockSize = 16; - if (key_type != CKK_CAMELLIA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = Camellia_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - pMechanism->mechanism == - CKM_CAMELLIA_ECB ? NSS_CAMELLIA : NSS_CAMELLIA_CBC, - isEncrypt, att->attrib.ulValueLen); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? - Camellia_Encrypt : Camellia_Decrypt); - context->destroy = (SFTKDestroy) Camellia_DestroyContext; - break; - - case CKM_AES_CBC_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_AES_ECB: - case CKM_AES_CBC: - context->blockSize = 16; - case CKM_AES_CTS: - case CKM_AES_CTR: - case CKM_AES_GCM: - if (pMechanism->mechanism == CKM_AES_GCM) { - context->multi = PR_FALSE; - } - if (key_type != CKK_AES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = AES_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - sftk_aes_mode(pMechanism->mechanism), - isEncrypt, att->attrib.ulValueLen, 16); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? AES_Encrypt : AES_Decrypt); - context->destroy = (SFTKDestroy) AES_DestroyContext; - break; - - case CKM_NETSCAPE_AES_KEY_WRAP_PAD: - context->doPad = PR_TRUE; - /* fall thru */ - case CKM_NETSCAPE_AES_KEY_WRAP: - context->multi = PR_FALSE; - context->blockSize = 8; - if (key_type != CKK_AES) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att = sftk_FindAttribute(key,CKA_VALUE); - if (att == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - context->cipherInfo = AESKeyWrap_CreateContext( - (unsigned char*)att->attrib.pValue, - (unsigned char*)pMechanism->pParameter, - isEncrypt, att->attrib.ulValueLen); - sftk_FreeAttribute(att); - if (context->cipherInfo == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->update = (SFTKCipher) (isEncrypt ? AESKeyWrap_Encrypt - : AESKeyWrap_Decrypt); - context->destroy = (SFTKDestroy) AESKeyWrap_DestroyContext; - break; - - default: - crv = CKR_MECHANISM_INVALID; - break; + case CKM_CDMF_ECB: + case CKM_CDMF_CBC: + if (key_type != CKK_CDMF) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + t = (pMechanism->mechanism == CKM_CDMF_ECB) ? NSS_DES : NSS_DES_CBC; + goto finish_des; + case CKM_DES_ECB: + if (key_type != CKK_DES) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + t = NSS_DES; + goto finish_des; + case CKM_DES_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_DES_CBC: + if (key_type != CKK_DES) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + t = NSS_DES_CBC; + goto finish_des; + case CKM_DES3_ECB: + if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + t = NSS_DES_EDE3; + goto finish_des; + case CKM_DES3_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_DES3_CBC: + if ((key_type != CKK_DES2) && (key_type != CKK_DES3)) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + t = NSS_DES_EDE3_CBC; + finish_des: + context->blockSize = 8; + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + if (key_type == CKK_DES2 && + (t == NSS_DES_EDE3_CBC || t == NSS_DES_EDE3)) { + /* extend DES2 key to DES3 key. */ + memcpy(newdeskey, att->attrib.pValue, 16); + memcpy(newdeskey + 16, newdeskey, 8); + useNewKey = PR_TRUE; + } else if (key_type == CKK_CDMF) { + crv = sftk_cdmf2des((unsigned char *)att->attrib.pValue, newdeskey); + if (crv != CKR_OK) { + sftk_FreeAttribute(att); + break; + } + useNewKey = PR_TRUE; + } + context->cipherInfo = DES_CreateContext( + useNewKey ? newdeskey : (unsigned char *)att->attrib.pValue, + (unsigned char *)pMechanism->pParameter, t, isEncrypt); + if (useNewKey) + memset(newdeskey, 0, sizeof newdeskey); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? DES_Encrypt : DES_Decrypt); + context->destroy = (SFTKDestroy)DES_DestroyContext; + break; + case CKM_SEED_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_SEED_CBC: + if (!pMechanism->pParameter || + pMechanism->ulParameterLen != 16) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + /* fall thru */ + case CKM_SEED_ECB: + context->blockSize = 16; + if (key_type != CKK_SEED) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = SEED_CreateContext( + (unsigned char *)att->attrib.pValue, + (unsigned char *)pMechanism->pParameter, + pMechanism->mechanism == CKM_SEED_ECB ? NSS_SEED : NSS_SEED_CBC, + isEncrypt); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? SEED_Encrypt : SEED_Decrypt); + context->destroy = (SFTKDestroy)SEED_DestroyContext; + break; + + case CKM_CAMELLIA_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_CAMELLIA_CBC: + if (!pMechanism->pParameter || + pMechanism->ulParameterLen != 16) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + /* fall thru */ + case CKM_CAMELLIA_ECB: + context->blockSize = 16; + if (key_type != CKK_CAMELLIA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = Camellia_CreateContext( + (unsigned char *)att->attrib.pValue, + (unsigned char *)pMechanism->pParameter, + pMechanism->mechanism == + CKM_CAMELLIA_ECB + ? NSS_CAMELLIA + : NSS_CAMELLIA_CBC, + isEncrypt, att->attrib.ulValueLen); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? Camellia_Encrypt : Camellia_Decrypt); + context->destroy = (SFTKDestroy)Camellia_DestroyContext; + break; + + case CKM_AES_CBC_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_AES_ECB: + case CKM_AES_CBC: + context->blockSize = 16; + case CKM_AES_CTS: + case CKM_AES_CTR: + case CKM_AES_GCM: + if (pMechanism->mechanism == CKM_AES_GCM) { + context->multi = PR_FALSE; + } + if (key_type != CKK_AES) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = AES_CreateContext( + (unsigned char *)att->attrib.pValue, + (unsigned char *)pMechanism->pParameter, + sftk_aes_mode(pMechanism->mechanism), + isEncrypt, att->attrib.ulValueLen, 16); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? AES_Encrypt : AES_Decrypt); + context->destroy = (SFTKDestroy)AES_DestroyContext; + break; + + case CKM_NSS_CHACHA20_POLY1305: + if (pMechanism->ulParameterLen != sizeof(CK_NSS_AEAD_PARAMS)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + context->multi = PR_FALSE; + if (key_type != CKK_NSS_CHACHA20) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = sftk_ChaCha20Poly1305_CreateContext( + (unsigned char *)att->attrib.pValue, att->attrib.ulValueLen, + (CK_NSS_AEAD_PARAMS *)pMechanism->pParameter); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + context->update = (SFTKCipher)(isEncrypt ? sftk_ChaCha20Poly1305_Encrypt : sftk_ChaCha20Poly1305_Decrypt); + context->destroy = (SFTKDestroy)sftk_ChaCha20Poly1305_DestroyContext; + break; + + case CKM_NSS_AES_KEY_WRAP_PAD: + context->doPad = PR_TRUE; + /* fall thru */ + case CKM_NSS_AES_KEY_WRAP: + context->multi = PR_FALSE; + context->blockSize = 8; + if (key_type != CKK_AES) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att = sftk_FindAttribute(key, CKA_VALUE); + if (att == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + context->cipherInfo = AESKeyWrap_CreateContext( + (unsigned char *)att->attrib.pValue, + (unsigned char *)pMechanism->pParameter, + isEncrypt, att->attrib.ulValueLen); + sftk_FreeAttribute(att); + if (context->cipherInfo == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->update = (SFTKCipher)(isEncrypt ? AESKeyWrap_Encrypt + : AESKeyWrap_Decrypt); + context->destroy = (SFTKDestroy)AESKeyWrap_DestroyContext; + break; + + default: + crv = CKR_MECHANISM_INVALID; + break; } if (crv != CKR_OK) { sftk_FreeContext(context); - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } sftk_SetContextByType(session, contextType, context); sftk_FreeSession(session); @@ -1102,21 +1228,23 @@ finish_des: } /* NSC_EncryptInit initializes an encryption operation. */ -CK_RV NSC_EncryptInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +CK_RV +NSC_EncryptInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { CHECK_FORK(); return sftk_CryptInit(hSession, pMechanism, hKey, CKA_ENCRYPT, CKA_ENCRYPT, - SFTK_ENCRYPT, PR_TRUE); + SFTK_ENCRYPT, PR_TRUE); } /* NSC_EncryptUpdate continues a multiple-part encryption operation. */ -CK_RV NSC_EncryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) +CK_RV +NSC_EncryptUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { SFTKSessionContext *context; - unsigned int outlen,i; + unsigned int outlen, i; unsigned int padoutlen = 0; unsigned int maxout = *pulEncryptedPartLen; CK_RV crv; @@ -1125,79 +1253,79 @@ CK_RV NSC_EncryptUpdate(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_ENCRYPT,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_ENCRYPT, PR_TRUE, NULL); + if (crv != CKR_OK) + return crv; if (!pEncryptedPart) { - if (context->doPad) { - CK_ULONG totalDataAvailable = ulPartLen + context->padDataLength; - CK_ULONG blocksToSend = totalDataAvailable/context->blockSize; + if (context->doPad) { + CK_ULONG totalDataAvailable = ulPartLen + context->padDataLength; + CK_ULONG blocksToSend = totalDataAvailable / context->blockSize; - *pulEncryptedPartLen = blocksToSend * context->blockSize; - return CKR_OK; - } - *pulEncryptedPartLen = ulPartLen; - return CKR_OK; + *pulEncryptedPartLen = blocksToSend * context->blockSize; + return CKR_OK; + } + *pulEncryptedPartLen = ulPartLen; + return CKR_OK; } /* do padding */ if (context->doPad) { - /* deal with previous buffered data */ - if (context->padDataLength != 0) { - /* fill in the padded to a full block size */ - for (i=context->padDataLength; - (ulPartLen != 0) && i < context->blockSize; i++) { - context->padBuf[i] = *pPart++; - ulPartLen--; - context->padDataLength++; - } - - /* not enough data to encrypt yet? then return */ - if (context->padDataLength != context->blockSize) { - *pulEncryptedPartLen = 0; - return CKR_OK; - } - /* encrypt the current padded data */ - rv = (*context->update)(context->cipherInfo, pEncryptedPart, - &padoutlen, context->blockSize, context->padBuf, - context->blockSize); - if (rv != SECSuccess) { - return sftk_MapCryptError(PORT_GetError()); - } - pEncryptedPart += padoutlen; - maxout -= padoutlen; - } - /* save the residual */ - context->padDataLength = ulPartLen % context->blockSize; - if (context->padDataLength) { - PORT_Memcpy(context->padBuf, - &pPart[ulPartLen-context->padDataLength], - context->padDataLength); - ulPartLen -= context->padDataLength; - } - /* if we've exhausted our new buffer, we're done */ - if (ulPartLen == 0) { - *pulEncryptedPartLen = padoutlen; - return CKR_OK; - } - } + /* deal with previous buffered data */ + if (context->padDataLength != 0) { + /* fill in the padded to a full block size */ + for (i = context->padDataLength; + (ulPartLen != 0) && i < context->blockSize; i++) { + context->padBuf[i] = *pPart++; + ulPartLen--; + context->padDataLength++; + } + /* not enough data to encrypt yet? then return */ + if (context->padDataLength != context->blockSize) { + *pulEncryptedPartLen = 0; + return CKR_OK; + } + /* encrypt the current padded data */ + rv = (*context->update)(context->cipherInfo, pEncryptedPart, + &padoutlen, context->blockSize, context->padBuf, + context->blockSize); + if (rv != SECSuccess) { + return sftk_MapCryptError(PORT_GetError()); + } + pEncryptedPart += padoutlen; + maxout -= padoutlen; + } + /* save the residual */ + context->padDataLength = ulPartLen % context->blockSize; + if (context->padDataLength) { + PORT_Memcpy(context->padBuf, + &pPart[ulPartLen - context->padDataLength], + context->padDataLength); + ulPartLen -= context->padDataLength; + } + /* if we've exhausted our new buffer, we're done */ + if (ulPartLen == 0) { + *pulEncryptedPartLen = padoutlen; + return CKR_OK; + } + } /* do it: NOTE: this assumes buf size in is >= buf size out! */ - rv = (*context->update)(context->cipherInfo,pEncryptedPart, - &outlen, maxout, pPart, ulPartLen); - *pulEncryptedPartLen = (CK_ULONG) (outlen + padoutlen); + rv = (*context->update)(context->cipherInfo, pEncryptedPart, + &outlen, maxout, pPart, ulPartLen); + *pulEncryptedPartLen = (CK_ULONG)(outlen + padoutlen); return (rv == SECSuccess) ? CKR_OK : sftk_MapCryptError(PORT_GetError()); } - /* NSC_EncryptFinal finishes a multiple-part encryption operation. */ -CK_RV NSC_EncryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen) +CK_RV +NSC_EncryptFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen) { SFTKSession *session; SFTKSessionContext *context; - unsigned int outlen,i; + unsigned int outlen, i; unsigned int maxout = *pulLastEncryptedPartLen; CK_RV crv; SECStatus rv = SECSuccess; @@ -1206,43 +1334,45 @@ CK_RV NSC_EncryptFinal(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_ENCRYPT,PR_TRUE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_ENCRYPT, PR_TRUE, &session); + if (crv != CKR_OK) + return crv; *pulLastEncryptedPartLen = 0; if (!pLastEncryptedPart) { - /* caller is checking the amount of remaining data */ - if (context->blockSize > 0 && context->doPad) { - *pulLastEncryptedPartLen = context->blockSize; - contextFinished = PR_FALSE; /* still have padding to go */ - } - goto finish; + /* caller is checking the amount of remaining data */ + if (context->blockSize > 0 && context->doPad) { + *pulLastEncryptedPartLen = context->blockSize; + contextFinished = PR_FALSE; /* still have padding to go */ + } + goto finish; } /* do padding */ if (context->doPad) { - unsigned char padbyte = (unsigned char) - (context->blockSize - context->padDataLength); - /* fill out rest of pad buffer with pad magic*/ - for (i=context->padDataLength; i < context->blockSize; i++) { - context->padBuf[i] = padbyte; - } - rv = (*context->update)(context->cipherInfo,pLastEncryptedPart, - &outlen, maxout, context->padBuf, context->blockSize); - if (rv == SECSuccess) *pulLastEncryptedPartLen = (CK_ULONG) outlen; + unsigned char padbyte = (unsigned char)(context->blockSize - context->padDataLength); + /* fill out rest of pad buffer with pad magic*/ + for (i = context->padDataLength; i < context->blockSize; i++) { + context->padBuf[i] = padbyte; + } + rv = (*context->update)(context->cipherInfo, pLastEncryptedPart, + &outlen, maxout, context->padBuf, context->blockSize); + if (rv == SECSuccess) + *pulLastEncryptedPartLen = (CK_ULONG)outlen; } finish: if (contextFinished) - sftk_TerminateOp( session, SFTK_ENCRYPT, context ); + sftk_TerminateOp(session, SFTK_ENCRYPT, context); sftk_FreeSession(session); return (rv == SECSuccess) ? CKR_OK : sftk_MapCryptError(PORT_GetError()); } /* NSC_Encrypt encrypts single-part data. */ -CK_RV NSC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, - CK_ULONG_PTR pulEncryptedDataLen) +CK_RV +NSC_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, + CK_ULONG_PTR pulEncryptedDataLen) { SFTKSession *session; SFTKSessionContext *context; @@ -1251,94 +1381,95 @@ CK_RV NSC_Encrypt (CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_RV crv; CK_RV crv2; SECStatus rv = SECSuccess; - SECItem pText; + SECItem pText; pText.type = siBuffer; pText.data = pData; - pText.len = ulDataLen; + pText.len = ulDataLen; CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_ENCRYPT,PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_ENCRYPT, PR_FALSE, &session); + if (crv != CKR_OK) + return crv; if (!pEncryptedData) { - *pulEncryptedDataLen = context->rsa ? context->maxLen : - ulDataLen + 2 * context->blockSize; - goto finish; + *pulEncryptedDataLen = context->rsa ? context->maxLen : ulDataLen + 2 * context->blockSize; + goto finish; } if (context->doPad) { - if (context->multi) { - CK_ULONG finalLen; - /* padding is fairly complicated, have the update and final - * code deal with it */ - sftk_FreeSession(session); - crv = NSC_EncryptUpdate(hSession, pData, ulDataLen, pEncryptedData, - pulEncryptedDataLen); - if (crv != CKR_OK) - *pulEncryptedDataLen = 0; - maxoutlen -= *pulEncryptedDataLen; - pEncryptedData += *pulEncryptedDataLen; - finalLen = maxoutlen; - crv2 = NSC_EncryptFinal(hSession, pEncryptedData, &finalLen); - if (crv2 == CKR_OK) - *pulEncryptedDataLen += finalLen; - return crv == CKR_OK ? crv2 : crv; - } - /* doPad without multi means that padding must be done on the first - ** and only update. There will be no final. - */ - PORT_Assert(context->blockSize > 1); - if (context->blockSize > 1) { - CK_ULONG remainder = ulDataLen % context->blockSize; - CK_ULONG padding = context->blockSize - remainder; - pText.len += padding; - pText.data = PORT_ZAlloc(pText.len); - if (pText.data) { - memcpy(pText.data, pData, ulDataLen); - memset(pText.data + ulDataLen, padding, padding); - } else { - crv = CKR_HOST_MEMORY; - goto fail; - } - } + if (context->multi) { + CK_ULONG finalLen; + /* padding is fairly complicated, have the update and final + * code deal with it */ + sftk_FreeSession(session); + crv = NSC_EncryptUpdate(hSession, pData, ulDataLen, pEncryptedData, + pulEncryptedDataLen); + if (crv != CKR_OK) + *pulEncryptedDataLen = 0; + maxoutlen -= *pulEncryptedDataLen; + pEncryptedData += *pulEncryptedDataLen; + finalLen = maxoutlen; + crv2 = NSC_EncryptFinal(hSession, pEncryptedData, &finalLen); + if (crv2 == CKR_OK) + *pulEncryptedDataLen += finalLen; + return crv == CKR_OK ? crv2 : crv; + } + /* doPad without multi means that padding must be done on the first + ** and only update. There will be no final. + */ + PORT_Assert(context->blockSize > 1); + if (context->blockSize > 1) { + CK_ULONG remainder = ulDataLen % context->blockSize; + CK_ULONG padding = context->blockSize - remainder; + pText.len += padding; + pText.data = PORT_ZAlloc(pText.len); + if (pText.data) { + memcpy(pText.data, pData, ulDataLen); + memset(pText.data + ulDataLen, padding, padding); + } else { + crv = CKR_HOST_MEMORY; + goto fail; + } + } } /* do it: NOTE: this assumes buf size is big enough. */ - rv = (*context->update)(context->cipherInfo, pEncryptedData, - &outlen, maxoutlen, pText.data, pText.len); + rv = (*context->update)(context->cipherInfo, pEncryptedData, + &outlen, maxoutlen, pText.data, pText.len); crv = (rv == SECSuccess) ? CKR_OK : sftk_MapCryptError(PORT_GetError()); - *pulEncryptedDataLen = (CK_ULONG) outlen; + *pulEncryptedDataLen = (CK_ULONG)outlen; if (pText.data != pData) - PORT_ZFree(pText.data, pText.len); + PORT_ZFree(pText.data, pText.len); fail: - sftk_TerminateOp( session, SFTK_ENCRYPT, context ); + sftk_TerminateOp(session, SFTK_ENCRYPT, context); finish: sftk_FreeSession(session); return crv; } - /* ************** Crypto Functions: Decrypt ************************ */ /* NSC_DecryptInit initializes a decryption operation. */ -CK_RV NSC_DecryptInit( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +CK_RV +NSC_DecryptInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { CHECK_FORK(); return sftk_CryptInit(hSession, pMechanism, hKey, CKA_DECRYPT, CKA_DECRYPT, - SFTK_DECRYPT, PR_FALSE); + SFTK_DECRYPT, PR_FALSE); } /* NSC_DecryptUpdate continues a multiple-part decryption operation. */ -CK_RV NSC_DecryptUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) +CK_RV +NSC_DecryptUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { SFTKSessionContext *context; unsigned int padoutlen = 0; @@ -1350,69 +1481,70 @@ CK_RV NSC_DecryptUpdate(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_DECRYPT,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_DECRYPT, PR_TRUE, NULL); + if (crv != CKR_OK) + return crv; /* this can only happen on an NSS programming error */ - PORT_Assert((context->padDataLength == 0) - || context->padDataLength == context->blockSize); - + PORT_Assert((context->padDataLength == 0) || context->padDataLength == context->blockSize); if (context->doPad) { - /* Check the data length for block ciphers. If we are padding, - * then we must be using a block cipher. In the non-padding case - * the error will be returned by the underlying decryption - * function when we do the actual decrypt. We need to do the - * check here to avoid returning a negative length to the caller - * or reading before the beginning of the pEncryptedPart buffer. - */ - if ((ulEncryptedPartLen == 0) || - (ulEncryptedPartLen % context->blockSize) != 0) { - return CKR_ENCRYPTED_DATA_LEN_RANGE; - } + /* Check the data length for block ciphers. If we are padding, + * then we must be using a block cipher. In the non-padding case + * the error will be returned by the underlying decryption + * function when we do the actual decrypt. We need to do the + * check here to avoid returning a negative length to the caller + * or reading before the beginning of the pEncryptedPart buffer. + */ + if ((ulEncryptedPartLen == 0) || + (ulEncryptedPartLen % context->blockSize) != 0) { + return CKR_ENCRYPTED_DATA_LEN_RANGE; + } } if (!pPart) { - if (context->doPad) { - *pulPartLen = - ulEncryptedPartLen + context->padDataLength - context->blockSize; - return CKR_OK; - } - /* for stream ciphers there is are no constraints on ulEncryptedPartLen. - * for block ciphers, it must be a multiple of blockSize. The error is - * detected when this function is called again do decrypt the output. - */ - *pulPartLen = ulEncryptedPartLen; - return CKR_OK; + if (context->doPad) { + *pulPartLen = + ulEncryptedPartLen + context->padDataLength - context->blockSize; + return CKR_OK; + } + /* for stream ciphers there is are no constraints on ulEncryptedPartLen. + * for block ciphers, it must be a multiple of blockSize. The error is + * detected when this function is called again do decrypt the output. + */ + *pulPartLen = ulEncryptedPartLen; + return CKR_OK; } if (context->doPad) { - /* first decrypt our saved buffer */ - if (context->padDataLength != 0) { - rv = (*context->update)(context->cipherInfo, pPart, &padoutlen, - maxout, context->padBuf, context->blockSize); - if (rv != SECSuccess) return sftk_MapDecryptError(PORT_GetError()); - pPart += padoutlen; - maxout -= padoutlen; - } - /* now save the final block for the next decrypt or the final */ - PORT_Memcpy(context->padBuf,&pEncryptedPart[ulEncryptedPartLen - - context->blockSize], context->blockSize); - context->padDataLength = context->blockSize; - ulEncryptedPartLen -= context->padDataLength; + /* first decrypt our saved buffer */ + if (context->padDataLength != 0) { + rv = (*context->update)(context->cipherInfo, pPart, &padoutlen, + maxout, context->padBuf, context->blockSize); + if (rv != SECSuccess) + return sftk_MapDecryptError(PORT_GetError()); + pPart += padoutlen; + maxout -= padoutlen; + } + /* now save the final block for the next decrypt or the final */ + PORT_Memcpy(context->padBuf, &pEncryptedPart[ulEncryptedPartLen - + context->blockSize], + context->blockSize); + context->padDataLength = context->blockSize; + ulEncryptedPartLen -= context->padDataLength; } /* do it: NOTE: this assumes buf size in is >= buf size out! */ - rv = (*context->update)(context->cipherInfo,pPart, &outlen, - maxout, pEncryptedPart, ulEncryptedPartLen); - *pulPartLen = (CK_ULONG) (outlen + padoutlen); - return (rv == SECSuccess) ? CKR_OK : sftk_MapDecryptError(PORT_GetError()); + rv = (*context->update)(context->cipherInfo, pPart, &outlen, + maxout, pEncryptedPart, ulEncryptedPartLen); + *pulPartLen = (CK_ULONG)(outlen + padoutlen); + return (rv == SECSuccess) ? CKR_OK : sftk_MapDecryptError(PORT_GetError()); } - /* NSC_DecryptFinal finishes a multiple-part decryption operation. */ -CK_RV NSC_DecryptFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen) +CK_RV +NSC_DecryptFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen) { SFTKSession *session; SFTKSessionContext *context; @@ -1424,60 +1556,62 @@ CK_RV NSC_DecryptFinal(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_DECRYPT,PR_TRUE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_DECRYPT, PR_TRUE, &session); + if (crv != CKR_OK) + return crv; *pulLastPartLen = 0; if (!pLastPart) { - /* caller is checking the amount of remaining data */ - if (context->padDataLength > 0) { - *pulLastPartLen = context->padDataLength; - } - goto finish; + /* caller is checking the amount of remaining data */ + if (context->padDataLength > 0) { + *pulLastPartLen = context->padDataLength; + } + goto finish; } if (context->doPad) { - /* decrypt our saved buffer */ - if (context->padDataLength != 0) { - /* this assumes that pLastPart is big enough to hold the *whole* - * buffer!!! */ - rv = (*context->update)(context->cipherInfo, pLastPart, &outlen, - maxout, context->padBuf, context->blockSize); - if (rv != SECSuccess) { - crv = sftk_MapDecryptError(PORT_GetError()); - } else { - unsigned int padSize = - (unsigned int) pLastPart[context->blockSize-1]; - if ((padSize > context->blockSize) || (padSize == 0)) { - crv = CKR_ENCRYPTED_DATA_INVALID; - } else { - unsigned int i; - unsigned int badPadding = 0; /* used as a boolean */ - for (i = 0; i < padSize; i++) { - badPadding |= - (unsigned int) pLastPart[context->blockSize-1-i] ^ - padSize; - } - if (badPadding) { - crv = CKR_ENCRYPTED_DATA_INVALID; - } else { - *pulLastPartLen = outlen - padSize; - } - } - } - } - } - - sftk_TerminateOp( session, SFTK_DECRYPT, context ); + /* decrypt our saved buffer */ + if (context->padDataLength != 0) { + /* this assumes that pLastPart is big enough to hold the *whole* + * buffer!!! */ + rv = (*context->update)(context->cipherInfo, pLastPart, &outlen, + maxout, context->padBuf, context->blockSize); + if (rv != SECSuccess) { + crv = sftk_MapDecryptError(PORT_GetError()); + } else { + unsigned int padSize = + (unsigned int)pLastPart[context->blockSize - 1]; + if ((padSize > context->blockSize) || (padSize == 0)) { + crv = CKR_ENCRYPTED_DATA_INVALID; + } else { + unsigned int i; + unsigned int badPadding = 0; /* used as a boolean */ + for (i = 0; i < padSize; i++) { + badPadding |= + (unsigned int)pLastPart[context->blockSize - 1 - i] ^ + padSize; + } + if (badPadding) { + crv = CKR_ENCRYPTED_DATA_INVALID; + } else { + *pulLastPartLen = outlen - padSize; + } + } + } + } + } + + sftk_TerminateOp(session, SFTK_DECRYPT, context); finish: sftk_FreeSession(session); return crv; } /* NSC_Decrypt decrypts encrypted data in a single part. */ -CK_RV NSC_Decrypt(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData,CK_ULONG ulEncryptedDataLen,CK_BYTE_PTR pData, - CK_ULONG_PTR pulDataLen) +CK_RV +NSC_Decrypt(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, + CK_ULONG_PTR pulDataLen) { SFTKSession *session; SFTKSessionContext *context; @@ -1490,69 +1624,69 @@ CK_RV NSC_Decrypt(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_DECRYPT,PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_DECRYPT, PR_FALSE, &session); + if (crv != CKR_OK) + return crv; if (!pData) { - *pulDataLen = ulEncryptedDataLen + context->blockSize; - goto finish; + *pulDataLen = ulEncryptedDataLen + context->blockSize; + goto finish; } if (context->doPad && context->multi) { - CK_ULONG finalLen; - /* padding is fairly complicated, have the update and final - * code deal with it */ - sftk_FreeSession(session); - crv = NSC_DecryptUpdate(hSession,pEncryptedData,ulEncryptedDataLen, - pData, pulDataLen); - if (crv != CKR_OK) - *pulDataLen = 0; - maxoutlen -= *pulDataLen; - pData += *pulDataLen; - finalLen = maxoutlen; - crv2 = NSC_DecryptFinal(hSession, pData, &finalLen); - if (crv2 == CKR_OK) - *pulDataLen += finalLen; - return crv == CKR_OK ? crv2 : crv; - } - - rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, - pEncryptedData, ulEncryptedDataLen); + CK_ULONG finalLen; + /* padding is fairly complicated, have the update and final + * code deal with it */ + sftk_FreeSession(session); + crv = NSC_DecryptUpdate(hSession, pEncryptedData, ulEncryptedDataLen, + pData, pulDataLen); + if (crv != CKR_OK) + *pulDataLen = 0; + maxoutlen -= *pulDataLen; + pData += *pulDataLen; + finalLen = maxoutlen; + crv2 = NSC_DecryptFinal(hSession, pData, &finalLen); + if (crv2 == CKR_OK) + *pulDataLen += finalLen; + return crv == CKR_OK ? crv2 : crv; + } + + rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, + pEncryptedData, ulEncryptedDataLen); /* XXX need to do MUCH better error mapping than this. */ crv = (rv == SECSuccess) ? CKR_OK : sftk_MapDecryptError(PORT_GetError()); if (rv == SECSuccess && context->doPad) { - unsigned int padding = pData[outlen - 1]; - if (padding > context->blockSize || !padding) { - crv = CKR_ENCRYPTED_DATA_INVALID; - } else { - unsigned int i; - unsigned int badPadding = 0; /* used as a boolean */ - for (i = 0; i < padding; i++) { - badPadding |= (unsigned int) pData[outlen - 1 - i] ^ padding; - } - if (badPadding) { - crv = CKR_ENCRYPTED_DATA_INVALID; - } else { - outlen -= padding; - } - } - } - *pulDataLen = (CK_ULONG) outlen; - sftk_TerminateOp( session, SFTK_DECRYPT, context ); + unsigned int padding = pData[outlen - 1]; + if (padding > context->blockSize || !padding) { + crv = CKR_ENCRYPTED_DATA_INVALID; + } else { + unsigned int i; + unsigned int badPadding = 0; /* used as a boolean */ + for (i = 0; i < padding; i++) { + badPadding |= (unsigned int)pData[outlen - 1 - i] ^ padding; + } + if (badPadding) { + crv = CKR_ENCRYPTED_DATA_INVALID; + } else { + outlen -= padding; + } + } + } + *pulDataLen = (CK_ULONG)outlen; + sftk_TerminateOp(session, SFTK_DECRYPT, context); finish: sftk_FreeSession(session); return crv; } - - /* ************** Crypto Functions: Digest (HASH) ************************ */ /* NSC_DigestInit initializes a message-digesting operation. */ -CK_RV NSC_DigestInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism) +CK_RV +NSC_DigestInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism) { SFTKSession *session; SFTKSessionContext *context; @@ -1561,61 +1695,60 @@ CK_RV NSC_DigestInit(CK_SESSION_HANDLE hSession, CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) - return CKR_SESSION_HANDLE_INVALID; - crv = sftk_InitGeneric(session,&context,SFTK_HASH,NULL,0,NULL, 0, 0); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + crv = sftk_InitGeneric(session, &context, SFTK_HASH, NULL, 0, NULL, 0, 0); if (crv != CKR_OK) { - sftk_FreeSession(session); - return crv; - } - - -#define INIT_MECH(mech,mmm) \ - case mech: { \ - mmm ## Context * mmm ## _ctx = mmm ## _NewContext(); \ - context->cipherInfo = (void *)mmm ## _ctx; \ - context->cipherInfoLen = mmm ## _FlattenSize(mmm ## _ctx); \ - context->currentMech = mech; \ - context->hashUpdate = (SFTKHash) mmm ## _Update; \ - context->end = (SFTKEnd) mmm ## _End; \ - context->destroy = (SFTKDestroy) mmm ## _DestroyContext; \ - context->maxLen = mmm ## _LENGTH; \ - if (mmm ## _ctx) \ - mmm ## _Begin(mmm ## _ctx); \ - else \ - crv = CKR_HOST_MEMORY; \ - break; \ - } - - switch(pMechanism->mechanism) { - INIT_MECH(CKM_MD2, MD2) - INIT_MECH(CKM_MD5, MD5) - INIT_MECH(CKM_SHA_1, SHA1) - INIT_MECH(CKM_SHA224, SHA224) - INIT_MECH(CKM_SHA256, SHA256) - INIT_MECH(CKM_SHA384, SHA384) - INIT_MECH(CKM_SHA512, SHA512) - - default: - crv = CKR_MECHANISM_INVALID; - break; + sftk_FreeSession(session); + return crv; + } + +#define INIT_MECH(mech, mmm) \ + case mech: { \ + mmm##Context *mmm##_ctx = mmm##_NewContext(); \ + context->cipherInfo = (void *)mmm##_ctx; \ + context->cipherInfoLen = mmm##_FlattenSize(mmm##_ctx); \ + context->currentMech = mech; \ + context->hashUpdate = (SFTKHash)mmm##_Update; \ + context->end = (SFTKEnd)mmm##_End; \ + context->destroy = (SFTKDestroy)mmm##_DestroyContext; \ + context->maxLen = mmm##_LENGTH; \ + if (mmm##_ctx) \ + mmm##_Begin(mmm##_ctx); \ + else \ + crv = CKR_HOST_MEMORY; \ + break; \ + } + + switch (pMechanism->mechanism) { + INIT_MECH(CKM_MD2, MD2) + INIT_MECH(CKM_MD5, MD5) + INIT_MECH(CKM_SHA_1, SHA1) + INIT_MECH(CKM_SHA224, SHA224) + INIT_MECH(CKM_SHA256, SHA256) + INIT_MECH(CKM_SHA384, SHA384) + INIT_MECH(CKM_SHA512, SHA512) + + default: + crv = CKR_MECHANISM_INVALID; + break; } if (crv != CKR_OK) { sftk_FreeContext(context); - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } sftk_SetContextByType(session, SFTK_HASH, context); sftk_FreeSession(session); return CKR_OK; } - /* NSC_Digest digests data in a single part. */ -CK_RV NSC_Digest(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen) +CK_RV +NSC_Digest(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen) { SFTKSession *session; SFTKSessionContext *context; @@ -1626,30 +1759,31 @@ CK_RV NSC_Digest(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_HASH,PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_FALSE, &session); + if (crv != CKR_OK) + return crv; if (pDigest == NULL) { - *pulDigestLen = context->maxLen; - goto finish; + *pulDigestLen = context->maxLen; + goto finish; } /* do it: */ (*context->hashUpdate)(context->cipherInfo, pData, ulDataLen); /* NOTE: this assumes buf size is bigenough for the algorithm */ - (*context->end)(context->cipherInfo, pDigest, &digestLen,maxout); + (*context->end)(context->cipherInfo, pDigest, &digestLen, maxout); *pulDigestLen = digestLen; - sftk_TerminateOp( session, SFTK_HASH, context ); + sftk_TerminateOp(session, SFTK_HASH, context); finish: sftk_FreeSession(session); return CKR_OK; } - /* NSC_DigestUpdate continues a multiple-part message-digesting operation. */ -CK_RV NSC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) +CK_RV +NSC_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen) { SFTKSessionContext *context; CK_RV crv; @@ -1657,17 +1791,18 @@ CK_RV NSC_DigestUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_HASH,PR_TRUE,NULL); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_TRUE, NULL); + if (crv != CKR_OK) + return crv; /* do it: */ (*context->hashUpdate)(context->cipherInfo, pPart, ulPartLen); return CKR_OK; } - /* NSC_DigestFinal finishes a multiple-part message-digesting operation. */ -CK_RV NSC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, - CK_ULONG_PTR pulDigestLen) +CK_RV +NSC_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, + CK_ULONG_PTR pulDigestLen) { SFTKSession *session; SFTKSessionContext *context; @@ -1679,14 +1814,15 @@ CK_RV NSC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, /* make sure we're legal */ crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_TRUE, &session); - if (crv != CKR_OK) return crv; + if (crv != CKR_OK) + return crv; if (pDigest != NULL) { (*context->end)(context->cipherInfo, pDigest, &digestLen, maxout); *pulDigestLen = digestLen; - sftk_TerminateOp( session, SFTK_HASH, context ); + sftk_TerminateOp(session, SFTK_HASH, context); } else { - *pulDigestLen = context->maxLen; + *pulDigestLen = context->maxLen; } sftk_FreeSession(session); @@ -1695,22 +1831,23 @@ CK_RV NSC_DigestFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pDigest, /* * these helper functions are used by Generic Macing and Signing functions - * that use hashes as part of their operations. + * that use hashes as part of their operations. */ -#define DOSUB(mmm) \ -static CK_RV \ -sftk_doSub ## mmm(SFTKSessionContext *context) { \ - mmm ## Context * mmm ## _ctx = mmm ## _NewContext(); \ - context->hashInfo = (void *) mmm ## _ctx; \ - context->hashUpdate = (SFTKHash) mmm ## _Update; \ - context->end = (SFTKEnd) mmm ## _End; \ - context->hashdestroy = (SFTKDestroy) mmm ## _DestroyContext; \ - if (!context->hashInfo) { \ - return CKR_HOST_MEMORY; \ - } \ - mmm ## _Begin( mmm ## _ctx ); \ - return CKR_OK; \ -} +#define DOSUB(mmm) \ + static CK_RV \ + sftk_doSub##mmm(SFTKSessionContext *context) \ + { \ + mmm##Context *mmm##_ctx = mmm##_NewContext(); \ + context->hashInfo = (void *)mmm##_ctx; \ + context->hashUpdate = (SFTKHash)mmm##_Update; \ + context->end = (SFTKEnd)mmm##_End; \ + context->hashdestroy = (SFTKDestroy)mmm##_DestroyContext; \ + if (!context->hashInfo) { \ + return CKR_HOST_MEMORY; \ + } \ + mmm##_Begin(mmm##_ctx); \ + return CKR_OK; \ + } DOSUB(MD2) DOSUB(MD5) @@ -1722,40 +1859,40 @@ DOSUB(SHA512) static SECStatus sftk_SignCopy( - CK_ULONG *copyLen, - void *out, unsigned int *outLength, - unsigned int maxLength, - const unsigned char *hashResult, - unsigned int hashResultLength) + CK_ULONG *copyLen, + void *out, unsigned int *outLength, + unsigned int maxLength, + const unsigned char *hashResult, + unsigned int hashResultLength) { unsigned int toCopy = *copyLen; if (toCopy > maxLength) { - toCopy = maxLength; + toCopy = maxLength; } if (toCopy > hashResultLength) { - toCopy = hashResultLength; + toCopy = hashResultLength; } memcpy(out, hashResult, toCopy); if (outLength) { - *outLength = toCopy; + *outLength = toCopy; } return SECSuccess; } /* Verify is just a compare for HMAC */ static SECStatus -sftk_HMACCmp(CK_ULONG *copyLen,unsigned char *sig,unsigned int sigLen, - unsigned char *hash, unsigned int hashLen) +sftk_HMACCmp(CK_ULONG *copyLen, unsigned char *sig, unsigned int sigLen, + unsigned char *hash, unsigned int hashLen) { - return (PORT_Memcmp(sig,hash,*copyLen) == 0) ? SECSuccess : SECFailure ; + return (PORT_Memcmp(sig, hash, *copyLen) == 0) ? SECSuccess : SECFailure; } /* * common HMAC initalization routine */ static CK_RV -sftk_doHMACInit(SFTKSessionContext *context,HASH_HashType hash, - SFTKObject *key, CK_ULONG mac_size) +sftk_doHMACInit(SFTKSessionContext *context, HASH_HashType hash, + SFTKObject *key, CK_ULONG mac_size) { SFTKAttribute *keyval; HMACContext *HMACcontext; @@ -1764,38 +1901,39 @@ sftk_doHMACInit(SFTKSessionContext *context,HASH_HashType hash, PRBool isFIPS = (key->slot->slotID == FIPS_SLOT_ID); /* required by FIPS 198 Section 4 */ - if (isFIPS && (mac_size < 4 || mac_size < hashObj->length/2)) { - return CKR_BUFFER_TOO_SMALL; + if (isFIPS && (mac_size < 4 || mac_size < hashObj->length / 2)) { + return CKR_BUFFER_TOO_SMALL; } - keyval = sftk_FindAttribute(key,CKA_VALUE); - if (keyval == NULL) return CKR_KEY_SIZE_RANGE; + keyval = sftk_FindAttribute(key, CKA_VALUE); + if (keyval == NULL) + return CKR_KEY_SIZE_RANGE; - HMACcontext = HMAC_Create(hashObj, - (const unsigned char*)keyval->attrib.pValue, - keyval->attrib.ulValueLen, isFIPS); + HMACcontext = HMAC_Create(hashObj, + (const unsigned char *)keyval->attrib.pValue, + keyval->attrib.ulValueLen, isFIPS); context->hashInfo = HMACcontext; context->multi = PR_TRUE; sftk_FreeAttribute(keyval); if (context->hashInfo == NULL) { - if (PORT_GetError() == SEC_ERROR_INVALID_ARGS) { - return CKR_KEY_SIZE_RANGE; - } - return CKR_HOST_MEMORY; + if (PORT_GetError() == SEC_ERROR_INVALID_ARGS) { + return CKR_KEY_SIZE_RANGE; + } + return CKR_HOST_MEMORY; } - context->hashUpdate = (SFTKHash) HMAC_Update; - context->end = (SFTKEnd) HMAC_Finish; + context->hashUpdate = (SFTKHash)HMAC_Update; + context->end = (SFTKEnd)HMAC_Finish; - context->hashdestroy = (SFTKDestroy) HMAC_Destroy; + context->hashdestroy = (SFTKDestroy)HMAC_Destroy; intpointer = PORT_New(CK_ULONG); if (intpointer == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } *intpointer = mac_size; context->cipherInfo = intpointer; - context->destroy = (SFTKDestroy) sftk_Space; - context->update = (SFTKCipher) sftk_SignCopy; - context->verify = (SFTKVerify) sftk_HMACCmp; + context->destroy = (SFTKDestroy)sftk_Space; + context->update = (SFTKCipher)sftk_SignCopy; + context->verify = (SFTKVerify)sftk_HMACCmp; context->maxLen = hashObj->length; HMAC_Begin(HMACcontext); return CKR_OK; @@ -1812,7 +1950,7 @@ sftk_doHMACInit(SFTKSessionContext *context,HASH_HashType hash, * We probably should have one copy of this table. We still need this table * in ssl to 'sign' the handshake hashes. */ -static unsigned char ssl_pad_1 [60] = { +static unsigned char ssl_pad_1[60] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, @@ -1822,7 +1960,7 @@ static unsigned char ssl_pad_1 [60] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36 }; -static unsigned char ssl_pad_2 [60] = { +static unsigned char ssl_pad_2[60] = { 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, @@ -1834,44 +1972,43 @@ static unsigned char ssl_pad_2 [60] = { }; static SECStatus -sftk_SSLMACSign(SFTKSSLMACInfo *info,unsigned char *sig,unsigned int *sigLen, - unsigned int maxLen,unsigned char *hash, unsigned int hashLen) +sftk_SSLMACSign(SFTKSSLMACInfo *info, unsigned char *sig, unsigned int *sigLen, + unsigned int maxLen, unsigned char *hash, unsigned int hashLen) { unsigned char tmpBuf[SFTK_MAX_MAC_LENGTH]; unsigned int out; info->begin(info->hashContext); - info->update(info->hashContext,info->key,info->keySize); - info->update(info->hashContext,ssl_pad_2,info->padSize); - info->update(info->hashContext,hash,hashLen); - info->end(info->hashContext,tmpBuf,&out,SFTK_MAX_MAC_LENGTH); - PORT_Memcpy(sig,tmpBuf,info->macSize); + info->update(info->hashContext, info->key, info->keySize); + info->update(info->hashContext, ssl_pad_2, info->padSize); + info->update(info->hashContext, hash, hashLen); + info->end(info->hashContext, tmpBuf, &out, SFTK_MAX_MAC_LENGTH); + PORT_Memcpy(sig, tmpBuf, info->macSize); *sigLen = info->macSize; return SECSuccess; } static SECStatus -sftk_SSLMACVerify(SFTKSSLMACInfo *info,unsigned char *sig,unsigned int sigLen, - unsigned char *hash, unsigned int hashLen) +sftk_SSLMACVerify(SFTKSSLMACInfo *info, unsigned char *sig, unsigned int sigLen, + unsigned char *hash, unsigned int hashLen) { unsigned char tmpBuf[SFTK_MAX_MAC_LENGTH]; unsigned int out; info->begin(info->hashContext); - info->update(info->hashContext,info->key,info->keySize); - info->update(info->hashContext,ssl_pad_2,info->padSize); - info->update(info->hashContext,hash,hashLen); - info->end(info->hashContext,tmpBuf,&out,SFTK_MAX_MAC_LENGTH); - return (PORT_Memcmp(sig,tmpBuf,info->macSize) == 0) ? - SECSuccess : SECFailure; + info->update(info->hashContext, info->key, info->keySize); + info->update(info->hashContext, ssl_pad_2, info->padSize); + info->update(info->hashContext, hash, hashLen); + info->end(info->hashContext, tmpBuf, &out, SFTK_MAX_MAC_LENGTH); + return (PORT_Memcmp(sig, tmpBuf, info->macSize) == 0) ? SECSuccess : SECFailure; } /* * common HMAC initalization routine */ static CK_RV -sftk_doSSLMACInit(SFTKSessionContext *context,SECOidTag oid, - SFTKObject *key, CK_ULONG mac_size) +sftk_doSSLMACInit(SFTKSessionContext *context, SECOidTag oid, + SFTKObject *key, CK_ULONG mac_size) { SFTKAttribute *keyval; SFTKBegin begin; @@ -1880,43 +2017,46 @@ sftk_doSSLMACInit(SFTKSessionContext *context,SECOidTag oid, CK_RV crv = CKR_MECHANISM_INVALID; if (oid == SEC_OID_SHA1) { - crv = sftk_doSubSHA1(context); - if (crv != CKR_OK) return crv; - begin = (SFTKBegin) SHA1_Begin; - padSize = 40; + crv = sftk_doSubSHA1(context); + if (crv != CKR_OK) + return crv; + begin = (SFTKBegin)SHA1_Begin; + padSize = 40; } else { - crv = sftk_doSubMD5(context); - if (crv != CKR_OK) return crv; - begin = (SFTKBegin) MD5_Begin; - padSize = 48; + crv = sftk_doSubMD5(context); + if (crv != CKR_OK) + return crv; + begin = (SFTKBegin)MD5_Begin; + padSize = 48; } context->multi = PR_TRUE; - keyval = sftk_FindAttribute(key,CKA_VALUE); - if (keyval == NULL) return CKR_KEY_SIZE_RANGE; + keyval = sftk_FindAttribute(key, CKA_VALUE); + if (keyval == NULL) + return CKR_KEY_SIZE_RANGE; - context->hashUpdate(context->hashInfo,keyval->attrib.pValue, - keyval->attrib.ulValueLen); - context->hashUpdate(context->hashInfo,ssl_pad_1,padSize); - sslmacinfo = (SFTKSSLMACInfo *) PORT_Alloc(sizeof(SFTKSSLMACInfo)); + context->hashUpdate(context->hashInfo, keyval->attrib.pValue, + keyval->attrib.ulValueLen); + context->hashUpdate(context->hashInfo, ssl_pad_1, padSize); + sslmacinfo = (SFTKSSLMACInfo *)PORT_Alloc(sizeof(SFTKSSLMACInfo)); if (sslmacinfo == NULL) { sftk_FreeAttribute(keyval); - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } sslmacinfo->macSize = mac_size; sslmacinfo->hashContext = context->hashInfo; - PORT_Memcpy(sslmacinfo->key,keyval->attrib.pValue, - keyval->attrib.ulValueLen); + PORT_Memcpy(sslmacinfo->key, keyval->attrib.pValue, + keyval->attrib.ulValueLen); sslmacinfo->keySize = keyval->attrib.ulValueLen; sslmacinfo->begin = begin; sslmacinfo->end = context->end; sslmacinfo->update = context->hashUpdate; sslmacinfo->padSize = padSize; sftk_FreeAttribute(keyval); - context->cipherInfo = (void *) sslmacinfo; - context->destroy = (SFTKDestroy) sftk_Space; - context->update = (SFTKCipher) sftk_SSLMACSign; - context->verify = (SFTKVerify) sftk_SSLMACVerify; + context->cipherInfo = (void *)sslmacinfo; + context->destroy = (SFTKDestroy)sftk_Space; + context->update = (SFTKCipher)sftk_SSLMACSign; + context->verify = (SFTKVerify)sftk_SSLMACVerify; context->maxLen = mac_size; return CKR_OK; } @@ -1925,16 +2065,16 @@ sftk_doSSLMACInit(SFTKSessionContext *context,SECOidTag oid, ************** Crypto Functions: Sign ************************ */ -/** +/** * Check if We're using CBCMacing and initialize the session context if we are. * @param contextType SFTK_SIGN or SFTK_VERIFY * @param keyUsage check whether key allows this usage */ static CK_RV sftk_InitCBCMac(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey, CK_ATTRIBUTE_TYPE keyUsage, - SFTKContextType contextType) - + CK_OBJECT_HANDLE hKey, CK_ATTRIBUTE_TYPE keyUsage, + SFTKContextType contextType) + { CK_MECHANISM cbc_mechanism; CK_ULONG mac_bytes = SFTK_INVALID_MAC_SIZE; @@ -1949,105 +2089,109 @@ sftk_InitCBCMac(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, unsigned int blockSize; switch (pMechanism->mechanism) { - case CKM_RC2_MAC_GENERAL: - mac_bytes = - ((CK_RC2_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; - /* fall through */ - case CKM_RC2_MAC: - /* this works because ulEffectiveBits is in the same place in both the - * CK_RC2_MAC_GENERAL_PARAMS and CK_RC2_CBC_PARAMS */ - rc2_params.ulEffectiveBits = ((CK_RC2_MAC_GENERAL_PARAMS *) - pMechanism->pParameter)->ulEffectiveBits; - PORT_Memset(rc2_params.iv,0,sizeof(rc2_params.iv)); - cbc_mechanism.mechanism = CKM_RC2_CBC; - cbc_mechanism.pParameter = &rc2_params; - cbc_mechanism.ulParameterLen = sizeof(rc2_params); - blockSize = 8; - break; + case CKM_RC2_MAC_GENERAL: + if (!pMechanism->pParameter) { + return CKR_MECHANISM_PARAM_INVALID; + } + mac_bytes = + ((CK_RC2_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; + /* fall through */ + case CKM_RC2_MAC: + /* this works because ulEffectiveBits is in the same place in both the + * CK_RC2_MAC_GENERAL_PARAMS and CK_RC2_CBC_PARAMS */ + rc2_params.ulEffectiveBits = ((CK_RC2_MAC_GENERAL_PARAMS *) + pMechanism->pParameter) + ->ulEffectiveBits; + PORT_Memset(rc2_params.iv, 0, sizeof(rc2_params.iv)); + cbc_mechanism.mechanism = CKM_RC2_CBC; + cbc_mechanism.pParameter = &rc2_params; + cbc_mechanism.ulParameterLen = sizeof(rc2_params); + blockSize = 8; + break; #if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_MAC_GENERAL: - mac_bytes = - ((CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; - /* fall through */ - case CKM_RC5_MAC: - /* this works because ulEffectiveBits is in the same place in both the - * CK_RC5_MAC_GENERAL_PARAMS and CK_RC5_CBC_PARAMS */ - rc5_mac = (CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter; - rc5_params.ulWordsize = rc5_mac->ulWordsize; - rc5_params.ulRounds = rc5_mac->ulRounds; - rc5_params.pIv = ivBlock; - if( (blockSize = rc5_mac->ulWordsize*2) > SFTK_MAX_BLOCK_SIZE ) - return CKR_MECHANISM_PARAM_INVALID; - rc5_params.ulIvLen = blockSize; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_RC5_CBC; - cbc_mechanism.pParameter = &rc5_params; - cbc_mechanism.ulParameterLen = sizeof(rc5_params); - break; + case CKM_RC5_MAC_GENERAL: + mac_bytes = + ((CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter)->ulMacLength; + /* fall through */ + case CKM_RC5_MAC: + /* this works because ulEffectiveBits is in the same place in both the + * CK_RC5_MAC_GENERAL_PARAMS and CK_RC5_CBC_PARAMS */ + rc5_mac = (CK_RC5_MAC_GENERAL_PARAMS *)pMechanism->pParameter; + rc5_params.ulWordsize = rc5_mac->ulWordsize; + rc5_params.ulRounds = rc5_mac->ulRounds; + rc5_params.pIv = ivBlock; + if ((blockSize = rc5_mac->ulWordsize * 2) > SFTK_MAX_BLOCK_SIZE) + return CKR_MECHANISM_PARAM_INVALID; + rc5_params.ulIvLen = blockSize; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_RC5_CBC; + cbc_mechanism.pParameter = &rc5_params; + cbc_mechanism.ulParameterLen = sizeof(rc5_params); + break; #endif - /* add cast and idea later */ - case CKM_DES_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_DES_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_DES_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_DES3_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_DES3_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_DES3_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_CDMF_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_CDMF_MAC: - blockSize = 8; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_CDMF_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_SEED_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_SEED_MAC: - blockSize = 16; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_SEED_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_CAMELLIA_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_CAMELLIA_MAC: - blockSize = 16; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_CAMELLIA_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - case CKM_AES_MAC_GENERAL: - mac_bytes = *(CK_ULONG *)pMechanism->pParameter; - /* fall through */ - case CKM_AES_MAC: - blockSize = 16; - PORT_Memset(ivBlock,0,blockSize); - cbc_mechanism.mechanism = CKM_AES_CBC; - cbc_mechanism.pParameter = &ivBlock; - cbc_mechanism.ulParameterLen = blockSize; - break; - default: - return CKR_FUNCTION_NOT_SUPPORTED; + /* add cast and idea later */ + case CKM_DES_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_DES_MAC: + blockSize = 8; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_DES_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + case CKM_DES3_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_DES3_MAC: + blockSize = 8; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_DES3_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + case CKM_CDMF_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_CDMF_MAC: + blockSize = 8; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_CDMF_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + case CKM_SEED_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_SEED_MAC: + blockSize = 16; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_SEED_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + case CKM_CAMELLIA_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_CAMELLIA_MAC: + blockSize = 16; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_CAMELLIA_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + case CKM_AES_MAC_GENERAL: + mac_bytes = *(CK_ULONG *)pMechanism->pParameter; + /* fall through */ + case CKM_AES_MAC: + blockSize = 16; + PORT_Memset(ivBlock, 0, blockSize); + cbc_mechanism.mechanism = CKM_AES_CBC; + cbc_mechanism.pParameter = &ivBlock; + cbc_mechanism.ulParameterLen = blockSize; + break; + default: + return CKR_FUNCTION_NOT_SUPPORTED; } /* if MAC size is externally supplied, it should be checked. @@ -2055,26 +2199,28 @@ sftk_InitCBCMac(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, if (mac_bytes == SFTK_INVALID_MAC_SIZE) mac_bytes = blockSize >> 1; else { - if( mac_bytes > blockSize ) + if (mac_bytes > blockSize) return CKR_MECHANISM_PARAM_INVALID; } crv = sftk_CryptInit(hSession, &cbc_mechanism, hKey, - CKA_ENCRYPT, /* CBC mech is able to ENCRYPT, not SIGN/VERIFY */ - keyUsage, contextType, PR_TRUE ); - if (crv != CKR_OK) return crv; - crv = sftk_GetContext(hSession,&context,contextType,PR_TRUE,NULL); + CKA_ENCRYPT, /* CBC mech is able to ENCRYPT, not SIGN/VERIFY */ + keyUsage, contextType, PR_TRUE); + if (crv != CKR_OK) + return crv; + crv = sftk_GetContext(hSession, &context, contextType, PR_TRUE, NULL); /* this shouldn't happen! */ PORT_Assert(crv == CKR_OK); - if (crv != CKR_OK) return crv; + if (crv != CKR_OK) + return crv; context->blockSize = blockSize; context->macSize = mac_bytes; return CKR_OK; } /* - * encode RSA PKCS #1 Signature data before signing... + * encode RSA PKCS #1 Signature data before signing... */ static SECStatus sftk_RSAHashSign(SFTKHashSignInfo *info, unsigned char *sig, @@ -2094,12 +2240,12 @@ sftk_RSAHashSign(SFTKHashSignInfo *info, unsigned char *sig, /* XXX Old template; want to expunge it eventually. */ static DERTemplate SECAlgorithmIDTemplate[] = { { DER_SEQUENCE, - 0, NULL, sizeof(SECAlgorithmID) }, + 0, NULL, sizeof(SECAlgorithmID) }, { DER_OBJECT_ID, - offsetof(SECAlgorithmID,algorithm), }, + offsetof(SECAlgorithmID, algorithm) }, { DER_OPTIONAL | DER_ANY, - offsetof(SECAlgorithmID,parameters), }, - { 0, } + offsetof(SECAlgorithmID, parameters) }, + { 0 } }; /* @@ -2108,17 +2254,17 @@ static DERTemplate SECAlgorithmIDTemplate[] = { */ static DERTemplate SGNDigestInfoTemplate[] = { { DER_SEQUENCE, - 0, NULL, sizeof(SGNDigestInfo) }, + 0, NULL, sizeof(SGNDigestInfo) }, { DER_INLINE, - offsetof(SGNDigestInfo,digestAlgorithm), - SECAlgorithmIDTemplate, }, + offsetof(SGNDigestInfo, digestAlgorithm), + SECAlgorithmIDTemplate }, { DER_OCTET_STRING, - offsetof(SGNDigestInfo,digest), }, - { 0, } + offsetof(SGNDigestInfo, digest) }, + { 0 } }; /* - * encode RSA PKCS #1 Signature data before signing... + * encode RSA PKCS #1 Signature data before signing... */ SECStatus RSA_HashSign(SECOidTag hashOid, NSSLOWKEYPrivateKey *key, @@ -2159,7 +2305,7 @@ RSA_HashSign(SECOidTag hashOid, NSSLOWKEYPrivateKey *key, sftk_fatalError = PR_TRUE; } - loser: +loser: SGN_DestroyDigestInfo(di); if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); @@ -2207,7 +2353,6 @@ sftk_RSASignRaw(NSSLOWKEYPrivateKey *key, unsigned char *output, sftk_fatalError = PR_TRUE; } return rv; - } static SECStatus @@ -2239,7 +2384,7 @@ sftk_RSASignPSS(SFTKHashSignInfo *info, unsigned char *sig, static SECStatus nsc_DSA_Verify_Stub(void *ctx, void *sigBuf, unsigned int sigLen, - void *dataBuf, unsigned int dataLen) + void *dataBuf, unsigned int dataLen) { SECItem signature, digest; NSSLOWKEYPublicKey *key = (NSSLOWKEYPublicKey *)ctx; @@ -2266,7 +2411,7 @@ nsc_DSA_Sign_Stub(void *ctx, void *sigBuf, digest.len = dataLen; rv = DSA_SignDigest(&(key->u.dsa), &signature, &digest); if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; + sftk_fatalError = PR_TRUE; } *sigLen = signature.len; return rv; @@ -2302,7 +2447,7 @@ nsc_ECDSASignStub(void *ctx, void *sigBuf, digest.len = dataLen; rv = ECDSA_SignDigest(&(key->u.ec), &signature, &digest); if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; + sftk_fatalError = PR_TRUE; } *sigLen = signature.len; return rv; @@ -2311,28 +2456,29 @@ nsc_ECDSASignStub(void *ctx, void *sigBuf, /* NSC_SignInit setups up the signing operations. There are three basic * types of signing: - * (1) the tradition single part, where "Raw RSA" or "Raw DSA" is applied + * (1) the tradition single part, where "Raw RSA" or "Raw DSA" is applied * to data in a single Sign operation (which often looks a lot like an * encrypt, with data coming in and data going out). - * (2) Hash based signing, where we continually hash the data, then apply + * (2) Hash based signing, where we continually hash the data, then apply * some sort of signature to the end. - * (3) Block Encryption CBC MAC's, where the Data is encrypted with a key, + * (3) Block Encryption CBC MAC's, where the Data is encrypted with a key, * and only the final block is part of the mac. * * For case number 3, we initialize a context much like the Encryption Context - * (in fact we share code). We detect case 3 in C_SignUpdate, C_Sign, and + * (in fact we share code). We detect case 3 in C_SignUpdate, C_Sign, and * C_Final by the following method... if it's not multi-part, and it's doesn't * have a hash context, it must be a block Encryption CBC MAC. * - * For case number 2, we initialize a hash structure, as well as make it + * For case number 2, we initialize a hash structure, as well as make it * multi-part. Updates are simple calls to the hash update function. Final * calls the hashend, then passes the result to the 'update' function (which * operates as a final signature function). In some hash based MAC'ing (as - * opposed to hash base signatures), the update function is can be simply a + * opposed to hash base signatures), the update function is can be simply a * copy (as is the case with HMAC). */ -CK_RV NSC_SignInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) +CK_RV +NSC_SignInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { SFTKSession *session; SFTKObject *key; @@ -2346,293 +2492,300 @@ CK_RV NSC_SignInit(CK_SESSION_HANDLE hSession, /* Block Cipher MACing Algorithms use a different Context init method..*/ crv = sftk_InitCBCMac(hSession, pMechanism, hKey, CKA_SIGN, SFTK_SIGN); - if (crv != CKR_FUNCTION_NOT_SUPPORTED) return crv; + if (crv != CKR_FUNCTION_NOT_SUPPORTED) + return crv; /* we're not using a block cipher mac */ session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = sftk_InitGeneric(session,&context,SFTK_SIGN,&key,hKey,&key_type, - CKO_PRIVATE_KEY,CKA_SIGN); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + crv = sftk_InitGeneric(session, &context, SFTK_SIGN, &key, hKey, &key_type, + CKO_PRIVATE_KEY, CKA_SIGN); if (crv != CKR_OK) { - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } context->multi = PR_FALSE; -#define INIT_RSA_SIGN_MECH(mmm) \ - case CKM_ ## mmm ## _RSA_PKCS: \ - context->multi = PR_TRUE; \ - crv = sftk_doSub ## mmm (context); \ - if (crv != CKR_OK) break; \ - context->update = (SFTKCipher) sftk_RSAHashSign; \ - info = PORT_New(SFTKHashSignInfo); \ - if (info == NULL) { crv = CKR_HOST_MEMORY; break; } \ - info->hashOid = SEC_OID_ ## mmm ; \ - goto finish_rsa; - - switch(pMechanism->mechanism) { - INIT_RSA_SIGN_MECH(MD5) - INIT_RSA_SIGN_MECH(MD2) - INIT_RSA_SIGN_MECH(SHA1) - INIT_RSA_SIGN_MECH(SHA224) - INIT_RSA_SIGN_MECH(SHA256) - INIT_RSA_SIGN_MECH(SHA384) - INIT_RSA_SIGN_MECH(SHA512) - - case CKM_RSA_PKCS: - context->update = (SFTKCipher) sftk_RSASign; - goto finish_rsa; - case CKM_RSA_X_509: - context->update = (SFTKCipher) sftk_RSASignRaw; -finish_rsa: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->rsa = PR_TRUE; - privKey = sftk_GetPrivKey(key,CKK_RSA,&crv); - if (privKey == NULL) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - /* OK, info is allocated only if we're doing hash and sign mechanism. - * It's necessary to be able to set the correct OID in the final - * signature. - */ - if (info) { - info->key = privKey; - context->cipherInfo = info; - context->destroy = (SFTKDestroy)sftk_Space; - } else { - context->cipherInfo = privKey; - context->destroy = (SFTKDestroy)sftk_Null; - } - context->maxLen = nsslowkey_PrivateModulusLen(privKey); - break; - case CKM_RSA_PKCS_PSS: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->rsa = PR_TRUE; - if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || - !sftk_ValidatePssParams((const CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter)) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - info = PORT_New(SFTKHashSignInfo); - if (info == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - info->params = pMechanism->pParameter; - info->key = sftk_GetPrivKey(key,CKK_RSA,&crv); - if (info->key == NULL) { - PORT_Free(info); - break; - } - context->cipherInfo = info; - context->destroy = (SFTKDestroy) sftk_Space; - context->update = (SFTKCipher) sftk_RSASignPSS; - context->maxLen = nsslowkey_PrivateModulusLen(info->key); - break; - - case CKM_DSA_SHA1: - context->multi = PR_TRUE; - crv = sftk_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_DSA: - if (key_type != CKK_DSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - privKey = sftk_GetPrivKey(key,CKK_DSA,&crv); - if (privKey == NULL) { - break; - } - context->cipherInfo = privKey; - context->update = (SFTKCipher) nsc_DSA_Sign_Stub; - context->destroy = (privKey == key->objectInfo) ? - (SFTKDestroy) sftk_Null:(SFTKDestroy)sftk_FreePrivKey; - context->maxLen = DSA_MAX_SIGNATURE_LEN; - - break; +#define INIT_RSA_SIGN_MECH(mmm) \ + case CKM_##mmm##_RSA_PKCS: \ + context->multi = PR_TRUE; \ + crv = sftk_doSub##mmm(context); \ + if (crv != CKR_OK) \ + break; \ + context->update = (SFTKCipher)sftk_RSAHashSign; \ + info = PORT_New(SFTKHashSignInfo); \ + if (info == NULL) { \ + crv = CKR_HOST_MEMORY; \ + break; \ + } \ + info->hashOid = SEC_OID_##mmm; \ + goto finish_rsa; + + switch (pMechanism->mechanism) { + INIT_RSA_SIGN_MECH(MD5) + INIT_RSA_SIGN_MECH(MD2) + INIT_RSA_SIGN_MECH(SHA1) + INIT_RSA_SIGN_MECH(SHA224) + INIT_RSA_SIGN_MECH(SHA256) + INIT_RSA_SIGN_MECH(SHA384) + INIT_RSA_SIGN_MECH(SHA512) + + case CKM_RSA_PKCS: + context->update = (SFTKCipher)sftk_RSASign; + goto finish_rsa; + case CKM_RSA_X_509: + context->update = (SFTKCipher)sftk_RSASignRaw; + finish_rsa: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->rsa = PR_TRUE; + privKey = sftk_GetPrivKey(key, CKK_RSA, &crv); + if (privKey == NULL) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + /* OK, info is allocated only if we're doing hash and sign mechanism. + * It's necessary to be able to set the correct OID in the final + * signature. + */ + if (info) { + info->key = privKey; + context->cipherInfo = info; + context->destroy = (SFTKDestroy)sftk_Space; + } else { + context->cipherInfo = privKey; + context->destroy = (SFTKDestroy)sftk_Null; + } + context->maxLen = nsslowkey_PrivateModulusLen(privKey); + break; + case CKM_RSA_PKCS_PSS: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->rsa = PR_TRUE; + if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || + !sftk_ValidatePssParams((const CK_RSA_PKCS_PSS_PARAMS *)pMechanism->pParameter)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + info = PORT_New(SFTKHashSignInfo); + if (info == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + info->params = pMechanism->pParameter; + info->key = sftk_GetPrivKey(key, CKK_RSA, &crv); + if (info->key == NULL) { + PORT_Free(info); + break; + } + context->cipherInfo = info; + context->destroy = (SFTKDestroy)sftk_Space; + context->update = (SFTKCipher)sftk_RSASignPSS; + context->maxLen = nsslowkey_PrivateModulusLen(info->key); + break; + + case CKM_DSA_SHA1: + context->multi = PR_TRUE; + crv = sftk_doSubSHA1(context); + if (crv != CKR_OK) + break; + /* fall through */ + case CKM_DSA: + if (key_type != CKK_DSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + privKey = sftk_GetPrivKey(key, CKK_DSA, &crv); + if (privKey == NULL) { + break; + } + context->cipherInfo = privKey; + context->update = (SFTKCipher)nsc_DSA_Sign_Stub; + context->destroy = (privKey == key->objectInfo) ? (SFTKDestroy)sftk_Null : (SFTKDestroy)sftk_FreePrivKey; + context->maxLen = DSA_MAX_SIGNATURE_LEN; + + break; #ifndef NSS_DISABLE_ECC - case CKM_ECDSA_SHA1: - context->multi = PR_TRUE; - crv = sftk_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_ECDSA: - if (key_type != CKK_EC) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - privKey = sftk_GetPrivKey(key,CKK_EC,&crv); - if (privKey == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->cipherInfo = privKey; - context->update = (SFTKCipher) nsc_ECDSASignStub; - context->destroy = (privKey == key->objectInfo) ? - (SFTKDestroy) sftk_Null:(SFTKDestroy)sftk_FreePrivKey; - context->maxLen = MAX_ECKEY_LEN * 2; - - break; + case CKM_ECDSA_SHA1: + context->multi = PR_TRUE; + crv = sftk_doSubSHA1(context); + if (crv != CKR_OK) + break; + /* fall through */ + case CKM_ECDSA: + if (key_type != CKK_EC) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + privKey = sftk_GetPrivKey(key, CKK_EC, &crv); + if (privKey == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->cipherInfo = privKey; + context->update = (SFTKCipher)nsc_ECDSASignStub; + context->destroy = (privKey == key->objectInfo) ? (SFTKDestroy)sftk_Null : (SFTKDestroy)sftk_FreePrivKey; + context->maxLen = MAX_ECKEY_LEN * 2; + + break; #endif /* NSS_DISABLE_ECC */ -#define INIT_HMAC_MECH(mmm) \ - case CKM_ ## mmm ## _HMAC_GENERAL: \ - crv = sftk_doHMACInit(context, HASH_Alg ## mmm ,key, \ - *(CK_ULONG *)pMechanism->pParameter); \ - break; \ - case CKM_ ## mmm ## _HMAC: \ - crv = sftk_doHMACInit(context, HASH_Alg ## mmm ,key, mmm ## _LENGTH); \ - break; - - INIT_HMAC_MECH(MD2) - INIT_HMAC_MECH(MD5) - INIT_HMAC_MECH(SHA224) - INIT_HMAC_MECH(SHA256) - INIT_HMAC_MECH(SHA384) - INIT_HMAC_MECH(SHA512) - - case CKM_SHA_1_HMAC_GENERAL: - crv = sftk_doHMACInit(context,HASH_AlgSHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SHA_1_HMAC: - crv = sftk_doHMACInit(context,HASH_AlgSHA1,key,SHA1_LENGTH); - break; - - case CKM_SSL3_MD5_MAC: - crv = sftk_doSSLMACInit(context,SEC_OID_MD5,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SSL3_SHA1_MAC: - crv = sftk_doSSLMACInit(context,SEC_OID_SHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_TLS_PRF_GENERAL: - crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgNULL, 0); - break; - case CKM_TLS_MAC: { - CK_TLS_MAC_PARAMS *tls12_mac_params; - HASH_HashType tlsPrfHash; - const char *label; - - if (pMechanism->ulParameterLen != sizeof(CK_TLS_MAC_PARAMS)) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - tls12_mac_params = (CK_TLS_MAC_PARAMS *)pMechanism->pParameter; - if (tls12_mac_params->prfMechanism == CKM_TLS_PRF) { - /* The TLS 1.0 and 1.1 PRF */ - tlsPrfHash = HASH_AlgNULL; - if (tls12_mac_params->ulMacLength != 12) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - } else { - /* The hash function for the TLS 1.2 PRF */ - tlsPrfHash = - GetHashTypeFromMechanism(tls12_mac_params->prfMechanism); - if (tlsPrfHash == HASH_AlgNULL || - tls12_mac_params->ulMacLength < 12) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - } - if (tls12_mac_params->ulServerOrClient == 1) { - label = "server finished"; - } else if (tls12_mac_params->ulServerOrClient == 2) { - label = "client finished"; - } else { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - crv = sftk_TLSPRFInit(context, key, key_type, tlsPrfHash, - tls12_mac_params->ulMacLength); - if (crv == CKR_OK) { - context->hashUpdate(context->hashInfo, label, 15); - } - break; - } - case CKM_NSS_TLS_PRF_GENERAL_SHA256: - crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgSHA256, 0); - break; - - case CKM_NSS_HMAC_CONSTANT_TIME: { - sftk_MACConstantTimeCtx *ctx = - sftk_HMACConstantTime_New(pMechanism,key); - CK_ULONG *intpointer; - - if (ctx == NULL) { - crv = CKR_ARGUMENTS_BAD; - break; - } - intpointer = PORT_New(CK_ULONG); - if (intpointer == NULL) { - PORT_Free(ctx); - crv = CKR_HOST_MEMORY; - break; - } - *intpointer = ctx->hash->length; - - context->cipherInfo = intpointer; - context->hashInfo = ctx; - context->currentMech = pMechanism->mechanism; - context->hashUpdate = sftk_HMACConstantTime_Update; - context->hashdestroy = sftk_MACConstantTime_DestroyContext; - context->end = sftk_MACConstantTime_EndHash; - context->update = (SFTKCipher) sftk_SignCopy; - context->destroy = sftk_Space; - context->maxLen = 64; - context->multi = PR_TRUE; - break; - } - - case CKM_NSS_SSL3_MAC_CONSTANT_TIME: { - sftk_MACConstantTimeCtx *ctx = - sftk_SSLv3MACConstantTime_New(pMechanism,key); - CK_ULONG *intpointer; - - if (ctx == NULL) { - crv = CKR_ARGUMENTS_BAD; - break; - } - intpointer = PORT_New(CK_ULONG); - if (intpointer == NULL) { - PORT_Free(ctx); - crv = CKR_HOST_MEMORY; - break; - } - *intpointer = ctx->hash->length; - - context->cipherInfo = intpointer; - context->hashInfo = ctx; - context->currentMech = pMechanism->mechanism; - context->hashUpdate = sftk_SSLv3MACConstantTime_Update; - context->hashdestroy = sftk_MACConstantTime_DestroyContext; - context->end = sftk_MACConstantTime_EndHash; - context->update = (SFTKCipher) sftk_SignCopy; - context->destroy = sftk_Space; - context->maxLen = 64; - context->multi = PR_TRUE; - break; - } - - default: - crv = CKR_MECHANISM_INVALID; - break; +#define INIT_HMAC_MECH(mmm) \ + case CKM_##mmm##_HMAC_GENERAL: \ + crv = sftk_doHMACInit(context, HASH_Alg##mmm, key, \ + *(CK_ULONG *)pMechanism->pParameter); \ + break; \ + case CKM_##mmm##_HMAC: \ + crv = sftk_doHMACInit(context, HASH_Alg##mmm, key, mmm##_LENGTH); \ + break; + + INIT_HMAC_MECH(MD2) + INIT_HMAC_MECH(MD5) + INIT_HMAC_MECH(SHA224) + INIT_HMAC_MECH(SHA256) + INIT_HMAC_MECH(SHA384) + INIT_HMAC_MECH(SHA512) + + case CKM_SHA_1_HMAC_GENERAL: + crv = sftk_doHMACInit(context, HASH_AlgSHA1, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_SHA_1_HMAC: + crv = sftk_doHMACInit(context, HASH_AlgSHA1, key, SHA1_LENGTH); + break; + + case CKM_SSL3_MD5_MAC: + crv = sftk_doSSLMACInit(context, SEC_OID_MD5, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_SSL3_SHA1_MAC: + crv = sftk_doSSLMACInit(context, SEC_OID_SHA1, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_TLS_PRF_GENERAL: + crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgNULL, 0); + break; + case CKM_TLS_MAC: { + CK_TLS_MAC_PARAMS *tls12_mac_params; + HASH_HashType tlsPrfHash; + const char *label; + + if (pMechanism->ulParameterLen != sizeof(CK_TLS_MAC_PARAMS)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + tls12_mac_params = (CK_TLS_MAC_PARAMS *)pMechanism->pParameter; + if (tls12_mac_params->prfMechanism == CKM_TLS_PRF) { + /* The TLS 1.0 and 1.1 PRF */ + tlsPrfHash = HASH_AlgNULL; + if (tls12_mac_params->ulMacLength != 12) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + } else { + /* The hash function for the TLS 1.2 PRF */ + tlsPrfHash = + GetHashTypeFromMechanism(tls12_mac_params->prfMechanism); + if (tlsPrfHash == HASH_AlgNULL || + tls12_mac_params->ulMacLength < 12) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + } + if (tls12_mac_params->ulServerOrClient == 1) { + label = "server finished"; + } else if (tls12_mac_params->ulServerOrClient == 2) { + label = "client finished"; + } else { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + crv = sftk_TLSPRFInit(context, key, key_type, tlsPrfHash, + tls12_mac_params->ulMacLength); + if (crv == CKR_OK) { + context->hashUpdate(context->hashInfo, label, 15); + } + break; + } + case CKM_NSS_TLS_PRF_GENERAL_SHA256: + crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgSHA256, 0); + break; + + case CKM_NSS_HMAC_CONSTANT_TIME: { + sftk_MACConstantTimeCtx *ctx = + sftk_HMACConstantTime_New(pMechanism, key); + CK_ULONG *intpointer; + + if (ctx == NULL) { + crv = CKR_ARGUMENTS_BAD; + break; + } + intpointer = PORT_New(CK_ULONG); + if (intpointer == NULL) { + PORT_Free(ctx); + crv = CKR_HOST_MEMORY; + break; + } + *intpointer = ctx->hash->length; + + context->cipherInfo = intpointer; + context->hashInfo = ctx; + context->currentMech = pMechanism->mechanism; + context->hashUpdate = sftk_HMACConstantTime_Update; + context->hashdestroy = sftk_MACConstantTime_DestroyContext; + context->end = sftk_MACConstantTime_EndHash; + context->update = (SFTKCipher)sftk_SignCopy; + context->destroy = sftk_Space; + context->maxLen = 64; + context->multi = PR_TRUE; + break; + } + + case CKM_NSS_SSL3_MAC_CONSTANT_TIME: { + sftk_MACConstantTimeCtx *ctx = + sftk_SSLv3MACConstantTime_New(pMechanism, key); + CK_ULONG *intpointer; + + if (ctx == NULL) { + crv = CKR_ARGUMENTS_BAD; + break; + } + intpointer = PORT_New(CK_ULONG); + if (intpointer == NULL) { + PORT_Free(ctx); + crv = CKR_HOST_MEMORY; + break; + } + *intpointer = ctx->hash->length; + + context->cipherInfo = intpointer; + context->hashInfo = ctx; + context->currentMech = pMechanism->mechanism; + context->hashUpdate = sftk_SSLv3MACConstantTime_Update; + context->hashdestroy = sftk_MACConstantTime_DestroyContext; + context->end = sftk_MACConstantTime_EndHash; + context->update = (SFTKCipher)sftk_SignCopy; + context->destroy = sftk_Space; + context->maxLen = 64; + context->multi = PR_TRUE; + break; + } + + default: + crv = CKR_MECHANISM_INVALID; + break; } if (crv != CKR_OK) { - if (info) PORT_Free(info); + if (info) + PORT_Free(info); sftk_FreeContext(context); sftk_FreeSession(session); return crv; @@ -2645,12 +2798,13 @@ finish_rsa: /** MAC one block of data by block cipher */ static CK_RV -sftk_MACBlock( SFTKSessionContext *ctx, void *blk ) +sftk_MACBlock(SFTKSessionContext *ctx, void *blk) { unsigned int outlen; - return ( SECSuccess == (ctx->update)( ctx->cipherInfo, ctx->macBuf, &outlen, - SFTK_MAX_BLOCK_SIZE, blk, ctx->blockSize )) - ? CKR_OK : sftk_MapCryptError(PORT_GetError()); + return (SECSuccess == (ctx->update)(ctx->cipherInfo, ctx->macBuf, &outlen, + SFTK_MAX_BLOCK_SIZE, blk, ctx->blockSize)) + ? CKR_OK + : sftk_MapCryptError(PORT_GetError()); } /** MAC last (incomplete) block of data by block cipher @@ -2658,100 +2812,101 @@ sftk_MACBlock( SFTKSessionContext *ctx, void *blk ) * Call once, then terminate MACing operation. */ static CK_RV -sftk_MACFinal( SFTKSessionContext *ctx ) +sftk_MACFinal(SFTKSessionContext *ctx) { unsigned int padLen = ctx->padDataLength; /* pad and proceed the residual */ - if( padLen ) { + if (padLen) { /* shd clr ctx->padLen to make sftk_MACFinal idempotent */ - PORT_Memset( ctx->padBuf + padLen, 0, ctx->blockSize - padLen ); - return sftk_MACBlock( ctx, ctx->padBuf ); + PORT_Memset(ctx->padBuf + padLen, 0, ctx->blockSize - padLen); + return sftk_MACBlock(ctx, ctx->padBuf); } else return CKR_OK; } /** The common implementation for {Sign,Verify}Update. (S/V only vary in their * setup and final operations). - * + * * A call which results in an error terminates the operation [PKCS#11,v2.11] */ static CK_RV -sftk_MACUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen,SFTKContextType type) +sftk_MACUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, SFTKContextType type) { SFTKSession *session; SFTKSessionContext *context; CK_RV crv; /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,type, PR_TRUE, &session ); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, type, PR_TRUE, &session); + if (crv != CKR_OK) + return crv; if (context->hashInfo) { - (*context->hashUpdate)(context->hashInfo, pPart, ulPartLen); - } else { - /* must be block cipher MACing */ + (*context->hashUpdate)(context->hashInfo, pPart, ulPartLen); + } else { + /* must be block cipher MACing */ - unsigned int blkSize = context->blockSize; + unsigned int blkSize = context->blockSize; unsigned char *residual = /* free room in context->padBuf */ - context->padBuf + context->padDataLength; - unsigned int minInput = /* min input for MACing at least one block */ - blkSize - context->padDataLength; + context->padBuf + context->padDataLength; + unsigned int minInput = /* min input for MACing at least one block */ + blkSize - context->padDataLength; /* not enough data even for one block */ - if( ulPartLen < minInput ) { - PORT_Memcpy( residual, pPart, ulPartLen ); + if (ulPartLen < minInput) { + PORT_Memcpy(residual, pPart, ulPartLen); context->padDataLength += ulPartLen; goto cleanup; } /* MACing residual */ - if( context->padDataLength ) { - PORT_Memcpy( residual, pPart, minInput ); + if (context->padDataLength) { + PORT_Memcpy(residual, pPart, minInput); ulPartLen -= minInput; - pPart += minInput; - if( CKR_OK != (crv = sftk_MACBlock( context, context->padBuf )) ) + pPart += minInput; + if (CKR_OK != (crv = sftk_MACBlock(context, context->padBuf))) goto terminate; } /* MACing full blocks */ - while( ulPartLen >= blkSize ) - { - if( CKR_OK != (crv = sftk_MACBlock( context, pPart )) ) + while (ulPartLen >= blkSize) { + if (CKR_OK != (crv = sftk_MACBlock(context, pPart))) goto terminate; ulPartLen -= blkSize; - pPart += blkSize; + pPart += blkSize; } /* save the residual */ - if( (context->padDataLength = ulPartLen) ) - PORT_Memcpy( context->padBuf, pPart, ulPartLen ); + if ((context->padDataLength = ulPartLen)) + PORT_Memcpy(context->padBuf, pPart, ulPartLen); } /* blk cipher MACing */ - goto cleanup; + goto cleanup; terminate: - sftk_TerminateOp( session, type, context ); + sftk_TerminateOp(session, type, context); cleanup: sftk_FreeSession(session); return crv; } /* NSC_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature + * where the signature is (will be) an appendix to the data, + * and plaintext cannot be recovered from the signature * * A call which results in an error terminates the operation [PKCS#11,v2.11] */ -CK_RV NSC_SignUpdate(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) +CK_RV +NSC_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen) { CHECK_FORK(); return sftk_MACUpdate(hSession, pPart, ulPartLen, SFTK_SIGN); } - -/* NSC_SignFinal finishes a multiple-part signature operation, +/* NSC_SignFinal finishes a multiple-part signature operation, * returning the signature. */ -CK_RV NSC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen) +CK_RV +NSC_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen) { SFTKSession *session; SFTKSessionContext *context; @@ -2762,19 +2917,21 @@ CK_RV NSC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_SIGN,PR_TRUE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_SIGN, PR_TRUE, &session); + if (crv != CKR_OK) + return crv; if (context->hashInfo) { unsigned int digestLen; unsigned char tmpbuf[SFTK_MAX_MAC_LENGTH]; - if( !pSignature ) { - outlen = context->maxLen; goto finish; + if (!pSignature) { + outlen = context->maxLen; + goto finish; } (*context->end)(context->hashInfo, tmpbuf, &digestLen, sizeof(tmpbuf)); - if( SECSuccess != (context->update)(context->cipherInfo, pSignature, - &outlen, maxoutlen, tmpbuf, digestLen)) + if (SECSuccess != (context->update)(context->cipherInfo, pSignature, + &outlen, maxoutlen, tmpbuf, digestLen)) crv = sftk_MapCryptError(PORT_GetError()); /* CKR_BUFFER_TOO_SMALL here isn't continuable, let operation terminate. * Keeping "too small" CK_RV intact is a standard violation, but allows @@ -2783,15 +2940,16 @@ CK_RV NSC_SignFinal(CK_SESSION_HANDLE hSession,CK_BYTE_PTR pSignature, /* must be block cipher MACing */ outlen = context->macSize; /* null or "too small" buf doesn't terminate operation [PKCS#11,v2.11]*/ - if( !pSignature || maxoutlen < outlen ) { - if( pSignature ) crv = CKR_BUFFER_TOO_SMALL; + if (!pSignature || maxoutlen < outlen) { + if (pSignature) + crv = CKR_BUFFER_TOO_SMALL; goto finish; } - if( CKR_OK == (crv = sftk_MACFinal( context )) ) - PORT_Memcpy(pSignature, context->macBuf, outlen ); + if (CKR_OK == (crv = sftk_MACFinal(context))) + PORT_Memcpy(pSignature, context->macBuf, outlen); } - sftk_TerminateOp( session, SFTK_SIGN, context ); + sftk_TerminateOp(session, SFTK_SIGN, context); finish: *pulSignatureLen = outlen; sftk_FreeSession(session); @@ -2799,11 +2957,12 @@ finish: } /* NSC_Sign signs (encrypts with private key) data in a single part, - * where the signature is (will be) an appendix to the data, + * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature */ -CK_RV NSC_Sign(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pData,CK_ULONG ulDataLen,CK_BYTE_PTR pSignature, - CK_ULONG_PTR pulSignatureLen) +CK_RV +NSC_Sign(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, + CK_ULONG_PTR pulSignatureLen) { SFTKSession *session; SFTKSessionContext *context; @@ -2812,33 +2971,34 @@ CK_RV NSC_Sign(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_SIGN,PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_SIGN, PR_FALSE, &session); + if (crv != CKR_OK) + return crv; if (!pSignature) { /* see also how C_SignUpdate implements this */ - *pulSignatureLen = (!context->multi || context->hashInfo) - ? context->maxLen - : context->macSize; /* must be block cipher MACing */ - goto finish; + *pulSignatureLen = (!context->multi || context->hashInfo) + ? context->maxLen + : context->macSize; /* must be block cipher MACing */ + goto finish; } /* multi part Signing are completely implemented by SignUpdate and * sign Final */ if (context->multi) { /* SignFinal can't follow failed SignUpdate */ - if( CKR_OK == (crv = NSC_SignUpdate(hSession,pData,ulDataLen) )) + if (CKR_OK == (crv = NSC_SignUpdate(hSession, pData, ulDataLen))) crv = NSC_SignFinal(hSession, pSignature, pulSignatureLen); - } else { - /* single-part PKC signature (e.g. CKM_ECDSA) */ + } else { + /* single-part PKC signature (e.g. CKM_ECDSA) */ unsigned int outlen; unsigned int maxoutlen = *pulSignatureLen; - if( SECSuccess != (*context->update)(context->cipherInfo, pSignature, - &outlen, maxoutlen, pData, ulDataLen)) + if (SECSuccess != (*context->update)(context->cipherInfo, pSignature, + &outlen, maxoutlen, pData, ulDataLen)) crv = sftk_MapCryptError(PORT_GetError()); - *pulSignatureLen = (CK_ULONG) outlen; + *pulSignatureLen = (CK_ULONG)outlen; /* "too small" here is certainly continuable */ - if( crv != CKR_BUFFER_TOO_SMALL ) + if (crv != CKR_BUFFER_TOO_SMALL) sftk_TerminateOp(session, SFTK_SIGN, context); } /* single-part */ @@ -2847,38 +3007,38 @@ finish: return crv; } - /* ************** Crypto Functions: Sign Recover ************************ */ /* NSC_SignRecoverInit initializes a signature operation, - * where the (digest) data can be recovered from the signature. + * where the (digest) data can be recovered from the signature. * E.g. encryption with the user's private key */ -CK_RV NSC_SignRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) +CK_RV +NSC_SignRecoverInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { CHECK_FORK(); switch (pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - return NSC_SignInit(hSession,pMechanism,hKey); - default: - break; + case CKM_RSA_PKCS: + case CKM_RSA_X_509: + return NSC_SignInit(hSession, pMechanism, hKey); + default: + break; } return CKR_MECHANISM_INVALID; } - /* NSC_SignRecover signs data in a single operation - * where the (digest) data can be recovered from the signature. + * where the (digest) data can be recovered from the signature. * E.g. encryption with the user's private key */ -CK_RV NSC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) +CK_RV +NSC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { CHECK_FORK(); - return NSC_Sign(hSession,pData,ulDataLen,pSignature,pulSignatureLen); + return NSC_Sign(hSession, pData, ulDataLen, pSignature, pulSignatureLen); } /* @@ -2887,7 +3047,7 @@ CK_RV NSC_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, /* Handle RSA Signature formatting */ static SECStatus -sftk_hashCheckSign(SFTKHashVerifyInfo *info, const unsigned char *sig, +sftk_hashCheckSign(SFTKHashVerifyInfo *info, const unsigned char *sig, unsigned int sigLen, const unsigned char *digest, unsigned int digestLen) { @@ -2922,19 +3082,19 @@ RSA_HashCheckSign(SECOidTag digestOid, NSSLOWKEYPublicKey *key, pkcs1DigestInfo.data = pkcs1DigestInfoData; pkcs1DigestInfo.len = bufferSize; - + /* decrypt the block */ rv = RSA_CheckSignRecover(&key->u.rsa, pkcs1DigestInfo.data, - &pkcs1DigestInfo.len, pkcs1DigestInfo.len, - sig, sigLen); + &pkcs1DigestInfo.len, pkcs1DigestInfo.len, + sig, sigLen); if (rv != SECSuccess) { PORT_SetError(SEC_ERROR_BAD_SIGNATURE); } else { - digest.data = (PRUint8*) digestData; + digest.data = (PRUint8 *)digestData; digest.len = digestLen; rv = _SGN_VerifyPKCS1DigestInfo( - digestOid, &digest, &pkcs1DigestInfo, - PR_TRUE /*XXX: unsafeAllowMissingParameters*/); + digestOid, &digest, &pkcs1DigestInfo, + PR_TRUE /*XXX: unsafeAllowMissingParameters*/); } PORT_Free(pkcs1DigestInfoData); @@ -2991,11 +3151,12 @@ sftk_RSACheckSignPSS(SFTKHashVerifyInfo *info, const unsigned char *sig, params->sLen, sig, sigLen, digest, digestLen); } -/* NSC_VerifyInit initializes a verification operation, - * where the signature is an appendix to the data, +/* NSC_VerifyInit initializes a verification operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature (e.g. DSA) */ -CK_RV NSC_VerifyInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) +CK_RV +NSC_VerifyInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { SFTKSession *session; SFTKObject *key; @@ -3009,183 +3170,195 @@ CK_RV NSC_VerifyInit(CK_SESSION_HANDLE hSession, /* Block Cipher MACing Algorithms use a different Context init method..*/ crv = sftk_InitCBCMac(hSession, pMechanism, hKey, CKA_VERIFY, SFTK_VERIFY); - if (crv != CKR_FUNCTION_NOT_SUPPORTED) return crv; + if (crv != CKR_FUNCTION_NOT_SUPPORTED) + return crv; session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = sftk_InitGeneric(session,&context,SFTK_VERIFY,&key,hKey,&key_type, - CKO_PUBLIC_KEY,CKA_VERIFY); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + crv = sftk_InitGeneric(session, &context, SFTK_VERIFY, &key, hKey, &key_type, + CKO_PUBLIC_KEY, CKA_VERIFY); if (crv != CKR_OK) { - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } context->multi = PR_FALSE; -#define INIT_RSA_VFY_MECH(mmm) \ - case CKM_ ## mmm ## _RSA_PKCS: \ - context->multi = PR_TRUE; \ - crv = sftk_doSub ## mmm (context); \ - if (crv != CKR_OK) break; \ - context->verify = (SFTKVerify) sftk_hashCheckSign; \ - info = PORT_New(SFTKHashVerifyInfo); \ - if (info == NULL) { crv = CKR_HOST_MEMORY; break; } \ - info->hashOid = SEC_OID_ ## mmm ; \ - goto finish_rsa; - - switch(pMechanism->mechanism) { - INIT_RSA_VFY_MECH(MD5) - INIT_RSA_VFY_MECH(MD2) - INIT_RSA_VFY_MECH(SHA1) - INIT_RSA_VFY_MECH(SHA224) - INIT_RSA_VFY_MECH(SHA256) - INIT_RSA_VFY_MECH(SHA384) - INIT_RSA_VFY_MECH(SHA512) - - case CKM_RSA_PKCS: - context->verify = (SFTKVerify) sftk_RSACheckSign; - goto finish_rsa; - case CKM_RSA_X_509: - context->verify = (SFTKVerify) sftk_RSACheckSignRaw; -finish_rsa: - if (key_type != CKK_RSA) { - if (info) PORT_Free(info); - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->rsa = PR_TRUE; - pubKey = sftk_GetPubKey(key,CKK_RSA,&crv); - if (pubKey == NULL) { - if (info) PORT_Free(info); - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - if (info) { - info->key = pubKey; - context->cipherInfo = info; - context->destroy = sftk_Space; - } else { - context->cipherInfo = pubKey; - context->destroy = sftk_Null; - } - break; - case CKM_RSA_PKCS_PSS: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->rsa = PR_TRUE; - if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || - !sftk_ValidatePssParams((const CK_RSA_PKCS_PSS_PARAMS*)pMechanism->pParameter)) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - info = PORT_New(SFTKHashVerifyInfo); - if (info == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - info->params = pMechanism->pParameter; - info->key = sftk_GetPubKey(key,CKK_RSA,&crv); - if (info->key == NULL) { - PORT_Free(info); - break; - } - context->cipherInfo = info; - context->destroy = (SFTKDestroy) sftk_Space; - context->verify = (SFTKVerify) sftk_RSACheckSignPSS; - break; - case CKM_DSA_SHA1: - context->multi = PR_TRUE; - crv = sftk_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_DSA: - if (key_type != CKK_DSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - pubKey = sftk_GetPubKey(key,CKK_DSA,&crv); - if (pubKey == NULL) { - break; - } - context->cipherInfo = pubKey; - context->verify = (SFTKVerify) nsc_DSA_Verify_Stub; - context->destroy = sftk_Null; - break; +#define INIT_RSA_VFY_MECH(mmm) \ + case CKM_##mmm##_RSA_PKCS: \ + context->multi = PR_TRUE; \ + crv = sftk_doSub##mmm(context); \ + if (crv != CKR_OK) \ + break; \ + context->verify = (SFTKVerify)sftk_hashCheckSign; \ + info = PORT_New(SFTKHashVerifyInfo); \ + if (info == NULL) { \ + crv = CKR_HOST_MEMORY; \ + break; \ + } \ + info->hashOid = SEC_OID_##mmm; \ + goto finish_rsa; + + switch (pMechanism->mechanism) { + INIT_RSA_VFY_MECH(MD5) + INIT_RSA_VFY_MECH(MD2) + INIT_RSA_VFY_MECH(SHA1) + INIT_RSA_VFY_MECH(SHA224) + INIT_RSA_VFY_MECH(SHA256) + INIT_RSA_VFY_MECH(SHA384) + INIT_RSA_VFY_MECH(SHA512) + + case CKM_RSA_PKCS: + context->verify = (SFTKVerify)sftk_RSACheckSign; + goto finish_rsa; + case CKM_RSA_X_509: + context->verify = (SFTKVerify)sftk_RSACheckSignRaw; + finish_rsa: + if (key_type != CKK_RSA) { + if (info) + PORT_Free(info); + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->rsa = PR_TRUE; + pubKey = sftk_GetPubKey(key, CKK_RSA, &crv); + if (pubKey == NULL) { + if (info) + PORT_Free(info); + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + if (info) { + info->key = pubKey; + context->cipherInfo = info; + context->destroy = sftk_Space; + } else { + context->cipherInfo = pubKey; + context->destroy = sftk_Null; + } + break; + case CKM_RSA_PKCS_PSS: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->rsa = PR_TRUE; + if (pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || + !sftk_ValidatePssParams((const CK_RSA_PKCS_PSS_PARAMS *)pMechanism->pParameter)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + info = PORT_New(SFTKHashVerifyInfo); + if (info == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + info->params = pMechanism->pParameter; + info->key = sftk_GetPubKey(key, CKK_RSA, &crv); + if (info->key == NULL) { + PORT_Free(info); + break; + } + context->cipherInfo = info; + context->destroy = (SFTKDestroy)sftk_Space; + context->verify = (SFTKVerify)sftk_RSACheckSignPSS; + break; + case CKM_DSA_SHA1: + context->multi = PR_TRUE; + crv = sftk_doSubSHA1(context); + if (crv != CKR_OK) + break; + /* fall through */ + case CKM_DSA: + if (key_type != CKK_DSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + pubKey = sftk_GetPubKey(key, CKK_DSA, &crv); + if (pubKey == NULL) { + break; + } + context->cipherInfo = pubKey; + context->verify = (SFTKVerify)nsc_DSA_Verify_Stub; + context->destroy = sftk_Null; + break; #ifndef NSS_DISABLE_ECC - case CKM_ECDSA_SHA1: - context->multi = PR_TRUE; - crv = sftk_doSubSHA1(context); - if (crv != CKR_OK) break; - /* fall through */ - case CKM_ECDSA: - if (key_type != CKK_EC) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - pubKey = sftk_GetPubKey(key,CKK_EC,&crv); - if (pubKey == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - context->cipherInfo = pubKey; - context->verify = (SFTKVerify) nsc_ECDSAVerifyStub; - context->destroy = sftk_Null; - break; + case CKM_ECDSA_SHA1: + context->multi = PR_TRUE; + crv = sftk_doSubSHA1(context); + if (crv != CKR_OK) + break; + /* fall through */ + case CKM_ECDSA: + if (key_type != CKK_EC) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + pubKey = sftk_GetPubKey(key, CKK_EC, &crv); + if (pubKey == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + context->cipherInfo = pubKey; + context->verify = (SFTKVerify)nsc_ECDSAVerifyStub; + context->destroy = sftk_Null; + break; #endif /* NSS_DISABLE_ECC */ - INIT_HMAC_MECH(MD2) - INIT_HMAC_MECH(MD5) - INIT_HMAC_MECH(SHA224) - INIT_HMAC_MECH(SHA256) - INIT_HMAC_MECH(SHA384) - INIT_HMAC_MECH(SHA512) - - case CKM_SHA_1_HMAC_GENERAL: - crv = sftk_doHMACInit(context,HASH_AlgSHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SHA_1_HMAC: - crv = sftk_doHMACInit(context,HASH_AlgSHA1,key,SHA1_LENGTH); - break; - - case CKM_SSL3_MD5_MAC: - crv = sftk_doSSLMACInit(context,SEC_OID_MD5,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_SSL3_SHA1_MAC: - crv = sftk_doSSLMACInit(context,SEC_OID_SHA1,key, - *(CK_ULONG *)pMechanism->pParameter); - break; - case CKM_TLS_PRF_GENERAL: - crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgNULL, 0); - break; - case CKM_NSS_TLS_PRF_GENERAL_SHA256: - crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgSHA256, 0); - break; - - default: - crv = CKR_MECHANISM_INVALID; - break; + INIT_HMAC_MECH(MD2) + INIT_HMAC_MECH(MD5) + INIT_HMAC_MECH(SHA224) + INIT_HMAC_MECH(SHA256) + INIT_HMAC_MECH(SHA384) + INIT_HMAC_MECH(SHA512) + + case CKM_SHA_1_HMAC_GENERAL: + crv = sftk_doHMACInit(context, HASH_AlgSHA1, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_SHA_1_HMAC: + crv = sftk_doHMACInit(context, HASH_AlgSHA1, key, SHA1_LENGTH); + break; + + case CKM_SSL3_MD5_MAC: + crv = sftk_doSSLMACInit(context, SEC_OID_MD5, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_SSL3_SHA1_MAC: + crv = sftk_doSSLMACInit(context, SEC_OID_SHA1, key, + *(CK_ULONG *)pMechanism->pParameter); + break; + case CKM_TLS_PRF_GENERAL: + crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgNULL, 0); + break; + case CKM_NSS_TLS_PRF_GENERAL_SHA256: + crv = sftk_TLSPRFInit(context, key, key_type, HASH_AlgSHA256, 0); + break; + + default: + crv = CKR_MECHANISM_INVALID; + break; } if (crv != CKR_OK) { - if (info) PORT_Free(info); + if (info) + PORT_Free(info); sftk_FreeContext(context); - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } sftk_SetContextByType(session, SFTK_VERIFY, context); sftk_FreeSession(session); return CKR_OK; } -/* NSC_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, +/* NSC_Verify verifies a signature in a single-part operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature */ -CK_RV NSC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, - CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) +CK_RV +NSC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, + CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { SFTKSession *session; SFTKSessionContext *context; @@ -3194,45 +3367,46 @@ CK_RV NSC_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_VERIFY,PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_VERIFY, PR_FALSE, &session); + if (crv != CKR_OK) + return crv; /* multi part Verifying are completely implemented by VerifyUpdate and * VerifyFinal */ if (context->multi) { /* VerifyFinal can't follow failed VerifyUpdate */ - if( CKR_OK == (crv = NSC_VerifyUpdate(hSession, pData, ulDataLen))) + if (CKR_OK == (crv = NSC_VerifyUpdate(hSession, pData, ulDataLen))) crv = NSC_VerifyFinal(hSession, pSignature, ulSignatureLen); } else { - if (SECSuccess != (*context->verify)(context->cipherInfo,pSignature, + if (SECSuccess != (*context->verify)(context->cipherInfo, pSignature, ulSignatureLen, pData, ulDataLen)) crv = sftk_MapCryptError(PORT_GetError()); - sftk_TerminateOp( session, SFTK_VERIFY, context ); + sftk_TerminateOp(session, SFTK_VERIFY, context); } sftk_FreeSession(session); return crv; } - -/* NSC_VerifyUpdate continues a multiple-part verification operation, - * where the signature is an appendix to the data, +/* NSC_VerifyUpdate continues a multiple-part verification operation, + * where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature * * A call which results in an error terminates the operation [PKCS#11,v2.11] */ -CK_RV NSC_VerifyUpdate( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen) +CK_RV +NSC_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen) { CHECK_FORK(); return sftk_MACUpdate(hSession, pPart, ulPartLen, SFTK_VERIFY); } - -/* NSC_VerifyFinal finishes a multiple-part verification operation, +/* NSC_VerifyFinal finishes a multiple-part verification operation, * checking the signature. */ -CK_RV NSC_VerifyFinal(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG ulSignatureLen) +CK_RV +NSC_VerifyFinal(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { SFTKSession *session; SFTKSessionContext *context; @@ -3240,34 +3414,33 @@ CK_RV NSC_VerifyFinal(CK_SESSION_HANDLE hSession, CHECK_FORK(); - if (!pSignature) - return CKR_ARGUMENTS_BAD; + if (!pSignature) + return CKR_ARGUMENTS_BAD; /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_VERIFY,PR_TRUE,&session); - if (crv != CKR_OK) - return crv; - + crv = sftk_GetContext(hSession, &context, SFTK_VERIFY, PR_TRUE, &session); + if (crv != CKR_OK) + return crv; + if (context->hashInfo) { unsigned int digestLen; unsigned char tmpbuf[SFTK_MAX_MAC_LENGTH]; - + (*context->end)(context->hashInfo, tmpbuf, &digestLen, sizeof(tmpbuf)); - if( SECSuccess != (context->verify)(context->cipherInfo, pSignature, + if (SECSuccess != (context->verify)(context->cipherInfo, pSignature, ulSignatureLen, tmpbuf, digestLen)) crv = sftk_MapCryptError(PORT_GetError()); } else if (ulSignatureLen != context->macSize) { - /* must be block cipher MACing */ - crv = CKR_SIGNATURE_LEN_RANGE; + /* must be block cipher MACing */ + crv = CKR_SIGNATURE_LEN_RANGE; } else if (CKR_OK == (crv = sftk_MACFinal(context))) { - if (PORT_Memcmp(pSignature, context->macBuf, ulSignatureLen)) - crv = CKR_SIGNATURE_INVALID; + if (PORT_Memcmp(pSignature, context->macBuf, ulSignatureLen)) + crv = CKR_SIGNATURE_INVALID; } - sftk_TerminateOp( session, SFTK_VERIFY, context ); + sftk_TerminateOp(session, SFTK_VERIFY, context); sftk_FreeSession(session); return crv; - } /* @@ -3303,11 +3476,12 @@ sftk_RSACheckSignRecoverRaw(NSSLOWKEYPublicKey *key, unsigned char *data, sig, sigLen); } -/* NSC_VerifyRecoverInit initializes a signature verification operation, - * where the data is recovered from the signature. +/* NSC_VerifyRecoverInit initializes a signature verification operation, + * where the data is recovered from the signature. * E.g. Decryption with the user's public key */ -CK_RV NSC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_OBJECT_HANDLE hKey) +CK_RV +NSC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { SFTKSession *session; SFTKObject *key; @@ -3319,56 +3493,58 @@ CK_RV NSC_VerifyRecoverInit(CK_SESSION_HANDLE hSession, CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - crv = sftk_InitGeneric(session,&context,SFTK_VERIFY_RECOVER, - &key,hKey,&key_type,CKO_PUBLIC_KEY,CKA_VERIFY_RECOVER); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + crv = sftk_InitGeneric(session, &context, SFTK_VERIFY_RECOVER, + &key, hKey, &key_type, CKO_PUBLIC_KEY, CKA_VERIFY_RECOVER); if (crv != CKR_OK) { - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } context->multi = PR_TRUE; - switch(pMechanism->mechanism) { - case CKM_RSA_PKCS: - case CKM_RSA_X_509: - if (key_type != CKK_RSA) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - context->multi = PR_FALSE; - context->rsa = PR_TRUE; - pubKey = sftk_GetPubKey(key,CKK_RSA,&crv); - if (pubKey == NULL) { - break; - } - context->cipherInfo = pubKey; - context->update = (SFTKCipher) (pMechanism->mechanism == CKM_RSA_X_509 - ? sftk_RSACheckSignRecoverRaw : sftk_RSACheckSignRecover); - context->destroy = sftk_Null; - break; - default: - crv = CKR_MECHANISM_INVALID; - break; + switch (pMechanism->mechanism) { + case CKM_RSA_PKCS: + case CKM_RSA_X_509: + if (key_type != CKK_RSA) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + context->multi = PR_FALSE; + context->rsa = PR_TRUE; + pubKey = sftk_GetPubKey(key, CKK_RSA, &crv); + if (pubKey == NULL) { + break; + } + context->cipherInfo = pubKey; + context->update = (SFTKCipher)(pMechanism->mechanism == CKM_RSA_X_509 + ? sftk_RSACheckSignRecoverRaw + : sftk_RSACheckSignRecover); + context->destroy = sftk_Null; + break; + default: + crv = CKR_MECHANISM_INVALID; + break; } if (crv != CKR_OK) { PORT_Free(context); - sftk_FreeSession(session); - return crv; + sftk_FreeSession(session); + return crv; } sftk_SetContextByType(session, SFTK_VERIFY_RECOVER, context); sftk_FreeSession(session); return CKR_OK; } - -/* NSC_VerifyRecover verifies a signature in a single-part operation, - * where the data is recovered from the signature. +/* NSC_VerifyRecover verifies a signature in a single-part operation, + * where the data is recovered from the signature. * E.g. Decryption with the user's public key */ -CK_RV NSC_VerifyRecover(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pSignature,CK_ULONG ulSignatureLen, - CK_BYTE_PTR pData,CK_ULONG_PTR pulDataLen) +CK_RV +NSC_VerifyRecover(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen, + CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { SFTKSession *session; SFTKSessionContext *context; @@ -3380,35 +3556,37 @@ CK_RV NSC_VerifyRecover(CK_SESSION_HANDLE hSession, CHECK_FORK(); /* make sure we're legal */ - crv = sftk_GetContext(hSession,&context,SFTK_VERIFY_RECOVER, - PR_FALSE,&session); - if (crv != CKR_OK) return crv; + crv = sftk_GetContext(hSession, &context, SFTK_VERIFY_RECOVER, + PR_FALSE, &session); + if (crv != CKR_OK) + return crv; if (pData == NULL) { - /* to return the actual size, we need to do the decrypt, just return - * the max size, which is the size of the input signature. */ - *pulDataLen = ulSignatureLen; - rv = SECSuccess; - goto finish; + /* to return the actual size, we need to do the decrypt, just return + * the max size, which is the size of the input signature. */ + *pulDataLen = ulSignatureLen; + rv = SECSuccess; + goto finish; } - rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, - pSignature, ulSignatureLen); - *pulDataLen = (CK_ULONG) outlen; + rv = (*context->update)(context->cipherInfo, pData, &outlen, maxoutlen, + pSignature, ulSignatureLen); + *pulDataLen = (CK_ULONG)outlen; sftk_TerminateOp(session, SFTK_VERIFY_RECOVER, context); finish: sftk_FreeSession(session); - return (rv == SECSuccess) ? CKR_OK : sftk_MapVerifyError(PORT_GetError()); + return (rv == SECSuccess) ? CKR_OK : sftk_MapVerifyError(PORT_GetError()); } /* **************************** Random Functions: ************************ */ -/* NSC_SeedRandom mixes additional seed material into the token's random number +/* NSC_SeedRandom mixes additional seed material into the token's random number * generator. */ -CK_RV NSC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, - CK_ULONG ulSeedLen) +CK_RV +NSC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, + CK_ULONG ulSeedLen) { SECStatus rv; @@ -3419,8 +3597,9 @@ CK_RV NSC_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, } /* NSC_GenerateRandom generates random data. */ -CK_RV NSC_GenerateRandom(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) +CK_RV +NSC_GenerateRandom(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) { SECStatus rv; @@ -3438,35 +3617,35 @@ CK_RV NSC_GenerateRandom(CK_SESSION_HANDLE hSession, **************************** Key Functions: ************************ */ - /* * generate a password based encryption key. This code uses * PKCS5 to do the work. */ static CK_RV nsc_pbe_key_gen(NSSPKCS5PBEParameter *pkcs5_pbe, CK_MECHANISM_PTR pMechanism, - void *buf, CK_ULONG *key_length, PRBool faulty3DES) + void *buf, CK_ULONG *key_length, PRBool faulty3DES) { SECItem *pbe_key = NULL, iv, pwitem; CK_PBE_PARAMS *pbe_params = NULL; CK_PKCS5_PBKD2_PARAMS *pbkd2_params = NULL; *key_length = 0; - iv.data = NULL; iv.len = 0; + iv.data = NULL; + iv.len = 0; if (pMechanism->mechanism == CKM_PKCS5_PBKD2) { - pbkd2_params = (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter; - pwitem.data = (unsigned char *)pbkd2_params->pPassword; - /* was this a typo in the PKCS #11 spec? */ - pwitem.len = *pbkd2_params->ulPasswordLen; + pbkd2_params = (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter; + pwitem.data = (unsigned char *)pbkd2_params->pPassword; + /* was this a typo in the PKCS #11 spec? */ + pwitem.len = *pbkd2_params->ulPasswordLen; } else { - pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; - pwitem.data = (unsigned char *)pbe_params->pPassword; - pwitem.len = pbe_params->ulPasswordLen; + pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; + pwitem.data = (unsigned char *)pbe_params->pPassword; + pwitem.len = pbe_params->ulPasswordLen; } pbe_key = nsspkcs5_ComputeKeyAndIV(pkcs5_pbe, &pwitem, &iv, faulty3DES); if (pbe_key == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } PORT_Memcpy(buf, pbe_key->data, pbe_key->len); @@ -3476,7 +3655,7 @@ nsc_pbe_key_gen(NSSPKCS5PBEParameter *pkcs5_pbe, CK_MECHANISM_PTR pMechanism, if (iv.data) { if (pbe_params && pbe_params->pInitVector != NULL) { - PORT_Memcpy(pbe_params->pInitVector, iv.data, iv.len); + PORT_Memcpy(pbe_params->pInitVector, iv.data, iv.len); } PORT_Free(iv.data); } @@ -3484,24 +3663,24 @@ nsc_pbe_key_gen(NSSPKCS5PBEParameter *pkcs5_pbe, CK_MECHANISM_PTR pMechanism, return CKR_OK; } -/* +/* * this is coded for "full" support. These selections will be limitted to * the official subset by freebl. */ static unsigned int sftk_GetSubPrimeFromPrime(unsigned int primeBits) { - if (primeBits <= 1024) { - return 160; - } else if (primeBits <= 2048) { - return 224; - } else if (primeBits <= 3072) { - return 256; - } else if (primeBits <= 7680) { - return 384; - } else { - return 512; - } + if (primeBits <= 1024) { + return 160; + } else if (primeBits <= 2048) { + return 224; + } else if (primeBits <= 3072) { + return 256; + } else if (primeBits <= 7680) { + return 384; + } else { + return 512; + } } static CK_RV @@ -3520,144 +3699,218 @@ nsc_parameter_gen(CK_KEY_TYPE key_type, SFTKObject *key) attribute = sftk_FindAttribute(key, CKA_PRIME_BITS); if (attribute == NULL) { - return CKR_TEMPLATE_INCOMPLETE; + attribute = sftk_FindAttribute(key, CKA_PRIME); + if (attribute == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } else { + primeBits = attribute->attrib.ulValueLen; + sftk_FreeAttribute(attribute); + } + } else { + primeBits = (unsigned int)*(CK_ULONG *)attribute->attrib.pValue; + sftk_FreeAttribute(attribute); } - primeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue; - sftk_FreeAttribute(attribute); if (primeBits < 1024) { - j = PQG_PBITS_TO_INDEX(primeBits); - if (j == (unsigned int)-1) { - return CKR_ATTRIBUTE_VALUE_INVALID; - } + j = PQG_PBITS_TO_INDEX(primeBits); + if (j == (unsigned int)-1) { + return CKR_ATTRIBUTE_VALUE_INVALID; + } } - attribute = sftk_FindAttribute(key, CKA_NETSCAPE_PQG_SEED_BITS); + attribute = sftk_FindAttribute(key, CKA_NSS_PQG_SEED_BITS); if (attribute != NULL) { - seedBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue; - sftk_FreeAttribute(attribute); + seedBits = (unsigned int)*(CK_ULONG *)attribute->attrib.pValue; + sftk_FreeAttribute(attribute); } attribute = sftk_FindAttribute(key, CKA_SUBPRIME_BITS); if (attribute != NULL) { - subprimeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue; - sftk_FreeAttribute(attribute); + subprimeBits = (unsigned int)*(CK_ULONG *)attribute->attrib.pValue; + sftk_FreeAttribute(attribute); + } + + /* if P and Q are supplied, we want to generate a new G */ + attribute = sftk_FindAttribute(key, CKA_PRIME); + if (attribute != NULL) { + PLArenaPool *arena; + + sftk_FreeAttribute(attribute); + arena = PORT_NewArena(1024); + if (arena == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } + params = PORT_ArenaAlloc(arena, sizeof(*params)); + if (params == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } + params->arena = arena; + crv = sftk_Attribute2SSecItem(arena, ¶ms->prime, key, CKA_PRIME); + if (crv != CKR_OK) { + goto loser; + } + crv = sftk_Attribute2SSecItem(arena, ¶ms->subPrime, + key, CKA_SUBPRIME); + if (crv != CKR_OK) { + goto loser; + } + + arena = PORT_NewArena(1024); + if (arena == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } + vfy = PORT_ArenaAlloc(arena, sizeof(*vfy)); + if (vfy == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } + vfy->arena = arena; + crv = sftk_Attribute2SSecItem(arena, &vfy->seed, key, CKA_NSS_PQG_SEED); + if (crv != CKR_OK) { + goto loser; + } + crv = sftk_Attribute2SSecItem(arena, &vfy->h, key, CKA_NSS_PQG_H); + if (crv != CKR_OK) { + goto loser; + } + sftk_DeleteAttributeType(key, CKA_PRIME); + sftk_DeleteAttributeType(key, CKA_SUBPRIME); + sftk_DeleteAttributeType(key, CKA_NSS_PQG_SEED); + sftk_DeleteAttributeType(key, CKA_NSS_PQG_H); } - sftk_DeleteAttributeType(key,CKA_PRIME_BITS); - sftk_DeleteAttributeType(key,CKA_SUBPRIME_BITS); - sftk_DeleteAttributeType(key,CKA_NETSCAPE_PQG_SEED_BITS); + sftk_DeleteAttributeType(key, CKA_PRIME_BITS); + sftk_DeleteAttributeType(key, CKA_SUBPRIME_BITS); + sftk_DeleteAttributeType(key, CKA_NSS_PQG_SEED_BITS); /* use the old PQG interface if we have old input data */ if ((primeBits < 1024) || ((primeBits == 1024) && (subprimeBits == 0))) { - if (seedBits == 0) { - rv = PQG_ParamGen(j, ¶ms, &vfy); - } else { - rv = PQG_ParamGenSeedLen(j,seedBits/8, ¶ms, &vfy); - } + if (seedBits == 0) { + rv = PQG_ParamGen(j, ¶ms, &vfy); + } else { + rv = PQG_ParamGenSeedLen(j, seedBits / 8, ¶ms, &vfy); + } } else { - if (subprimeBits == 0) { - subprimeBits = sftk_GetSubPrimeFromPrime(primeBits); + if (subprimeBits == 0) { + subprimeBits = sftk_GetSubPrimeFromPrime(primeBits); } - if (seedBits == 0) { - seedBits = primeBits; - } - rv = PQG_ParamGenV2(primeBits, subprimeBits, seedBits/8, ¶ms, &vfy); + if (seedBits == 0) { + seedBits = primeBits; + } + rv = PQG_ParamGenV2(primeBits, subprimeBits, seedBits / 8, ¶ms, &vfy); } - - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; - } - return sftk_MapCryptError(PORT_GetError()); - } - crv = sftk_AddAttributeType(key,CKA_PRIME, - params->prime.data, params->prime.len); - if (crv != CKR_OK) goto loser; - crv = sftk_AddAttributeType(key,CKA_SUBPRIME, - params->subPrime.data, params->subPrime.len); - if (crv != CKR_OK) goto loser; - crv = sftk_AddAttributeType(key,CKA_BASE, - params->base.data, params->base.len); - if (crv != CKR_OK) goto loser; + if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + sftk_fatalError = PR_TRUE; + } + return sftk_MapCryptError(PORT_GetError()); + } + crv = sftk_AddAttributeType(key, CKA_PRIME, + params->prime.data, params->prime.len); + if (crv != CKR_OK) + goto loser; + crv = sftk_AddAttributeType(key, CKA_SUBPRIME, + params->subPrime.data, params->subPrime.len); + if (crv != CKR_OK) + goto loser; + crv = sftk_AddAttributeType(key, CKA_BASE, + params->base.data, params->base.len); + if (crv != CKR_OK) + goto loser; counter = vfy->counter; - crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_COUNTER, - &counter, sizeof(counter)); - crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_SEED, - vfy->seed.data, vfy->seed.len); - if (crv != CKR_OK) goto loser; - crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_H, - vfy->h.data, vfy->h.len); - if (crv != CKR_OK) goto loser; + crv = sftk_AddAttributeType(key, CKA_NSS_PQG_COUNTER, + &counter, sizeof(counter)); + crv = sftk_AddAttributeType(key, CKA_NSS_PQG_SEED, + vfy->seed.data, vfy->seed.len); + if (crv != CKR_OK) + goto loser; + crv = sftk_AddAttributeType(key, CKA_NSS_PQG_H, + vfy->h.data, vfy->h.len); + if (crv != CKR_OK) + goto loser; loser: - PQG_DestroyParams(params); + if (params) { + PQG_DestroyParams(params); + } if (vfy) { - PQG_DestroyVerify(vfy); + PQG_DestroyVerify(vfy); } return crv; } - static CK_RV nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE mechanism, CK_KEY_TYPE *key_type, - CK_ULONG *key_length) + CK_ULONG *key_length) { CK_RV crv = CKR_OK; switch (mechanism) { - case CKM_RC2_KEY_GEN: - *key_type = CKK_RC2; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; + case CKM_RC2_KEY_GEN: + *key_type = CKK_RC2; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; #if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_KEY_GEN: - *key_type = CKK_RC5; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; + case CKM_RC5_KEY_GEN: + *key_type = CKK_RC5; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; #endif - case CKM_RC4_KEY_GEN: - *key_type = CKK_RC4; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - case CKM_GENERIC_SECRET_KEY_GEN: - *key_type = CKK_GENERIC_SECRET; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - case CKM_CDMF_KEY_GEN: - *key_type = CKK_CDMF; - *key_length = 8; - break; - case CKM_DES_KEY_GEN: - *key_type = CKK_DES; - *key_length = 8; - break; - case CKM_DES2_KEY_GEN: - *key_type = CKK_DES2; - *key_length = 16; - break; - case CKM_DES3_KEY_GEN: - *key_type = CKK_DES3; - *key_length = 24; - break; - case CKM_SEED_KEY_GEN: - *key_type = CKK_SEED; - *key_length = 16; - break; - case CKM_CAMELLIA_KEY_GEN: - *key_type = CKK_CAMELLIA; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - case CKM_AES_KEY_GEN: - *key_type = CKK_AES; - if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE; - break; - default: - PORT_Assert(0); - crv = CKR_MECHANISM_INVALID; - break; + case CKM_RC4_KEY_GEN: + *key_type = CKK_RC4; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; + case CKM_GENERIC_SECRET_KEY_GEN: + *key_type = CKK_GENERIC_SECRET; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; + case CKM_CDMF_KEY_GEN: + *key_type = CKK_CDMF; + *key_length = 8; + break; + case CKM_DES_KEY_GEN: + *key_type = CKK_DES; + *key_length = 8; + break; + case CKM_DES2_KEY_GEN: + *key_type = CKK_DES2; + *key_length = 16; + break; + case CKM_DES3_KEY_GEN: + *key_type = CKK_DES3; + *key_length = 24; + break; + case CKM_SEED_KEY_GEN: + *key_type = CKK_SEED; + *key_length = 16; + break; + case CKM_CAMELLIA_KEY_GEN: + *key_type = CKK_CAMELLIA; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; + case CKM_AES_KEY_GEN: + *key_type = CKK_AES; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; + case CKM_NSS_CHACHA20_KEY_GEN: + *key_type = CKK_NSS_CHACHA20; + if (*key_length == 0) + crv = CKR_TEMPLATE_INCOMPLETE; + break; + default: + PORT_Assert(0); + crv = CKR_MECHANISM_INVALID; + break; } return crv; @@ -3666,7 +3919,7 @@ nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE mechanism, CK_KEY_TYPE *key_type, CK_RV nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe) { - SECItem salt; + SECItem salt; CK_PBE_PARAMS *pbe_params = NULL; NSSPKCS5PBEParameter *params; PLArenaPool *arena = NULL; @@ -3676,14 +3929,14 @@ nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe) arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE); if (arena == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } - params = (NSSPKCS5PBEParameter *) PORT_ArenaZAlloc(arena, - sizeof(NSSPKCS5PBEParameter)); + params = (NSSPKCS5PBEParameter *)PORT_ArenaZAlloc(arena, + sizeof(NSSPKCS5PBEParameter)); if (params == NULL) { - PORT_FreeArena(arena,PR_TRUE); - return CKR_HOST_MEMORY; + PORT_FreeArena(arena, PR_TRUE); + return CKR_HOST_MEMORY; } params->poolp = arena; @@ -3699,28 +3952,28 @@ nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe) salt.data = (unsigned char *)pbe_params->pSalt; salt.len = (unsigned int)pbe_params->ulSaltLen; salt.type = siBuffer; - rv = SECITEM_CopyItem(arena,¶ms->salt,&salt); + rv = SECITEM_CopyItem(arena, ¶ms->salt, &salt); if (rv != SECSuccess) { - PORT_FreeArena(arena,PR_TRUE); - return CKR_HOST_MEMORY; + PORT_FreeArena(arena, PR_TRUE); + return CKR_HOST_MEMORY; } switch (pMechanism->mechanism) { - case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: - case CKM_PBA_SHA1_WITH_SHA1_HMAC: - params->hashType = HASH_AlgSHA1; - params->keyLen = 20; - break; - case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: - params->hashType = HASH_AlgMD5; - params->keyLen = 16; - break; - case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: - params->hashType = HASH_AlgMD2; - params->keyLen = 16; - break; - default: - PORT_FreeArena(arena,PR_TRUE); - return CKR_MECHANISM_INVALID; + case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: + case CKM_PBA_SHA1_WITH_SHA1_HMAC: + params->hashType = HASH_AlgSHA1; + params->keyLen = 20; + break; + case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: + params->hashType = HASH_AlgMD5; + params->keyLen = 16; + break; + case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: + params->hashType = HASH_AlgMD2; + params->keyLen = 16; + break; + default: + PORT_FreeArena(arena, PR_TRUE); + return CKR_MECHANISM_INVALID; } *pbe = params; return CKR_OK; @@ -3728,13 +3981,14 @@ nsc_SetupHMACKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe) /* maybe this should be table driven? */ static CK_RV -nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, - CK_KEY_TYPE *key_type, CK_ULONG *key_length) +nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, + CK_KEY_TYPE *key_type, CK_ULONG *key_length) { CK_RV crv = CKR_OK; SECOidData *oid; CK_PBE_PARAMS *pbe_params = NULL; NSSPKCS5PBEParameter *params = NULL; + HASH_HashType hashType = HASH_AlgSHA1; CK_PKCS5_PBKD2_PARAMS *pbkd2_params = NULL; SECItem salt; CK_ULONG iteration = 0; @@ -3743,85 +3997,100 @@ nsc_SetupPBEKeyGen(CK_MECHANISM_PTR pMechanism, NSSPKCS5PBEParameter **pbe, oid = SECOID_FindOIDByMechanism(pMechanism->mechanism); if (oid == NULL) { - return CKR_MECHANISM_INVALID; + return CKR_MECHANISM_INVALID; } if (pMechanism->mechanism == CKM_PKCS5_PBKD2) { - pbkd2_params = (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter; - if (pbkd2_params->saltSource != CKZ_SALT_SPECIFIED) { - return CKR_MECHANISM_PARAM_INVALID; - } - salt.data = (unsigned char *)pbkd2_params->pSaltSourceData; - salt.len = (unsigned int)pbkd2_params->ulSaltSourceDataLen; - iteration = pbkd2_params->iterations; + pbkd2_params = (CK_PKCS5_PBKD2_PARAMS *)pMechanism->pParameter; + if (pbkd2_params == NULL) { + return CKR_MECHANISM_PARAM_INVALID; + } + switch (pbkd2_params->prf) { + case CKP_PKCS5_PBKD2_HMAC_SHA1: + hashType = HASH_AlgSHA1; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA224: + hashType = HASH_AlgSHA224; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA256: + hashType = HASH_AlgSHA256; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA384: + hashType = HASH_AlgSHA384; + break; + case CKP_PKCS5_PBKD2_HMAC_SHA512: + hashType = HASH_AlgSHA512; + break; + default: + return CKR_MECHANISM_PARAM_INVALID; + } + if (pbkd2_params->saltSource != CKZ_SALT_SPECIFIED) { + return CKR_MECHANISM_PARAM_INVALID; + } + salt.data = (unsigned char *)pbkd2_params->pSaltSourceData; + salt.len = (unsigned int)pbkd2_params->ulSaltSourceDataLen; + iteration = pbkd2_params->iterations; } else { - pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; - salt.data = (unsigned char *)pbe_params->pSalt; - salt.len = (unsigned int)pbe_params->ulSaltLen; - iteration = pbe_params->ulIteration; + pbe_params = (CK_PBE_PARAMS *)pMechanism->pParameter; + salt.data = (unsigned char *)pbe_params->pSalt; + salt.len = (unsigned int)pbe_params->ulSaltLen; + iteration = pbe_params->ulIteration; } - params=nsspkcs5_NewParam(oid->offset, &salt, iteration); + params = nsspkcs5_NewParam(oid->offset, hashType, &salt, iteration); if (params == NULL) { - return CKR_MECHANISM_INVALID; + return CKR_MECHANISM_INVALID; } switch (params->encAlg) { - case SEC_OID_DES_CBC: - *key_type = CKK_DES; - *key_length = params->keyLen; - break; - case SEC_OID_DES_EDE3_CBC: - *key_type = params->is2KeyDES ? CKK_DES2 : CKK_DES3; - *key_length = params->keyLen; - break; - case SEC_OID_RC2_CBC: - *key_type = CKK_RC2; - *key_length = params->keyLen; - break; - case SEC_OID_RC4: - *key_type = CKK_RC4; - *key_length = params->keyLen; - break; - case SEC_OID_PKCS5_PBKDF2: - /* sigh, PKCS #11 currently only defines SHA1 for the KDF hash type. - * we do the check here because this where we would handle multiple - * hash types in the future */ - if (pbkd2_params == NULL || - pbkd2_params->prf != CKP_PKCS5_PBKD2_HMAC_SHA1) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - /* key type must already be set */ - if (*key_type == CKK_INVALID_KEY_TYPE) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - /* PBKDF2 needs to calculate the key length from the other parameters - */ - if (*key_length == 0) { - *key_length = sftk_MapKeySize(*key_type); - } - if (*key_length == 0) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - params->keyLen = *key_length; - break; - default: - crv = CKR_MECHANISM_INVALID; - nsspkcs5_DestroyPBEParameter(params); - break; + case SEC_OID_DES_CBC: + *key_type = CKK_DES; + *key_length = params->keyLen; + break; + case SEC_OID_DES_EDE3_CBC: + *key_type = params->is2KeyDES ? CKK_DES2 : CKK_DES3; + *key_length = params->keyLen; + break; + case SEC_OID_RC2_CBC: + *key_type = CKK_RC2; + *key_length = params->keyLen; + break; + case SEC_OID_RC4: + *key_type = CKK_RC4; + *key_length = params->keyLen; + break; + case SEC_OID_PKCS5_PBKDF2: + /* key type must already be set */ + if (*key_type == CKK_INVALID_KEY_TYPE) { + crv = CKR_TEMPLATE_INCOMPLETE; + break; + } + /* PBKDF2 needs to calculate the key length from the other parameters + */ + if (*key_length == 0) { + *key_length = sftk_MapKeySize(*key_type); + } + if (*key_length == 0) { + crv = CKR_TEMPLATE_INCOMPLETE; + break; + } + params->keyLen = *key_length; + break; + default: + crv = CKR_MECHANISM_INVALID; + nsspkcs5_DestroyPBEParameter(params); + break; } if (crv == CKR_OK) { - *pbe = params; + *pbe = params; } return crv; } /* NSC_GenerateKey generates a secret key, creating a new key object. */ -CK_RV NSC_GenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism,CK_ATTRIBUTE_PTR pTemplate,CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey) +CK_RV +NSC_GenerateKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phKey) { SFTKObject *key; SFTKSession *session; @@ -3834,12 +4103,16 @@ CK_RV NSC_GenerateKey(CK_SESSION_HANDLE hSession, int i; SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); unsigned char buf[MAX_KEY_LEN]; - enum {nsc_pbe, nsc_ssl, nsc_bulk, nsc_param, nsc_jpake} key_gen_type; + enum { nsc_pbe, + nsc_ssl, + nsc_bulk, + nsc_param, + nsc_jpake } key_gen_type; NSSPKCS5PBEParameter *pbe_param; SSL3RSAPreMasterSecret *rsa_pms; CK_VERSION *version; - /* in very old versions of NSS, there were implementation errors with key - * generation methods. We want to beable to read these, but not + /* in very old versions of NSS, there were implementation errors with key + * generation methods. We want to beable to read these, but not * produce them any more. The affected algorithm was 3DES. */ PRBool faultyPBE3DES = PR_FALSE; @@ -3855,206 +4128,232 @@ CK_RV NSC_GenerateKey(CK_SESSION_HANDLE hSession, */ key = sftk_NewObject(slot); /* fill in the handle later */ if (key == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* * load the template values into the object */ - for (i=0; i < (int) ulCount; i++) { - if (pTemplate[i].type == CKA_VALUE_LEN) { - key_length = *(CK_ULONG *)pTemplate[i].pValue; - continue; - } - /* some algorithms need keytype specified */ - if (pTemplate[i].type == CKA_KEY_TYPE) { - key_type = *(CK_ULONG *)pTemplate[i].pValue; - continue; - } - - crv = sftk_AddAttributeType(key,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; + for (i = 0; i < (int)ulCount; i++) { + if (pTemplate[i].type == CKA_VALUE_LEN) { + key_length = *(CK_ULONG *)pTemplate[i].pValue; + continue; + } + /* some algorithms need keytype specified */ + if (pTemplate[i].type == CKA_KEY_TYPE) { + key_type = *(CK_ULONG *)pTemplate[i].pValue; + continue; + } + + crv = sftk_AddAttributeType(key, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) + break; } if (crv != CKR_OK) { - sftk_FreeObject(key); - return crv; + sftk_FreeObject(key); + return crv; } /* make sure we don't have any class, key_type, or value fields */ - sftk_DeleteAttributeType(key,CKA_CLASS); - sftk_DeleteAttributeType(key,CKA_KEY_TYPE); - sftk_DeleteAttributeType(key,CKA_VALUE); + sftk_DeleteAttributeType(key, CKA_CLASS); + sftk_DeleteAttributeType(key, CKA_KEY_TYPE); + sftk_DeleteAttributeType(key, CKA_VALUE); /* Now Set up the parameters to generate the key (based on mechanism) */ key_gen_type = nsc_bulk; /* bulk key by default */ switch (pMechanism->mechanism) { - case CKM_CDMF_KEY_GEN: - case CKM_DES_KEY_GEN: - case CKM_DES2_KEY_GEN: - case CKM_DES3_KEY_GEN: - checkWeak = PR_TRUE; + case CKM_CDMF_KEY_GEN: + case CKM_DES_KEY_GEN: + case CKM_DES2_KEY_GEN: + case CKM_DES3_KEY_GEN: + checkWeak = PR_TRUE; /* fall through */ - case CKM_RC2_KEY_GEN: - case CKM_RC4_KEY_GEN: - case CKM_GENERIC_SECRET_KEY_GEN: - case CKM_SEED_KEY_GEN: - case CKM_CAMELLIA_KEY_GEN: - case CKM_AES_KEY_GEN: + case CKM_RC2_KEY_GEN: + case CKM_RC4_KEY_GEN: + case CKM_GENERIC_SECRET_KEY_GEN: + case CKM_SEED_KEY_GEN: + case CKM_CAMELLIA_KEY_GEN: + case CKM_AES_KEY_GEN: + case CKM_NSS_CHACHA20_KEY_GEN: #if NSS_SOFTOKEN_DOES_RC5 - case CKM_RC5_KEY_GEN: + case CKM_RC5_KEY_GEN: #endif - crv = nsc_SetupBulkKeyGen(pMechanism->mechanism,&key_type,&key_length); - break; - case CKM_SSL3_PRE_MASTER_KEY_GEN: - key_type = CKK_GENERIC_SECRET; - key_length = 48; - key_gen_type = nsc_ssl; - break; - case CKM_PBA_SHA1_WITH_SHA1_HMAC: - case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: - case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: - case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: - key_gen_type = nsc_pbe; - key_type = CKK_GENERIC_SECRET; - crv = nsc_SetupHMACKeyGen(pMechanism, &pbe_param); - break; - case CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC: - faultyPBE3DES = PR_TRUE; + crv = nsc_SetupBulkKeyGen(pMechanism->mechanism, &key_type, &key_length); + break; + case CKM_SSL3_PRE_MASTER_KEY_GEN: + key_type = CKK_GENERIC_SECRET; + key_length = 48; + key_gen_type = nsc_ssl; + break; + case CKM_PBA_SHA1_WITH_SHA1_HMAC: + case CKM_NETSCAPE_PBE_SHA1_HMAC_KEY_GEN: + case CKM_NETSCAPE_PBE_MD5_HMAC_KEY_GEN: + case CKM_NETSCAPE_PBE_MD2_HMAC_KEY_GEN: + key_gen_type = nsc_pbe; + key_type = CKK_GENERIC_SECRET; + crv = nsc_SetupHMACKeyGen(pMechanism, &pbe_param); + break; + case CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC: + faultyPBE3DES = PR_TRUE; /* fall through */ - case CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC: - case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC: - case CKM_NETSCAPE_PBE_SHA1_DES_CBC: - case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC: - case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4: - case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4: - case CKM_PBE_SHA1_DES3_EDE_CBC: - case CKM_PBE_SHA1_DES2_EDE_CBC: - case CKM_PBE_SHA1_RC2_128_CBC: - case CKM_PBE_SHA1_RC2_40_CBC: - case CKM_PBE_SHA1_RC4_128: - case CKM_PBE_SHA1_RC4_40: - case CKM_PBE_MD5_DES_CBC: - case CKM_PBE_MD2_DES_CBC: - case CKM_PKCS5_PBKD2: - key_gen_type = nsc_pbe; - crv = nsc_SetupPBEKeyGen(pMechanism,&pbe_param, &key_type, &key_length); - break; - case CKM_DSA_PARAMETER_GEN: - key_gen_type = nsc_param; - key_type = CKK_DSA; - objclass = CKO_KG_PARAMETERS; - crv = CKR_OK; - break; - case CKM_NSS_JPAKE_ROUND1_SHA1: hashType = HASH_AlgSHA1; goto jpake1; - case CKM_NSS_JPAKE_ROUND1_SHA256: hashType = HASH_AlgSHA256; goto jpake1; - case CKM_NSS_JPAKE_ROUND1_SHA384: hashType = HASH_AlgSHA384; goto jpake1; - case CKM_NSS_JPAKE_ROUND1_SHA512: hashType = HASH_AlgSHA512; goto jpake1; -jpake1: - key_gen_type = nsc_jpake; - key_type = CKK_NSS_JPAKE_ROUND1; - objclass = CKO_PRIVATE_KEY; - if (pMechanism->pParameter == NULL || - pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKERound1Params)) { - crv = CKR_MECHANISM_PARAM_INVALID; + case CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC: + case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC2_CBC: + case CKM_NETSCAPE_PBE_SHA1_DES_CBC: + case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC2_CBC: + case CKM_NETSCAPE_PBE_SHA1_40_BIT_RC4: + case CKM_NETSCAPE_PBE_SHA1_128_BIT_RC4: + case CKM_PBE_SHA1_DES3_EDE_CBC: + case CKM_PBE_SHA1_DES2_EDE_CBC: + case CKM_PBE_SHA1_RC2_128_CBC: + case CKM_PBE_SHA1_RC2_40_CBC: + case CKM_PBE_SHA1_RC4_128: + case CKM_PBE_SHA1_RC4_40: + case CKM_PBE_MD5_DES_CBC: + case CKM_PBE_MD2_DES_CBC: + case CKM_PKCS5_PBKD2: + key_gen_type = nsc_pbe; + crv = nsc_SetupPBEKeyGen(pMechanism, &pbe_param, &key_type, &key_length); break; - } - if (sftk_isTrue(key, CKA_TOKEN)) { - crv = CKR_TEMPLATE_INCONSISTENT; + case CKM_DSA_PARAMETER_GEN: + key_gen_type = nsc_param; + key_type = CKK_DSA; + objclass = CKO_KG_PARAMETERS; + crv = CKR_OK; + break; + case CKM_NSS_JPAKE_ROUND1_SHA1: + hashType = HASH_AlgSHA1; + goto jpake1; + case CKM_NSS_JPAKE_ROUND1_SHA256: + hashType = HASH_AlgSHA256; + goto jpake1; + case CKM_NSS_JPAKE_ROUND1_SHA384: + hashType = HASH_AlgSHA384; + goto jpake1; + case CKM_NSS_JPAKE_ROUND1_SHA512: + hashType = HASH_AlgSHA512; + goto jpake1; + jpake1: + key_gen_type = nsc_jpake; + key_type = CKK_NSS_JPAKE_ROUND1; + objclass = CKO_PRIVATE_KEY; + if (pMechanism->pParameter == NULL || + pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKERound1Params)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + if (sftk_isTrue(key, CKA_TOKEN)) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + crv = CKR_OK; + break; + default: + crv = CKR_MECHANISM_INVALID; break; - } - crv = CKR_OK; - break; - default: - crv = CKR_MECHANISM_INVALID; - break; } /* make sure we aren't going to overflow the buffer */ if (sizeof(buf) < key_length) { - /* someone is getting pretty optimistic about how big their key can - * be... */ + /* someone is getting pretty optimistic about how big their key can + * be... */ crv = CKR_TEMPLATE_INCONSISTENT; } - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } /* if there was no error, * key_type *MUST* be set in the switch statement above */ - PORT_Assert( key_type != CKK_INVALID_KEY_TYPE ); + PORT_Assert(key_type != CKK_INVALID_KEY_TYPE); /* * now to the actual key gen. */ switch (key_gen_type) { - case nsc_pbe: - crv = nsc_pbe_key_gen(pbe_param, pMechanism, buf, &key_length, - faultyPBE3DES); - nsspkcs5_DestroyPBEParameter(pbe_param); - break; - case nsc_ssl: - rsa_pms = (SSL3RSAPreMasterSecret *)buf; - version = (CK_VERSION *)pMechanism->pParameter; - rsa_pms->client_version[0] = version->major; - rsa_pms->client_version[1] = version->minor; - crv = - NSC_GenerateRandom(0,&rsa_pms->random[0], sizeof(rsa_pms->random)); - break; - case nsc_bulk: - /* get the key, check for weak keys and repeat if found */ - do { - crv = NSC_GenerateRandom(0, buf, key_length); - } while (crv == CKR_OK && checkWeak && sftk_IsWeakKey(buf,key_type)); - break; - case nsc_param: - /* generate parameters */ - *buf = 0; - crv = nsc_parameter_gen(key_type,key); - break; - case nsc_jpake: - crv = jpake_Round1(hashType, - (CK_NSS_JPAKERound1Params *) pMechanism->pParameter, - key); - break; + case nsc_pbe: + crv = nsc_pbe_key_gen(pbe_param, pMechanism, buf, &key_length, + faultyPBE3DES); + nsspkcs5_DestroyPBEParameter(pbe_param); + break; + case nsc_ssl: + rsa_pms = (SSL3RSAPreMasterSecret *)buf; + version = (CK_VERSION *)pMechanism->pParameter; + rsa_pms->client_version[0] = version->major; + rsa_pms->client_version[1] = version->minor; + crv = + NSC_GenerateRandom(0, &rsa_pms->random[0], sizeof(rsa_pms->random)); + break; + case nsc_bulk: + /* get the key, check for weak keys and repeat if found */ + do { + crv = NSC_GenerateRandom(0, buf, key_length); + } while (crv == CKR_OK && checkWeak && sftk_IsWeakKey(buf, key_type)); + break; + case nsc_param: + /* generate parameters */ + *buf = 0; + crv = nsc_parameter_gen(key_type, key); + break; + case nsc_jpake: + crv = jpake_Round1(hashType, + (CK_NSS_JPAKERound1Params *)pMechanism->pParameter, + key); + break; } - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } /* Add the class, key_type, and value */ - crv = sftk_AddAttributeType(key,CKA_CLASS,&objclass,sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } - crv = sftk_AddAttributeType(key,CKA_KEY_TYPE,&key_type,sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } + crv = sftk_AddAttributeType(key, CKA_CLASS, &objclass, sizeof(CK_OBJECT_CLASS)); + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } + crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &key_type, sizeof(CK_KEY_TYPE)); + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } if (key_length != 0) { - crv = sftk_AddAttributeType(key,CKA_VALUE,buf,key_length); - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } + crv = sftk_AddAttributeType(key, CKA_VALUE, buf, key_length); + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } } /* get the session */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { - sftk_FreeObject(key); + sftk_FreeObject(key); return CKR_SESSION_HANDLE_INVALID; } /* * handle the base object stuff */ - crv = sftk_handleObject(key,session); + crv = sftk_handleObject(key, session); sftk_FreeSession(session); - if (sftk_isTrue(key,CKA_SENSITIVE)) { - sftk_forceAttribute(key,CKA_ALWAYS_SENSITIVE,&cktrue,sizeof(CK_BBOOL)); + if (crv == CKR_OK && sftk_isTrue(key, CKA_SENSITIVE)) { + crv = sftk_forceAttribute(key, CKA_ALWAYS_SENSITIVE, &cktrue, sizeof(CK_BBOOL)); } - if (!sftk_isTrue(key,CKA_EXTRACTABLE)) { - sftk_forceAttribute(key,CKA_NEVER_EXTRACTABLE,&cktrue,sizeof(CK_BBOOL)); + if (crv == CKR_OK && !sftk_isTrue(key, CKA_EXTRACTABLE)) { + crv = sftk_forceAttribute(key, CKA_NEVER_EXTRACTABLE, &cktrue, sizeof(CK_BBOOL)); + } + if (crv == CKR_OK) { + *phKey = key->handle; } - - *phKey = key->handle; sftk_FreeObject(key); return crv; } -#define PAIRWISE_DIGEST_LENGTH SHA1_LENGTH /* 160-bits */ -#define PAIRWISE_MESSAGE_LENGTH 20 /* 160-bits */ +#define PAIRWISE_DIGEST_LENGTH SHA1_LENGTH /* 160-bits */ +#define PAIRWISE_MESSAGE_LENGTH 20 /* 160-bits */ /* * FIPS 140-2 pairwise consistency check utilized to validate key pair. @@ -4067,7 +4366,7 @@ jpake1: */ static CK_RV sftk_PairwiseConsistencyCheck(CK_SESSION_HANDLE hSession, - SFTKObject *publicKey, SFTKObject *privateKey, CK_KEY_TYPE keyType) + SFTKObject *publicKey, SFTKObject *privateKey, CK_KEY_TYPE keyType) { /* * Key type Mechanism type @@ -4082,7 +4381,7 @@ sftk_PairwiseConsistencyCheck(CK_SESSION_HANDLE hSession, * * None of these mechanisms has a parameter. */ - CK_MECHANISM mech = {0, NULL, 0}; + CK_MECHANISM mech = { 0, NULL, 0 }; CK_ULONG modulusLen = 0; CK_ULONG subPrimeLen = 0; @@ -4103,146 +4402,145 @@ sftk_PairwiseConsistencyCheck(CK_SESSION_HANDLE hSession, /* Variables used for Signature/Verification functions. */ /* Must be at least 256 bits for DSA2 digest */ - unsigned char *known_digest = (unsigned char *) - "Mozilla Rules the World through NSS!"; + unsigned char *known_digest = (unsigned char *)"Mozilla Rules the World through NSS!"; unsigned char *signature; CK_ULONG signature_length; if (keyType == CKK_RSA) { - SFTKAttribute *attribute; - - /* Get modulus length of private key. */ - attribute = sftk_FindAttribute(privateKey, CKA_MODULUS); - if (attribute == NULL) { - return CKR_DEVICE_ERROR; - } - modulusLen = attribute->attrib.ulValueLen; - if (*(unsigned char *)attribute->attrib.pValue == 0) { - modulusLen--; - } - sftk_FreeAttribute(attribute); + SFTKAttribute *attribute; + + /* Get modulus length of private key. */ + attribute = sftk_FindAttribute(privateKey, CKA_MODULUS); + if (attribute == NULL) { + return CKR_DEVICE_ERROR; + } + modulusLen = attribute->attrib.ulValueLen; + if (*(unsigned char *)attribute->attrib.pValue == 0) { + modulusLen--; + } + sftk_FreeAttribute(attribute); } else if (keyType == CKK_DSA) { - SFTKAttribute *attribute; + SFTKAttribute *attribute; - /* Get subprime length of private key. */ - attribute = sftk_FindAttribute(privateKey, CKA_SUBPRIME); - if (attribute == NULL) { - return CKR_DEVICE_ERROR; - } - subPrimeLen = attribute->attrib.ulValueLen; - if (subPrimeLen > 1 && *(unsigned char *)attribute->attrib.pValue == 0) { - subPrimeLen--; - } - sftk_FreeAttribute(attribute); + /* Get subprime length of private key. */ + attribute = sftk_FindAttribute(privateKey, CKA_SUBPRIME); + if (attribute == NULL) { + return CKR_DEVICE_ERROR; + } + subPrimeLen = attribute->attrib.ulValueLen; + if (subPrimeLen > 1 && *(unsigned char *)attribute->attrib.pValue == 0) { + subPrimeLen--; + } + sftk_FreeAttribute(attribute); } /**************************************************/ /* Pairwise Consistency Check of Encrypt/Decrypt. */ /**************************************************/ - isEncryptable = sftk_isTrue(privateKey, CKA_DECRYPT); + isEncryptable = sftk_isTrue(privateKey, CKA_DECRYPT); /* * If the decryption attribute is set, attempt to encrypt * with the public key and decrypt with the private key. */ if (isEncryptable) { - if (keyType != CKK_RSA) { - return CKR_DEVICE_ERROR; - } - bytes_encrypted = modulusLen; - mech.mechanism = CKM_RSA_PKCS; - - /* Allocate space for ciphertext. */ - ciphertext = (unsigned char *) PORT_ZAlloc(bytes_encrypted); - if (ciphertext == NULL) { - return CKR_HOST_MEMORY; - } - - /* Prepare for encryption using the public key. */ - crv = NSC_EncryptInit(hSession, &mech, publicKey->handle); - if (crv != CKR_OK) { - PORT_Free(ciphertext); - return crv; - } - - /* Encrypt using the public key. */ - crv = NSC_Encrypt(hSession, - known_message, - PAIRWISE_MESSAGE_LENGTH, - ciphertext, - &bytes_encrypted); - if (crv != CKR_OK) { - PORT_Free(ciphertext); - return crv; - } - - /* Always use the smaller of these two values . . . */ - bytes_compared = PR_MIN(bytes_encrypted, PAIRWISE_MESSAGE_LENGTH); - - /* - * If there was a failure, the plaintext - * goes at the end, therefore . . . - */ - text_compared = ciphertext + bytes_encrypted - bytes_compared; - - /* - * Check to ensure that ciphertext does - * NOT EQUAL known input message text - * per FIPS PUB 140-2 directive. - */ - if (PORT_Memcmp(text_compared, known_message, - bytes_compared) == 0) { - /* Set error to Invalid PRIVATE Key. */ - PORT_SetError(SEC_ERROR_INVALID_KEY); - PORT_Free(ciphertext); - return CKR_GENERAL_ERROR; - } - - /* Prepare for decryption using the private key. */ - crv = NSC_DecryptInit(hSession, &mech, privateKey->handle); - if (crv != CKR_OK) { - PORT_Free(ciphertext); - return crv; - } - - memset(plaintext, 0, PAIRWISE_MESSAGE_LENGTH); - - /* - * Initialize bytes decrypted to be the - * expected PAIRWISE_MESSAGE_LENGTH. - */ - bytes_decrypted = PAIRWISE_MESSAGE_LENGTH; - - /* - * Decrypt using the private key. - * NOTE: No need to reset the - * value of bytes_encrypted. - */ - crv = NSC_Decrypt(hSession, - ciphertext, - bytes_encrypted, - plaintext, - &bytes_decrypted); - - /* Finished with ciphertext; free it. */ - PORT_Free(ciphertext); - - if (crv != CKR_OK) { - return crv; - } - - /* - * Check to ensure that the output plaintext - * does EQUAL known input message text. - */ - if ((bytes_decrypted != PAIRWISE_MESSAGE_LENGTH) || - (PORT_Memcmp(plaintext, known_message, - PAIRWISE_MESSAGE_LENGTH) != 0)) { - /* Set error to Bad PUBLIC Key. */ - PORT_SetError(SEC_ERROR_BAD_KEY); - return CKR_GENERAL_ERROR; - } + if (keyType != CKK_RSA) { + return CKR_DEVICE_ERROR; + } + bytes_encrypted = modulusLen; + mech.mechanism = CKM_RSA_PKCS; + + /* Allocate space for ciphertext. */ + ciphertext = (unsigned char *)PORT_ZAlloc(bytes_encrypted); + if (ciphertext == NULL) { + return CKR_HOST_MEMORY; + } + + /* Prepare for encryption using the public key. */ + crv = NSC_EncryptInit(hSession, &mech, publicKey->handle); + if (crv != CKR_OK) { + PORT_Free(ciphertext); + return crv; + } + + /* Encrypt using the public key. */ + crv = NSC_Encrypt(hSession, + known_message, + PAIRWISE_MESSAGE_LENGTH, + ciphertext, + &bytes_encrypted); + if (crv != CKR_OK) { + PORT_Free(ciphertext); + return crv; + } + + /* Always use the smaller of these two values . . . */ + bytes_compared = PR_MIN(bytes_encrypted, PAIRWISE_MESSAGE_LENGTH); + + /* + * If there was a failure, the plaintext + * goes at the end, therefore . . . + */ + text_compared = ciphertext + bytes_encrypted - bytes_compared; + + /* + * Check to ensure that ciphertext does + * NOT EQUAL known input message text + * per FIPS PUB 140-2 directive. + */ + if (PORT_Memcmp(text_compared, known_message, + bytes_compared) == 0) { + /* Set error to Invalid PRIVATE Key. */ + PORT_SetError(SEC_ERROR_INVALID_KEY); + PORT_Free(ciphertext); + return CKR_GENERAL_ERROR; + } + + /* Prepare for decryption using the private key. */ + crv = NSC_DecryptInit(hSession, &mech, privateKey->handle); + if (crv != CKR_OK) { + PORT_Free(ciphertext); + return crv; + } + + memset(plaintext, 0, PAIRWISE_MESSAGE_LENGTH); + + /* + * Initialize bytes decrypted to be the + * expected PAIRWISE_MESSAGE_LENGTH. + */ + bytes_decrypted = PAIRWISE_MESSAGE_LENGTH; + + /* + * Decrypt using the private key. + * NOTE: No need to reset the + * value of bytes_encrypted. + */ + crv = NSC_Decrypt(hSession, + ciphertext, + bytes_encrypted, + plaintext, + &bytes_decrypted); + + /* Finished with ciphertext; free it. */ + PORT_Free(ciphertext); + + if (crv != CKR_OK) { + return crv; + } + + /* + * Check to ensure that the output plaintext + * does EQUAL known input message text. + */ + if ((bytes_decrypted != PAIRWISE_MESSAGE_LENGTH) || + (PORT_Memcmp(plaintext, known_message, + PAIRWISE_MESSAGE_LENGTH) != 0)) { + /* Set error to Bad PUBLIC Key. */ + PORT_SetError(SEC_ERROR_BAD_KEY); + return CKR_GENERAL_ERROR; + } } /**********************************************/ @@ -4250,75 +4548,83 @@ sftk_PairwiseConsistencyCheck(CK_SESSION_HANDLE hSession, /**********************************************/ canSignVerify = sftk_isTrue(privateKey, CKA_SIGN); - + /* Unfortunately CKA_SIGN is always true in lg dbs. We have to check the + * actual curve to determine if we can do sign/verify. */ + if (canSignVerify && keyType == CKK_EC) { + NSSLOWKEYPrivateKey *privKey = sftk_GetPrivKey(privateKey, CKK_EC, &crv); + if (privKey && privKey->u.ec.ecParams.name == ECCurve25519) { + canSignVerify = PR_FALSE; + } + } + if (canSignVerify) { - /* Determine length of signature. */ - switch (keyType) { - case CKK_RSA: - signature_length = modulusLen; - mech.mechanism = CKM_RSA_PKCS; - break; - case CKK_DSA: - signature_length = DSA_MAX_SIGNATURE_LEN; - pairwise_digest_length = subPrimeLen; - mech.mechanism = CKM_DSA; - break; + /* Determine length of signature. */ + switch (keyType) { + case CKK_RSA: + signature_length = modulusLen; + mech.mechanism = CKM_RSA_PKCS; + break; + case CKK_DSA: + signature_length = DSA_MAX_SIGNATURE_LEN; + pairwise_digest_length = subPrimeLen; + mech.mechanism = CKM_DSA; + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - signature_length = MAX_ECKEY_LEN * 2; - mech.mechanism = CKM_ECDSA; - break; + case CKK_EC: + signature_length = MAX_ECKEY_LEN * 2; + mech.mechanism = CKM_ECDSA; + break; #endif - default: - return CKR_DEVICE_ERROR; - } - - /* Allocate space for signature data. */ - signature = (unsigned char *) PORT_ZAlloc(signature_length); - if (signature == NULL) { - return CKR_HOST_MEMORY; - } - - /* Sign the known hash using the private key. */ - crv = NSC_SignInit(hSession, &mech, privateKey->handle); - if (crv != CKR_OK) { - PORT_Free(signature); - return crv; - } - - crv = NSC_Sign(hSession, - known_digest, - pairwise_digest_length, - signature, - &signature_length); - if (crv != CKR_OK) { - PORT_Free(signature); - return crv; - } - - /* Verify the known hash using the public key. */ - crv = NSC_VerifyInit(hSession, &mech, publicKey->handle); - if (crv != CKR_OK) { - PORT_Free(signature); - return crv; - } - - crv = NSC_Verify(hSession, - known_digest, - pairwise_digest_length, - signature, - signature_length); - - /* Free signature data. */ - PORT_Free(signature); - - if ((crv == CKR_SIGNATURE_LEN_RANGE) || - (crv == CKR_SIGNATURE_INVALID)) { - return CKR_GENERAL_ERROR; - } - if (crv != CKR_OK) { - return crv; - } + default: + return CKR_DEVICE_ERROR; + } + + /* Allocate space for signature data. */ + signature = (unsigned char *)PORT_ZAlloc(signature_length); + if (signature == NULL) { + return CKR_HOST_MEMORY; + } + + /* Sign the known hash using the private key. */ + crv = NSC_SignInit(hSession, &mech, privateKey->handle); + if (crv != CKR_OK) { + PORT_Free(signature); + return crv; + } + + crv = NSC_Sign(hSession, + known_digest, + pairwise_digest_length, + signature, + &signature_length); + if (crv != CKR_OK) { + PORT_Free(signature); + return crv; + } + + /* Verify the known hash using the public key. */ + crv = NSC_VerifyInit(hSession, &mech, publicKey->handle); + if (crv != CKR_OK) { + PORT_Free(signature); + return crv; + } + + crv = NSC_Verify(hSession, + known_digest, + pairwise_digest_length, + signature, + signature_length); + + /* Free signature data. */ + PORT_Free(signature); + + if ((crv == CKR_SIGNATURE_LEN_RANGE) || + (crv == CKR_SIGNATURE_INVALID)) { + return CKR_GENERAL_ERROR; + } + if (crv != CKR_OK) { + return crv; + } } /**********************************************/ @@ -4326,70 +4632,70 @@ sftk_PairwiseConsistencyCheck(CK_SESSION_HANDLE hSession, /**********************************************/ isDerivable = sftk_isTrue(privateKey, CKA_DERIVE); - - if (isDerivable) { - /* - * We are not doing consistency check for Diffie-Hellman Key - - * otherwise it would be here - * This is also true for Elliptic Curve Diffie-Hellman keys - * NOTE: EC keys are currently subjected to pairwise - * consistency check for signing/verification. - */ - /* - * FIPS 140-2 had the following pairwise consistency test for - * public and private keys used for key agreement: - * If the keys are used to perform key agreement, then the - * cryptographic module shall create a second, compatible - * key pair. The cryptographic module shall perform both - * sides of the key agreement algorithm and shall compare - * the resulting shared values. If the shared values are - * not equal, the test shall fail. - * This test was removed in Change Notice 3. - */ + if (isDerivable) { + /* + * We are not doing consistency check for Diffie-Hellman Key - + * otherwise it would be here + * This is also true for Elliptic Curve Diffie-Hellman keys + * NOTE: EC keys are currently subjected to pairwise + * consistency check for signing/verification. + */ + /* + * FIPS 140-2 had the following pairwise consistency test for + * public and private keys used for key agreement: + * If the keys are used to perform key agreement, then the + * cryptographic module shall create a second, compatible + * key pair. The cryptographic module shall perform both + * sides of the key agreement algorithm and shall compare + * the resulting shared values. If the shared values are + * not equal, the test shall fail. + * This test was removed in Change Notice 3. + */ } return CKR_OK; } -/* NSC_GenerateKeyPair generates a public-key/private-key pair, +/* NSC_GenerateKeyPair generates a public-key/private-key pair, * creating new key objects. */ -CK_RV NSC_GenerateKeyPair (CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey) +CK_RV +NSC_GenerateKeyPair(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, + CK_OBJECT_HANDLE_PTR phPrivateKey) { - SFTKObject * publicKey,*privateKey; - SFTKSession * session; - CK_KEY_TYPE key_type; - CK_RV crv = CKR_OK; - CK_BBOOL cktrue = CK_TRUE; - SECStatus rv; - CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY; - CK_OBJECT_CLASS privClass = CKO_PRIVATE_KEY; - int i; - SFTKSlot * slot = sftk_SlotFromSessionHandle(hSession); + SFTKObject *publicKey, *privateKey; + SFTKSession *session; + CK_KEY_TYPE key_type; + CK_RV crv = CKR_OK; + CK_BBOOL cktrue = CK_TRUE; + SECStatus rv; + CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY; + CK_OBJECT_CLASS privClass = CKO_PRIVATE_KEY; + int i; + SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); unsigned int bitSize; /* RSA */ - int public_modulus_bits = 0; - SECItem pubExp; - RSAPrivateKey * rsaPriv; + int public_modulus_bits = 0; + SECItem pubExp; + RSAPrivateKey *rsaPriv; /* DSA */ - PQGParams pqgParam; - DHParams dhParam; - DSAPrivateKey * dsaPriv; + PQGParams pqgParam; + DHParams dhParam; + DSAPrivateKey *dsaPriv; /* Diffie Hellman */ - DHPrivateKey * dhPriv; + DHPrivateKey *dhPriv; #ifndef NSS_DISABLE_ECC /* Elliptic Curve Cryptography */ - SECItem ecEncodedParams; /* DER Encoded parameters */ - ECPrivateKey * ecPriv; - ECParams * ecParams; + SECItem ecEncodedParams; /* DER Encoded parameters */ + ECPrivateKey *ecPriv; + ECParams *ecParams; #endif /* NSS_DISABLE_ECC */ CHECK_FORK(); @@ -4402,435 +4708,462 @@ CK_RV NSC_GenerateKeyPair (CK_SESSION_HANDLE hSession, */ publicKey = sftk_NewObject(slot); /* fill in the handle later */ if (publicKey == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* * load the template values into the publicKey */ - for (i=0; i < (int) ulPublicKeyAttributeCount; i++) { - if (pPublicKeyTemplate[i].type == CKA_MODULUS_BITS) { - public_modulus_bits = *(CK_ULONG *)pPublicKeyTemplate[i].pValue; - continue; - } + for (i = 0; i < (int)ulPublicKeyAttributeCount; i++) { + if (pPublicKeyTemplate[i].type == CKA_MODULUS_BITS) { + public_modulus_bits = *(CK_ULONG *)pPublicKeyTemplate[i].pValue; + continue; + } - crv = sftk_AddAttributeType(publicKey, - sftk_attr_expand(&pPublicKeyTemplate[i])); - if (crv != CKR_OK) break; + crv = sftk_AddAttributeType(publicKey, + sftk_attr_expand(&pPublicKeyTemplate[i])); + if (crv != CKR_OK) + break; } if (crv != CKR_OK) { - sftk_FreeObject(publicKey); - return CKR_HOST_MEMORY; + sftk_FreeObject(publicKey); + return CKR_HOST_MEMORY; } privateKey = sftk_NewObject(slot); /* fill in the handle later */ if (privateKey == NULL) { - sftk_FreeObject(publicKey); - return CKR_HOST_MEMORY; + sftk_FreeObject(publicKey); + return CKR_HOST_MEMORY; } /* * now load the private key template */ - for (i=0; i < (int) ulPrivateKeyAttributeCount; i++) { - if (pPrivateKeyTemplate[i].type == CKA_VALUE_BITS) { - continue; - } + for (i = 0; i < (int)ulPrivateKeyAttributeCount; i++) { + if (pPrivateKeyTemplate[i].type == CKA_VALUE_BITS) { + continue; + } - crv = sftk_AddAttributeType(privateKey, - sftk_attr_expand(&pPrivateKeyTemplate[i])); - if (crv != CKR_OK) break; + crv = sftk_AddAttributeType(privateKey, + sftk_attr_expand(&pPrivateKeyTemplate[i])); + if (crv != CKR_OK) + break; } if (crv != CKR_OK) { - sftk_FreeObject(publicKey); - sftk_FreeObject(privateKey); - return CKR_HOST_MEMORY; + sftk_FreeObject(publicKey); + sftk_FreeObject(privateKey); + return CKR_HOST_MEMORY; } - sftk_DeleteAttributeType(privateKey,CKA_CLASS); - sftk_DeleteAttributeType(privateKey,CKA_KEY_TYPE); - sftk_DeleteAttributeType(privateKey,CKA_VALUE); - sftk_DeleteAttributeType(publicKey,CKA_CLASS); - sftk_DeleteAttributeType(publicKey,CKA_KEY_TYPE); - sftk_DeleteAttributeType(publicKey,CKA_VALUE); + sftk_DeleteAttributeType(privateKey, CKA_CLASS); + sftk_DeleteAttributeType(privateKey, CKA_KEY_TYPE); + sftk_DeleteAttributeType(privateKey, CKA_VALUE); + sftk_DeleteAttributeType(publicKey, CKA_CLASS); + sftk_DeleteAttributeType(publicKey, CKA_KEY_TYPE); + sftk_DeleteAttributeType(publicKey, CKA_VALUE); /* Now Set up the parameters to generate the key (based on mechanism) */ switch (pMechanism->mechanism) { - case CKM_RSA_PKCS_KEY_PAIR_GEN: - /* format the keys */ - sftk_DeleteAttributeType(publicKey,CKA_MODULUS); - sftk_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - sftk_DeleteAttributeType(privateKey,CKA_MODULUS); - sftk_DeleteAttributeType(privateKey,CKA_PRIVATE_EXPONENT); - sftk_DeleteAttributeType(privateKey,CKA_PUBLIC_EXPONENT); - sftk_DeleteAttributeType(privateKey,CKA_PRIME_1); - sftk_DeleteAttributeType(privateKey,CKA_PRIME_2); - sftk_DeleteAttributeType(privateKey,CKA_EXPONENT_1); - sftk_DeleteAttributeType(privateKey,CKA_EXPONENT_2); - sftk_DeleteAttributeType(privateKey,CKA_COEFFICIENT); - key_type = CKK_RSA; - if (public_modulus_bits == 0) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - if (public_modulus_bits < RSA_MIN_MODULUS_BITS) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - if (public_modulus_bits % 2 != 0) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - - /* extract the exponent */ - crv=sftk_Attribute2SSecItem(NULL,&pubExp,publicKey,CKA_PUBLIC_EXPONENT); - if (crv != CKR_OK) break; - bitSize = sftk_GetLengthInBits(pubExp.data, pubExp.len); - if (bitSize < 2) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - break; - } - crv = sftk_AddAttributeType(privateKey,CKA_PUBLIC_EXPONENT, - sftk_item_expand(&pubExp)); - if (crv != CKR_OK) { - PORT_Free(pubExp.data); - break; - } - - rsaPriv = RSA_NewKey(public_modulus_bits, &pubExp); - PORT_Free(pubExp.data); - if (rsaPriv == NULL) { - if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; - } - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - /* now fill in the RSA dependent paramenters in the public key */ - crv = sftk_AddAttributeType(publicKey,CKA_MODULUS, - sftk_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - /* now fill in the RSA dependent paramenters in the private key */ - crv = sftk_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - sftk_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_MODULUS, - sftk_item_expand(&rsaPriv->modulus)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_PRIVATE_EXPONENT, - sftk_item_expand(&rsaPriv->privateExponent)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_PRIME_1, - sftk_item_expand(&rsaPriv->prime1)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_PRIME_2, - sftk_item_expand(&rsaPriv->prime2)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_EXPONENT_1, - sftk_item_expand(&rsaPriv->exponent1)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_EXPONENT_2, - sftk_item_expand(&rsaPriv->exponent2)); - if (crv != CKR_OK) goto kpg_done; - crv = sftk_AddAttributeType(privateKey,CKA_COEFFICIENT, - sftk_item_expand(&rsaPriv->coefficient)); -kpg_done: - /* Should zeroize the contents first, since this func doesn't. */ - PORT_FreeArena(rsaPriv->arena, PR_TRUE); - break; - case CKM_DSA_KEY_PAIR_GEN: - sftk_DeleteAttributeType(publicKey,CKA_VALUE); - sftk_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - sftk_DeleteAttributeType(privateKey,CKA_PRIME); - sftk_DeleteAttributeType(privateKey,CKA_SUBPRIME); - sftk_DeleteAttributeType(privateKey,CKA_BASE); - key_type = CKK_DSA; - - /* extract the necessary parameters and copy them to the private key */ - crv=sftk_Attribute2SSecItem(NULL,&pqgParam.prime,publicKey,CKA_PRIME); - if (crv != CKR_OK) break; - crv=sftk_Attribute2SSecItem(NULL,&pqgParam.subPrime,publicKey, - CKA_SUBPRIME); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - break; - } - crv=sftk_Attribute2SSecItem(NULL,&pqgParam.base,publicKey,CKA_BASE); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - break; - } - crv = sftk_AddAttributeType(privateKey,CKA_PRIME, - sftk_item_expand(&pqgParam.prime)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - crv = sftk_AddAttributeType(privateKey,CKA_SUBPRIME, - sftk_item_expand(&pqgParam.subPrime)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - crv = sftk_AddAttributeType(privateKey,CKA_BASE, - sftk_item_expand(&pqgParam.base)); - if (crv != CKR_OK) { - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - - /* - * these are checked by DSA_NewKey - */ - bitSize = sftk_GetLengthInBits(pqgParam.subPrime.data, - pqgParam.subPrime.len); - if ((bitSize < DSA_MIN_Q_BITS) || (bitSize > DSA_MAX_Q_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - bitSize = sftk_GetLengthInBits(pqgParam.prime.data,pqgParam.prime.len); - if ((bitSize < DSA_MIN_P_BITS) || (bitSize > DSA_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - bitSize = sftk_GetLengthInBits(pqgParam.base.data,pqgParam.base.len); - if ((bitSize < 2) || (bitSize > DSA_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - break; - } - - /* Generate the key */ - rv = DSA_NewKey(&pqgParam, &dsaPriv); - - PORT_Free(pqgParam.prime.data); - PORT_Free(pqgParam.subPrime.data); - PORT_Free(pqgParam.base.data); - - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; - } - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - - /* store the generated key into the attributes */ - crv = sftk_AddAttributeType(publicKey,CKA_VALUE, - sftk_item_expand(&dsaPriv->publicValue)); - if (crv != CKR_OK) goto dsagn_done; - - /* now fill in the RSA dependent paramenters in the private key */ - crv = sftk_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - sftk_item_expand(&dsaPriv->publicValue)); - if (crv != CKR_OK) goto dsagn_done; - crv = sftk_AddAttributeType(privateKey,CKA_VALUE, - sftk_item_expand(&dsaPriv->privateValue)); - -dsagn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(dsaPriv->params.arena, PR_TRUE); - break; - - case CKM_DH_PKCS_KEY_PAIR_GEN: - sftk_DeleteAttributeType(privateKey,CKA_PRIME); - sftk_DeleteAttributeType(privateKey,CKA_BASE); - sftk_DeleteAttributeType(privateKey,CKA_VALUE); - sftk_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - key_type = CKK_DH; - - /* extract the necessary parameters and copy them to private keys */ - crv = sftk_Attribute2SSecItem(NULL, &dhParam.prime, publicKey, - CKA_PRIME); - if (crv != CKR_OK) break; - crv = sftk_Attribute2SSecItem(NULL, &dhParam.base, publicKey, CKA_BASE); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - break; - } - crv = sftk_AddAttributeType(privateKey, CKA_PRIME, - sftk_item_expand(&dhParam.prime)); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - crv = sftk_AddAttributeType(privateKey, CKA_BASE, - sftk_item_expand(&dhParam.base)); - if (crv != CKR_OK) { - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - bitSize = sftk_GetLengthInBits(dhParam.prime.data,dhParam.prime.len); - if ((bitSize < DH_MIN_P_BITS) || (bitSize > DH_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - bitSize = sftk_GetLengthInBits(dhParam.base.data,dhParam.base.len); - if ((bitSize < 1) || (bitSize > DH_MAX_P_BITS)) { - crv = CKR_TEMPLATE_INCOMPLETE; - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - break; - } - - rv = DH_NewKey(&dhParam, &dhPriv); - PORT_Free(dhParam.prime.data); - PORT_Free(dhParam.base.data); - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; - } - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - - crv=sftk_AddAttributeType(publicKey, CKA_VALUE, - sftk_item_expand(&dhPriv->publicValue)); - if (crv != CKR_OK) goto dhgn_done; - - crv = sftk_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - sftk_item_expand(&dhPriv->publicValue)); - if (crv != CKR_OK) goto dhgn_done; - - crv=sftk_AddAttributeType(privateKey, CKA_VALUE, - sftk_item_expand(&dhPriv->privateValue)); - -dhgn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(dhPriv->arena, PR_TRUE); - break; + case CKM_RSA_PKCS_KEY_PAIR_GEN: + /* format the keys */ + sftk_DeleteAttributeType(publicKey, CKA_MODULUS); + sftk_DeleteAttributeType(privateKey, CKA_NETSCAPE_DB); + sftk_DeleteAttributeType(privateKey, CKA_MODULUS); + sftk_DeleteAttributeType(privateKey, CKA_PRIVATE_EXPONENT); + sftk_DeleteAttributeType(privateKey, CKA_PUBLIC_EXPONENT); + sftk_DeleteAttributeType(privateKey, CKA_PRIME_1); + sftk_DeleteAttributeType(privateKey, CKA_PRIME_2); + sftk_DeleteAttributeType(privateKey, CKA_EXPONENT_1); + sftk_DeleteAttributeType(privateKey, CKA_EXPONENT_2); + sftk_DeleteAttributeType(privateKey, CKA_COEFFICIENT); + key_type = CKK_RSA; + if (public_modulus_bits == 0) { + crv = CKR_TEMPLATE_INCOMPLETE; + break; + } + if (public_modulus_bits < RSA_MIN_MODULUS_BITS) { + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; + } + if (public_modulus_bits % 2 != 0) { + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; + } + + /* extract the exponent */ + crv = sftk_Attribute2SSecItem(NULL, &pubExp, publicKey, CKA_PUBLIC_EXPONENT); + if (crv != CKR_OK) + break; + bitSize = sftk_GetLengthInBits(pubExp.data, pubExp.len); + if (bitSize < 2) { + crv = CKR_ATTRIBUTE_VALUE_INVALID; + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_PUBLIC_EXPONENT, + sftk_item_expand(&pubExp)); + if (crv != CKR_OK) { + PORT_Free(pubExp.data); + break; + } + + rsaPriv = RSA_NewKey(public_modulus_bits, &pubExp); + PORT_Free(pubExp.data); + if (rsaPriv == NULL) { + if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + sftk_fatalError = PR_TRUE; + } + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + /* now fill in the RSA dependent paramenters in the public key */ + crv = sftk_AddAttributeType(publicKey, CKA_MODULUS, + sftk_item_expand(&rsaPriv->modulus)); + if (crv != CKR_OK) + goto kpg_done; + /* now fill in the RSA dependent paramenters in the private key */ + crv = sftk_AddAttributeType(privateKey, CKA_NETSCAPE_DB, + sftk_item_expand(&rsaPriv->modulus)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_MODULUS, + sftk_item_expand(&rsaPriv->modulus)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_PRIVATE_EXPONENT, + sftk_item_expand(&rsaPriv->privateExponent)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_PRIME_1, + sftk_item_expand(&rsaPriv->prime1)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_PRIME_2, + sftk_item_expand(&rsaPriv->prime2)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_EXPONENT_1, + sftk_item_expand(&rsaPriv->exponent1)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_EXPONENT_2, + sftk_item_expand(&rsaPriv->exponent2)); + if (crv != CKR_OK) + goto kpg_done; + crv = sftk_AddAttributeType(privateKey, CKA_COEFFICIENT, + sftk_item_expand(&rsaPriv->coefficient)); + kpg_done: + /* Should zeroize the contents first, since this func doesn't. */ + PORT_FreeArena(rsaPriv->arena, PR_TRUE); + break; + case CKM_DSA_KEY_PAIR_GEN: + sftk_DeleteAttributeType(publicKey, CKA_VALUE); + sftk_DeleteAttributeType(privateKey, CKA_NETSCAPE_DB); + sftk_DeleteAttributeType(privateKey, CKA_PRIME); + sftk_DeleteAttributeType(privateKey, CKA_SUBPRIME); + sftk_DeleteAttributeType(privateKey, CKA_BASE); + key_type = CKK_DSA; + + /* extract the necessary parameters and copy them to the private key */ + crv = sftk_Attribute2SSecItem(NULL, &pqgParam.prime, publicKey, CKA_PRIME); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(NULL, &pqgParam.subPrime, publicKey, + CKA_SUBPRIME); + if (crv != CKR_OK) { + PORT_Free(pqgParam.prime.data); + break; + } + crv = sftk_Attribute2SSecItem(NULL, &pqgParam.base, publicKey, CKA_BASE); + if (crv != CKR_OK) { + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_PRIME, + sftk_item_expand(&pqgParam.prime)); + if (crv != CKR_OK) { + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_SUBPRIME, + sftk_item_expand(&pqgParam.subPrime)); + if (crv != CKR_OK) { + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_BASE, + sftk_item_expand(&pqgParam.base)); + if (crv != CKR_OK) { + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + + /* + * these are checked by DSA_NewKey + */ + bitSize = sftk_GetLengthInBits(pqgParam.subPrime.data, + pqgParam.subPrime.len); + if ((bitSize < DSA_MIN_Q_BITS) || (bitSize > DSA_MAX_Q_BITS)) { + crv = CKR_TEMPLATE_INCOMPLETE; + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + bitSize = sftk_GetLengthInBits(pqgParam.prime.data, pqgParam.prime.len); + if ((bitSize < DSA_MIN_P_BITS) || (bitSize > DSA_MAX_P_BITS)) { + crv = CKR_TEMPLATE_INCOMPLETE; + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + bitSize = sftk_GetLengthInBits(pqgParam.base.data, pqgParam.base.len); + if ((bitSize < 2) || (bitSize > DSA_MAX_P_BITS)) { + crv = CKR_TEMPLATE_INCOMPLETE; + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + break; + } + + /* Generate the key */ + rv = DSA_NewKey(&pqgParam, &dsaPriv); + + PORT_Free(pqgParam.prime.data); + PORT_Free(pqgParam.subPrime.data); + PORT_Free(pqgParam.base.data); + + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + sftk_fatalError = PR_TRUE; + } + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + + /* store the generated key into the attributes */ + crv = sftk_AddAttributeType(publicKey, CKA_VALUE, + sftk_item_expand(&dsaPriv->publicValue)); + if (crv != CKR_OK) + goto dsagn_done; + + /* now fill in the RSA dependent paramenters in the private key */ + crv = sftk_AddAttributeType(privateKey, CKA_NETSCAPE_DB, + sftk_item_expand(&dsaPriv->publicValue)); + if (crv != CKR_OK) + goto dsagn_done; + crv = sftk_AddAttributeType(privateKey, CKA_VALUE, + sftk_item_expand(&dsaPriv->privateValue)); + + dsagn_done: + /* should zeroize, since this function doesn't. */ + PORT_FreeArena(dsaPriv->params.arena, PR_TRUE); + break; + + case CKM_DH_PKCS_KEY_PAIR_GEN: + sftk_DeleteAttributeType(privateKey, CKA_PRIME); + sftk_DeleteAttributeType(privateKey, CKA_BASE); + sftk_DeleteAttributeType(privateKey, CKA_VALUE); + sftk_DeleteAttributeType(privateKey, CKA_NETSCAPE_DB); + key_type = CKK_DH; + + /* extract the necessary parameters and copy them to private keys */ + crv = sftk_Attribute2SSecItem(NULL, &dhParam.prime, publicKey, + CKA_PRIME); + if (crv != CKR_OK) + break; + crv = sftk_Attribute2SSecItem(NULL, &dhParam.base, publicKey, CKA_BASE); + if (crv != CKR_OK) { + PORT_Free(dhParam.prime.data); + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_PRIME, + sftk_item_expand(&dhParam.prime)); + if (crv != CKR_OK) { + PORT_Free(dhParam.prime.data); + PORT_Free(dhParam.base.data); + break; + } + crv = sftk_AddAttributeType(privateKey, CKA_BASE, + sftk_item_expand(&dhParam.base)); + if (crv != CKR_OK) { + PORT_Free(dhParam.prime.data); + PORT_Free(dhParam.base.data); + break; + } + bitSize = sftk_GetLengthInBits(dhParam.prime.data, dhParam.prime.len); + if ((bitSize < DH_MIN_P_BITS) || (bitSize > DH_MAX_P_BITS)) { + crv = CKR_TEMPLATE_INCOMPLETE; + PORT_Free(dhParam.prime.data); + PORT_Free(dhParam.base.data); + break; + } + bitSize = sftk_GetLengthInBits(dhParam.base.data, dhParam.base.len); + if ((bitSize < 1) || (bitSize > DH_MAX_P_BITS)) { + crv = CKR_TEMPLATE_INCOMPLETE; + PORT_Free(dhParam.prime.data); + PORT_Free(dhParam.base.data); + break; + } + + rv = DH_NewKey(&dhParam, &dhPriv); + PORT_Free(dhParam.prime.data); + PORT_Free(dhParam.base.data); + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + sftk_fatalError = PR_TRUE; + } + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + + crv = sftk_AddAttributeType(publicKey, CKA_VALUE, + sftk_item_expand(&dhPriv->publicValue)); + if (crv != CKR_OK) + goto dhgn_done; + + crv = sftk_AddAttributeType(privateKey, CKA_NETSCAPE_DB, + sftk_item_expand(&dhPriv->publicValue)); + if (crv != CKR_OK) + goto dhgn_done; + + crv = sftk_AddAttributeType(privateKey, CKA_VALUE, + sftk_item_expand(&dhPriv->privateValue)); + + dhgn_done: + /* should zeroize, since this function doesn't. */ + PORT_FreeArena(dhPriv->arena, PR_TRUE); + break; #ifndef NSS_DISABLE_ECC - case CKM_EC_KEY_PAIR_GEN: - sftk_DeleteAttributeType(privateKey,CKA_EC_PARAMS); - sftk_DeleteAttributeType(privateKey,CKA_VALUE); - sftk_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB); - key_type = CKK_EC; - - /* extract the necessary parameters and copy them to private keys */ - crv = sftk_Attribute2SSecItem(NULL, &ecEncodedParams, publicKey, - CKA_EC_PARAMS); - if (crv != CKR_OK) break; - - crv = sftk_AddAttributeType(privateKey, CKA_EC_PARAMS, - sftk_item_expand(&ecEncodedParams)); - if (crv != CKR_OK) { - PORT_Free(ecEncodedParams.data); - break; - } - - /* Decode ec params before calling EC_NewKey */ - rv = EC_DecodeParams(&ecEncodedParams, &ecParams); - PORT_Free(ecEncodedParams.data); - if (rv != SECSuccess) { - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - rv = EC_NewKey(ecParams, &ecPriv); - PORT_FreeArena(ecParams->arena, PR_TRUE); - if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { - sftk_fatalError = PR_TRUE; - } - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - - if (getenv("NSS_USE_DECODED_CKA_EC_POINT")) { - crv = sftk_AddAttributeType(publicKey, CKA_EC_POINT, - sftk_item_expand(&ecPriv->publicValue)); - } else { - SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL, - &ecPriv->publicValue, - SEC_ASN1_GET(SEC_OctetStringTemplate)); - if (!pubValue) { - crv = CKR_ARGUMENTS_BAD; - goto ecgn_done; - } - crv = sftk_AddAttributeType(publicKey, CKA_EC_POINT, - sftk_item_expand(pubValue)); - SECITEM_FreeItem(pubValue, PR_TRUE); - } - if (crv != CKR_OK) goto ecgn_done; - - crv = sftk_AddAttributeType(privateKey, CKA_VALUE, - sftk_item_expand(&ecPriv->privateValue)); - if (crv != CKR_OK) goto ecgn_done; - - crv = sftk_AddAttributeType(privateKey,CKA_NETSCAPE_DB, - sftk_item_expand(&ecPriv->publicValue)); -ecgn_done: - /* should zeroize, since this function doesn't. */ - PORT_FreeArena(ecPriv->ecParams.arena, PR_TRUE); - break; + case CKM_EC_KEY_PAIR_GEN: + sftk_DeleteAttributeType(privateKey, CKA_EC_PARAMS); + sftk_DeleteAttributeType(privateKey, CKA_VALUE); + sftk_DeleteAttributeType(privateKey, CKA_NETSCAPE_DB); + key_type = CKK_EC; + + /* extract the necessary parameters and copy them to private keys */ + crv = sftk_Attribute2SSecItem(NULL, &ecEncodedParams, publicKey, + CKA_EC_PARAMS); + if (crv != CKR_OK) + break; + + crv = sftk_AddAttributeType(privateKey, CKA_EC_PARAMS, + sftk_item_expand(&ecEncodedParams)); + if (crv != CKR_OK) { + PORT_Free(ecEncodedParams.data); + break; + } + + /* Decode ec params before calling EC_NewKey */ + rv = EC_DecodeParams(&ecEncodedParams, &ecParams); + PORT_Free(ecEncodedParams.data); + if (rv != SECSuccess) { + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + rv = EC_NewKey(ecParams, &ecPriv); + if (rv != SECSuccess) { + if (PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) { + sftk_fatalError = PR_TRUE; + } + PORT_FreeArena(ecParams->arena, PR_TRUE); + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + + if (PR_GetEnvSecure("NSS_USE_DECODED_CKA_EC_POINT") || + ecParams->fieldID.type == ec_field_plain) { + PORT_FreeArena(ecParams->arena, PR_TRUE); + crv = sftk_AddAttributeType(publicKey, CKA_EC_POINT, + sftk_item_expand(&ecPriv->publicValue)); + } else { + PORT_FreeArena(ecParams->arena, PR_TRUE); + SECItem *pubValue = SEC_ASN1EncodeItem(NULL, NULL, + &ecPriv->publicValue, + SEC_ASN1_GET(SEC_OctetStringTemplate)); + if (!pubValue) { + crv = CKR_ARGUMENTS_BAD; + goto ecgn_done; + } + crv = sftk_AddAttributeType(publicKey, CKA_EC_POINT, + sftk_item_expand(pubValue)); + SECITEM_FreeItem(pubValue, PR_TRUE); + } + if (crv != CKR_OK) + goto ecgn_done; + + crv = sftk_AddAttributeType(privateKey, CKA_VALUE, + sftk_item_expand(&ecPriv->privateValue)); + if (crv != CKR_OK) + goto ecgn_done; + + crv = sftk_AddAttributeType(privateKey, CKA_NETSCAPE_DB, + sftk_item_expand(&ecPriv->publicValue)); + ecgn_done: + /* should zeroize, since this function doesn't. */ + PORT_FreeArena(ecPriv->ecParams.arena, PR_TRUE); + break; #endif /* NSS_DISABLE_ECC */ - default: - crv = CKR_MECHANISM_INVALID; + default: + crv = CKR_MECHANISM_INVALID; } if (crv != CKR_OK) { - sftk_FreeObject(privateKey); - sftk_FreeObject(publicKey); - return crv; + sftk_FreeObject(privateKey); + sftk_FreeObject(publicKey); + return crv; } - /* Add the class, key_type The loop lets us check errors blow out * on errors and clean up at the bottom */ session = NULL; /* make pedtantic happy... session cannot leave the*/ - /* loop below NULL unless an error is set... */ + /* loop below NULL unless an error is set... */ do { - crv = sftk_AddAttributeType(privateKey,CKA_CLASS,&privClass, - sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) break; - crv = sftk_AddAttributeType(publicKey,CKA_CLASS,&pubClass, - sizeof(CK_OBJECT_CLASS)); - if (crv != CKR_OK) break; - crv = sftk_AddAttributeType(privateKey,CKA_KEY_TYPE,&key_type, - sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) break; - crv = sftk_AddAttributeType(publicKey,CKA_KEY_TYPE,&key_type, - sizeof(CK_KEY_TYPE)); - if (crv != CKR_OK) break; + crv = sftk_AddAttributeType(privateKey, CKA_CLASS, &privClass, + sizeof(CK_OBJECT_CLASS)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(publicKey, CKA_CLASS, &pubClass, + sizeof(CK_OBJECT_CLASS)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(privateKey, CKA_KEY_TYPE, &key_type, + sizeof(CK_KEY_TYPE)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(publicKey, CKA_KEY_TYPE, &key_type, + sizeof(CK_KEY_TYPE)); + if (crv != CKR_OK) + break; session = sftk_SessionFromHandle(hSession); - if (session == NULL) crv = CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + crv = CKR_SESSION_HANDLE_INVALID; } while (0); if (crv != CKR_OK) { - sftk_FreeObject(privateKey); - sftk_FreeObject(publicKey); - return crv; + sftk_FreeObject(privateKey); + sftk_FreeObject(publicKey); + return crv; } /* * handle the base object cleanup for the public Key */ - crv = sftk_handleObject(privateKey,session); + crv = sftk_handleObject(privateKey, session); if (crv != CKR_OK) { sftk_FreeSession(session); - sftk_FreeObject(privateKey); - sftk_FreeObject(publicKey); - return crv; + sftk_FreeObject(privateKey); + sftk_FreeObject(publicKey); + return crv; } /* @@ -4838,50 +5171,55 @@ ecgn_done: * If we have any problems, we destroy the public Key we've * created and linked. */ - crv = sftk_handleObject(publicKey,session); + crv = sftk_handleObject(publicKey, session); sftk_FreeSession(session); if (crv != CKR_OK) { - sftk_FreeObject(publicKey); - NSC_DestroyObject(hSession,privateKey->handle); - sftk_FreeObject(privateKey); - return crv; + sftk_FreeObject(publicKey); + NSC_DestroyObject(hSession, privateKey->handle); + sftk_FreeObject(privateKey); + return crv; } - if (sftk_isTrue(privateKey,CKA_SENSITIVE)) { - sftk_forceAttribute(privateKey,CKA_ALWAYS_SENSITIVE, - &cktrue,sizeof(CK_BBOOL)); + if (sftk_isTrue(privateKey, CKA_SENSITIVE)) { + crv = sftk_forceAttribute(privateKey, CKA_ALWAYS_SENSITIVE, + &cktrue, sizeof(CK_BBOOL)); } - if (sftk_isTrue(publicKey,CKA_SENSITIVE)) { - sftk_forceAttribute(publicKey,CKA_ALWAYS_SENSITIVE, - &cktrue,sizeof(CK_BBOOL)); + if (crv == CKR_OK && sftk_isTrue(publicKey, CKA_SENSITIVE)) { + crv = sftk_forceAttribute(publicKey, CKA_ALWAYS_SENSITIVE, + &cktrue, sizeof(CK_BBOOL)); } - if (!sftk_isTrue(privateKey,CKA_EXTRACTABLE)) { - sftk_forceAttribute(privateKey,CKA_NEVER_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); + if (crv == CKR_OK && !sftk_isTrue(privateKey, CKA_EXTRACTABLE)) { + crv = sftk_forceAttribute(privateKey, CKA_NEVER_EXTRACTABLE, + &cktrue, sizeof(CK_BBOOL)); } - if (!sftk_isTrue(publicKey,CKA_EXTRACTABLE)) { - sftk_forceAttribute(publicKey,CKA_NEVER_EXTRACTABLE, - &cktrue,sizeof(CK_BBOOL)); + if (crv == CKR_OK && !sftk_isTrue(publicKey, CKA_EXTRACTABLE)) { + crv = sftk_forceAttribute(publicKey, CKA_NEVER_EXTRACTABLE, + &cktrue, sizeof(CK_BBOOL)); + } + + if (crv == CKR_OK) { + /* Perform FIPS 140-2 pairwise consistency check. */ + crv = sftk_PairwiseConsistencyCheck(hSession, + publicKey, privateKey, key_type); + if (crv != CKR_OK) { + if (sftk_audit_enabled) { + char msg[128]; + PR_snprintf(msg, sizeof msg, + "C_GenerateKeyPair(hSession=0x%08lX, " + "pMechanism->mechanism=0x%08lX)=0x%08lX " + "self-test: pair-wise consistency test failed", + (PRUint32)hSession, (PRUint32)pMechanism->mechanism, + (PRUint32)crv); + sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); + } + } } - /* Perform FIPS 140-2 pairwise consistency check. */ - crv = sftk_PairwiseConsistencyCheck(hSession, - publicKey, privateKey, key_type); if (crv != CKR_OK) { - NSC_DestroyObject(hSession,publicKey->handle); - sftk_FreeObject(publicKey); - NSC_DestroyObject(hSession,privateKey->handle); - sftk_FreeObject(privateKey); - if (sftk_audit_enabled) { - char msg[128]; - PR_snprintf(msg,sizeof msg, - "C_GenerateKeyPair(hSession=0x%08lX, " - "pMechanism->mechanism=0x%08lX)=0x%08lX " - "self-test: pair-wise consistency test failed", - (PRUint32)hSession,(PRUint32)pMechanism->mechanism, - (PRUint32)crv); - sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg); - } - return crv; + NSC_DestroyObject(hSession, publicKey->handle); + sftk_FreeObject(publicKey); + NSC_DestroyObject(hSession, privateKey->handle); + sftk_FreeObject(privateKey); + return crv; } *phPrivateKey = privateKey->handle; @@ -4892,7 +5230,8 @@ ecgn_done: return CKR_OK; } -static SECItem *sftk_PackagePrivateKey(SFTKObject *key, CK_RV *crvp) +static SECItem * +sftk_PackagePrivateKey(SFTKObject *key, CK_RV *crvp) { NSSLOWKEYPrivateKey *lk = NULL; NSSLOWKEYPrivateKeyInfo *pki = NULL; @@ -4909,159 +5248,162 @@ static SECItem *sftk_PackagePrivateKey(SFTKObject *key, CK_RV *crvp) int savelen; #endif - if(!key) { - *crvp = CKR_KEY_HANDLE_INVALID; /* really can't happen */ - return NULL; + if (!key) { + *crvp = CKR_KEY_HANDLE_INVALID; /* really can't happen */ + return NULL; } attribute = sftk_FindAttribute(key, CKA_KEY_TYPE); - if(!attribute) { - *crvp = CKR_KEY_TYPE_INCONSISTENT; - return NULL; + if (!attribute) { + *crvp = CKR_KEY_TYPE_INCONSISTENT; + return NULL; } lk = sftk_GetPrivKey(key, *(CK_KEY_TYPE *)attribute->attrib.pValue, crvp); sftk_FreeAttribute(attribute); - if(!lk) { - return NULL; + if (!lk) { + return NULL; } - arena = PORT_NewArena(2048); /* XXX different size? */ - if(!arena) { - *crvp = CKR_HOST_MEMORY; - rv = SECFailure; - goto loser; + arena = PORT_NewArena(2048); /* XXX different size? */ + if (!arena) { + *crvp = CKR_HOST_MEMORY; + rv = SECFailure; + goto loser; } - pki = (NSSLOWKEYPrivateKeyInfo*)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - if(!pki) { - *crvp = CKR_HOST_MEMORY; - rv = SECFailure; - goto loser; + pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPrivateKeyInfo)); + if (!pki) { + *crvp = CKR_HOST_MEMORY; + rv = SECFailure; + goto loser; } pki->arena = arena; param = NULL; - switch(lk->keyType) { - case NSSLOWKEYRSAKey: - prepare_low_rsa_priv_key_for_asn1(lk); - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_RSAPrivateKeyTemplate); - algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; - break; - case NSSLOWKEYDSAKey: + switch (lk->keyType) { + case NSSLOWKEYRSAKey: + prepare_low_rsa_priv_key_for_asn1(lk); + dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, + nsslowkey_RSAPrivateKeyTemplate); + algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; + break; + case NSSLOWKEYDSAKey: prepare_low_dsa_priv_key_export_for_asn1(lk); - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_DSAPrivateKeyExportTemplate); - prepare_low_pqg_params_for_asn1(&lk->u.dsa.params); - param = SEC_ASN1EncodeItem(NULL, NULL, &(lk->u.dsa.params), - nsslowkey_PQGParamsTemplate); - algorithm = SEC_OID_ANSIX9_DSA_SIGNATURE; - break; + dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, + nsslowkey_DSAPrivateKeyExportTemplate); + prepare_low_pqg_params_for_asn1(&lk->u.dsa.params); + param = SEC_ASN1EncodeItem(NULL, NULL, &(lk->u.dsa.params), + nsslowkey_PQGParamsTemplate); + algorithm = SEC_OID_ANSIX9_DSA_SIGNATURE; + break; #ifndef NSS_DISABLE_ECC case NSSLOWKEYECKey: prepare_low_ec_priv_key_for_asn1(lk); - /* Public value is encoded as a bit string so adjust length - * to be in bits before ASN encoding and readjust - * immediately after. - * - * Since the SECG specification recommends not including the - * parameters as part of ECPrivateKey, we zero out the curveOID - * length before encoding and restore it later. - */ - lk->u.ec.publicValue.len <<= 3; - savelen = lk->u.ec.ecParams.curveOID.len; - lk->u.ec.ecParams.curveOID.len = 0; - dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, - nsslowkey_ECPrivateKeyTemplate); - lk->u.ec.ecParams.curveOID.len = savelen; - lk->u.ec.publicValue.len >>= 3; + /* Public value is encoded as a bit string so adjust length + * to be in bits before ASN encoding and readjust + * immediately after. + * + * Since the SECG specification recommends not including the + * parameters as part of ECPrivateKey, we zero out the curveOID + * length before encoding and restore it later. + */ + lk->u.ec.publicValue.len <<= 3; + savelen = lk->u.ec.ecParams.curveOID.len; + lk->u.ec.ecParams.curveOID.len = 0; + dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk, + nsslowkey_ECPrivateKeyTemplate); + lk->u.ec.ecParams.curveOID.len = savelen; + lk->u.ec.publicValue.len >>= 3; #ifdef EC_DEBUG - fordebug = &pki->privateKey; - SEC_PRINT("sftk_PackagePrivateKey()", "PrivateKey", lk->keyType, - fordebug); + fordebug = &pki->privateKey; + SEC_PRINT("sftk_PackagePrivateKey()", "PrivateKey", lk->keyType, + fordebug); #endif - param = SECITEM_DupItem(&lk->u.ec.ecParams.DEREncoding); + param = SECITEM_DupItem(&lk->u.ec.ecParams.DEREncoding); - algorithm = SEC_OID_ANSIX962_EC_PUBLIC_KEY; - break; + algorithm = SEC_OID_ANSIX962_EC_PUBLIC_KEY; + break; #endif /* NSS_DISABLE_ECC */ - case NSSLOWKEYDHKey: - default: - dummy = NULL; - break; - } - - if(!dummy || ((lk->keyType == NSSLOWKEYDSAKey) && !param)) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; - } - - rv = SECOID_SetAlgorithmID(arena, &pki->algorithm, algorithm, - (SECItem*)param); - if(rv != SECSuccess) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; + case NSSLOWKEYDHKey: + default: + dummy = NULL; + break; + } + + if (!dummy || ((lk->keyType == NSSLOWKEYDSAKey) && !param)) { + *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ + rv = SECFailure; + goto loser; + } + + rv = SECOID_SetAlgorithmID(arena, &pki->algorithm, algorithm, + (SECItem *)param); + if (rv != SECSuccess) { + *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ + rv = SECFailure; + goto loser; } dummy = SEC_ASN1EncodeInteger(arena, &pki->version, - NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); - if(!dummy) { - *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ - rv = SECFailure; - goto loser; + NSSLOWKEY_PRIVATE_KEY_INFO_VERSION); + if (!dummy) { + *crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */ + rv = SECFailure; + goto loser; } - encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, - nsslowkey_PrivateKeyInfoTemplate); + encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, + nsslowkey_PrivateKeyInfoTemplate); *crvp = encodedKey ? CKR_OK : CKR_DEVICE_ERROR; #ifdef EC_DEBUG fordebug = encodedKey; SEC_PRINT("sftk_PackagePrivateKey()", "PrivateKeyInfo", lk->keyType, - fordebug); + fordebug); #endif loser: - if(arena) { - PORT_FreeArena(arena, PR_TRUE); + if (arena) { + PORT_FreeArena(arena, PR_TRUE); } - if(lk && (lk != key->objectInfo)) { - nsslowkey_DestroyPrivateKey(lk); + if (lk && (lk != key->objectInfo)) { + nsslowkey_DestroyPrivateKey(lk); } - - if(param) { - SECITEM_ZfreeItem((SECItem*)param, PR_TRUE); + + if (param) { + SECITEM_ZfreeItem((SECItem *)param, PR_TRUE); } - if(rv != SECSuccess) { - return NULL; + if (rv != SECSuccess) { + return NULL; } return encodedKey; } - + /* it doesn't matter yet, since we colapse error conditions in the * level above, but we really should map those few key error differences */ -static CK_RV -sftk_mapWrap(CK_RV crv) -{ +static CK_RV +sftk_mapWrap(CK_RV crv) +{ switch (crv) { - case CKR_ENCRYPTED_DATA_INVALID: crv = CKR_WRAPPED_KEY_INVALID; break; + case CKR_ENCRYPTED_DATA_INVALID: + crv = CKR_WRAPPED_KEY_INVALID; + break; } - return crv; + return crv; } /* NSC_WrapKey wraps (i.e., encrypts) a key. */ -CK_RV NSC_WrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, - CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen) +CK_RV +NSC_WrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, + CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen) { SFTKSession *session; SFTKAttribute *attribute; @@ -5072,117 +5414,115 @@ CK_RV NSC_WrapKey(CK_SESSION_HANDLE hSession, session = sftk_SessionFromHandle(hSession); if (session == NULL) { - return CKR_SESSION_HANDLE_INVALID; + return CKR_SESSION_HANDLE_INVALID; } - key = sftk_ObjectFromHandle(hKey,session); + key = sftk_ObjectFromHandle(hKey, session); sftk_FreeSession(session); if (key == NULL) { - return CKR_KEY_HANDLE_INVALID; - } - - switch(key->objclass) { - case CKO_SECRET_KEY: - { - SFTKSessionContext *context = NULL; - SECItem pText; - - attribute = sftk_FindAttribute(key,CKA_VALUE); - - if (attribute == NULL) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - crv = sftk_CryptInit(hSession, pMechanism, hWrappingKey, - CKA_WRAP, CKA_WRAP, SFTK_ENCRYPT, PR_TRUE); - if (crv != CKR_OK) { - sftk_FreeAttribute(attribute); - break; - } - - pText.type = siBuffer; - pText.data = (unsigned char *)attribute->attrib.pValue; - pText.len = attribute->attrib.ulValueLen; - - /* Find out if this is a block cipher. */ - crv = sftk_GetContext(hSession,&context,SFTK_ENCRYPT,PR_FALSE,NULL); - if (crv != CKR_OK || !context) - break; - if (context->blockSize > 1) { - unsigned int remainder = pText.len % context->blockSize; - if (!context->doPad && remainder) { - /* When wrapping secret keys with unpadded block ciphers, - ** the keys are zero padded, if necessary, to fill out - ** a full block. - */ - pText.len += context->blockSize - remainder; - pText.data = PORT_ZAlloc(pText.len); - if (pText.data) - memcpy(pText.data, attribute->attrib.pValue, - attribute->attrib.ulValueLen); - else { - crv = CKR_HOST_MEMORY; - break; - } - } - } - - crv = NSC_Encrypt(hSession, (CK_BYTE_PTR)pText.data, - pText.len, pWrappedKey, pulWrappedKeyLen); - /* always force a finalize, both on errors and when - * we are just getting the size */ - if (crv != CKR_OK || pWrappedKey == NULL) { - CK_RV lcrv ; - lcrv = sftk_GetContext(hSession,&context, - SFTK_ENCRYPT,PR_FALSE,NULL); - sftk_SetContextByType(session, SFTK_ENCRYPT, NULL); - if (lcrv == CKR_OK && context) { - sftk_FreeContext(context); - } - } - - if (pText.data != (unsigned char *)attribute->attrib.pValue) - PORT_ZFree(pText.data, pText.len); - sftk_FreeAttribute(attribute); - break; - } - - case CKO_PRIVATE_KEY: - { - SECItem *bpki = sftk_PackagePrivateKey(key, &crv); - SFTKSessionContext *context = NULL; - - if(!bpki) { - break; - } - - crv = sftk_CryptInit(hSession, pMechanism, hWrappingKey, - CKA_WRAP, CKA_WRAP, SFTK_ENCRYPT, PR_TRUE); - if(crv != CKR_OK) { - SECITEM_ZfreeItem(bpki, PR_TRUE); - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - - crv = NSC_Encrypt(hSession, bpki->data, bpki->len, - pWrappedKey, pulWrappedKeyLen); - /* always force a finalize */ - if (crv != CKR_OK || pWrappedKey == NULL) { - CK_RV lcrv ; - lcrv = sftk_GetContext(hSession,&context, - SFTK_ENCRYPT,PR_FALSE,NULL); - sftk_SetContextByType(session, SFTK_ENCRYPT, NULL); - if (lcrv == CKR_OK && context) { - sftk_FreeContext(context); - } - } - SECITEM_ZfreeItem(bpki, PR_TRUE); - break; - } - - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; + return CKR_KEY_HANDLE_INVALID; + } + + switch (key->objclass) { + case CKO_SECRET_KEY: { + SFTKSessionContext *context = NULL; + SECItem pText; + + attribute = sftk_FindAttribute(key, CKA_VALUE); + + if (attribute == NULL) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + crv = sftk_CryptInit(hSession, pMechanism, hWrappingKey, + CKA_WRAP, CKA_WRAP, SFTK_ENCRYPT, PR_TRUE); + if (crv != CKR_OK) { + sftk_FreeAttribute(attribute); + break; + } + + pText.type = siBuffer; + pText.data = (unsigned char *)attribute->attrib.pValue; + pText.len = attribute->attrib.ulValueLen; + + /* Find out if this is a block cipher. */ + crv = sftk_GetContext(hSession, &context, SFTK_ENCRYPT, PR_FALSE, NULL); + if (crv != CKR_OK || !context) + break; + if (context->blockSize > 1) { + unsigned int remainder = pText.len % context->blockSize; + if (!context->doPad && remainder) { + /* When wrapping secret keys with unpadded block ciphers, + ** the keys are zero padded, if necessary, to fill out + ** a full block. + */ + pText.len += context->blockSize - remainder; + pText.data = PORT_ZAlloc(pText.len); + if (pText.data) + memcpy(pText.data, attribute->attrib.pValue, + attribute->attrib.ulValueLen); + else { + crv = CKR_HOST_MEMORY; + break; + } + } + } + + crv = NSC_Encrypt(hSession, (CK_BYTE_PTR)pText.data, + pText.len, pWrappedKey, pulWrappedKeyLen); + /* always force a finalize, both on errors and when + * we are just getting the size */ + if (crv != CKR_OK || pWrappedKey == NULL) { + CK_RV lcrv; + lcrv = sftk_GetContext(hSession, &context, + SFTK_ENCRYPT, PR_FALSE, NULL); + sftk_SetContextByType(session, SFTK_ENCRYPT, NULL); + if (lcrv == CKR_OK && context) { + sftk_FreeContext(context); + } + } + + if (pText.data != (unsigned char *)attribute->attrib.pValue) + PORT_ZFree(pText.data, pText.len); + sftk_FreeAttribute(attribute); + break; + } + + case CKO_PRIVATE_KEY: { + SECItem *bpki = sftk_PackagePrivateKey(key, &crv); + SFTKSessionContext *context = NULL; + + if (!bpki) { + break; + } + + crv = sftk_CryptInit(hSession, pMechanism, hWrappingKey, + CKA_WRAP, CKA_WRAP, SFTK_ENCRYPT, PR_TRUE); + if (crv != CKR_OK) { + SECITEM_ZfreeItem(bpki, PR_TRUE); + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + + crv = NSC_Encrypt(hSession, bpki->data, bpki->len, + pWrappedKey, pulWrappedKeyLen); + /* always force a finalize */ + if (crv != CKR_OK || pWrappedKey == NULL) { + CK_RV lcrv; + lcrv = sftk_GetContext(hSession, &context, + SFTK_ENCRYPT, PR_FALSE, NULL); + sftk_SetContextByType(session, SFTK_ENCRYPT, NULL); + if (lcrv == CKR_OK && context) { + sftk_FreeContext(context); + } + } + SECITEM_ZfreeItem(bpki, PR_TRUE); + break; + } + + default: + crv = CKR_KEY_TYPE_INCONSISTENT; + break; } sftk_FreeObject(key); @@ -5195,7 +5535,7 @@ CK_RV NSC_WrapKey(CK_SESSION_HANDLE hSession, static SECStatus sftk_unwrapPrivateKey(SFTKObject *key, SECItem *bpki) { - CK_BBOOL cktrue = CK_TRUE; + CK_BBOOL cktrue = CK_TRUE; CK_KEY_TYPE keyType = CKK_RSA; SECStatus rv = SECFailure; const SEC_ASN1Template *keyTemplate, *paramTemplate; @@ -5206,66 +5546,65 @@ sftk_unwrapPrivateKey(SFTKObject *key, SECItem *bpki) CK_RV crv = CKR_KEY_TYPE_INCONSISTENT; arena = PORT_NewArena(2048); - if(!arena) { - return SECFailure; + if (!arena) { + return SECFailure; } - pki = (NSSLOWKEYPrivateKeyInfo*)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKeyInfo)); - if(!pki) { - PORT_FreeArena(arena, PR_FALSE); - return SECFailure; + pki = (NSSLOWKEYPrivateKeyInfo *)PORT_ArenaZAlloc(arena, + sizeof(NSSLOWKEYPrivateKeyInfo)); + if (!pki) { + PORT_FreeArena(arena, PR_FALSE); + return SECFailure; } - if(SEC_ASN1DecodeItem(arena, pki, nsslowkey_PrivateKeyInfoTemplate, bpki) - != SECSuccess) { - PORT_FreeArena(arena, PR_TRUE); - return SECFailure; + if (SEC_ASN1DecodeItem(arena, pki, nsslowkey_PrivateKeyInfoTemplate, bpki) != SECSuccess) { + PORT_FreeArena(arena, PR_TRUE); + return SECFailure; } lpk = (NSSLOWKEYPrivateKey *)PORT_ArenaZAlloc(arena, - sizeof(NSSLOWKEYPrivateKey)); - if(lpk == NULL) { - goto loser; + sizeof(NSSLOWKEYPrivateKey)); + if (lpk == NULL) { + goto loser; } lpk->arena = arena; - switch(SECOID_GetAlgorithmTag(&pki->algorithm)) { - case SEC_OID_PKCS1_RSA_ENCRYPTION: - keyTemplate = nsslowkey_RSAPrivateKeyTemplate; - paramTemplate = NULL; - paramDest = NULL; - lpk->keyType = NSSLOWKEYRSAKey; - prepare_low_rsa_priv_key_for_asn1(lpk); - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: - keyTemplate = nsslowkey_DSAPrivateKeyExportTemplate; - paramTemplate = nsslowkey_PQGParamsTemplate; - paramDest = &(lpk->u.dsa.params); - lpk->keyType = NSSLOWKEYDSAKey; - prepare_low_dsa_priv_key_export_for_asn1(lpk); - prepare_low_pqg_params_for_asn1(&lpk->u.dsa.params); - break; - /* case NSSLOWKEYDHKey: */ + switch (SECOID_GetAlgorithmTag(&pki->algorithm)) { + case SEC_OID_PKCS1_RSA_ENCRYPTION: + keyTemplate = nsslowkey_RSAPrivateKeyTemplate; + paramTemplate = NULL; + paramDest = NULL; + lpk->keyType = NSSLOWKEYRSAKey; + prepare_low_rsa_priv_key_for_asn1(lpk); + break; + case SEC_OID_ANSIX9_DSA_SIGNATURE: + keyTemplate = nsslowkey_DSAPrivateKeyExportTemplate; + paramTemplate = nsslowkey_PQGParamsTemplate; + paramDest = &(lpk->u.dsa.params); + lpk->keyType = NSSLOWKEYDSAKey; + prepare_low_dsa_priv_key_export_for_asn1(lpk); + prepare_low_pqg_params_for_asn1(&lpk->u.dsa.params); + break; +/* case NSSLOWKEYDHKey: */ #ifndef NSS_DISABLE_ECC case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - keyTemplate = nsslowkey_ECPrivateKeyTemplate; - paramTemplate = NULL; - paramDest = &(lpk->u.ec.ecParams.DEREncoding); - lpk->keyType = NSSLOWKEYECKey; - prepare_low_ec_priv_key_for_asn1(lpk); - prepare_low_ecparams_for_asn1(&lpk->u.ec.ecParams); - break; + keyTemplate = nsslowkey_ECPrivateKeyTemplate; + paramTemplate = NULL; + paramDest = &(lpk->u.ec.ecParams.DEREncoding); + lpk->keyType = NSSLOWKEYECKey; + prepare_low_ec_priv_key_for_asn1(lpk); + prepare_low_ecparams_for_asn1(&lpk->u.ec.ecParams); + break; #endif /* NSS_DISABLE_ECC */ - default: - keyTemplate = NULL; - paramTemplate = NULL; - paramDest = NULL; - break; + default: + keyTemplate = NULL; + paramTemplate = NULL; + paramDest = NULL; + break; } - if(!keyTemplate) { - goto loser; + if (!keyTemplate) { + goto loser; } /* decode the private key and any algorithm parameters */ @@ -5274,165 +5613,190 @@ sftk_unwrapPrivateKey(SFTKObject *key, SECItem *bpki) #ifndef NSS_DISABLE_ECC if (lpk->keyType == NSSLOWKEYECKey) { /* convert length in bits to length in bytes */ - lpk->u.ec.publicValue.len >>= 3; - rv = SECITEM_CopyItem(arena, - &(lpk->u.ec.ecParams.DEREncoding), - &(pki->algorithm.parameters)); - if(rv != SECSuccess) { - goto loser; - } + lpk->u.ec.publicValue.len >>= 3; + rv = SECITEM_CopyItem(arena, + &(lpk->u.ec.ecParams.DEREncoding), + &(pki->algorithm.parameters)); + if (rv != SECSuccess) { + goto loser; + } } #endif /* NSS_DISABLE_ECC */ - if(rv != SECSuccess) { - goto loser; + if (rv != SECSuccess) { + goto loser; } - if(paramDest && paramTemplate) { - rv = SEC_QuickDERDecodeItem(arena, paramDest, paramTemplate, - &(pki->algorithm.parameters)); - if(rv != SECSuccess) { - goto loser; - } + if (paramDest && paramTemplate) { + rv = SEC_QuickDERDecodeItem(arena, paramDest, paramTemplate, + &(pki->algorithm.parameters)); + if (rv != SECSuccess) { + goto loser; + } } rv = SECFailure; switch (lpk->keyType) { case NSSLOWKEYRSAKey: - keyType = CKK_RSA; - if(sftk_hasAttribute(key, CKA_NETSCAPE_DB)) { - sftk_DeleteAttributeType(key, CKA_NETSCAPE_DB); - } - crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_UNWRAP, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_DECRYPT, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_MODULUS, - sftk_item_expand(&lpk->u.rsa.modulus)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_PUBLIC_EXPONENT, - sftk_item_expand(&lpk->u.rsa.publicExponent)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_PRIVATE_EXPONENT, - sftk_item_expand(&lpk->u.rsa.privateExponent)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_PRIME_1, - sftk_item_expand(&lpk->u.rsa.prime1)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_PRIME_2, - sftk_item_expand(&lpk->u.rsa.prime2)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_EXPONENT_1, - sftk_item_expand(&lpk->u.rsa.exponent1)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_EXPONENT_2, - sftk_item_expand(&lpk->u.rsa.exponent2)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_COEFFICIENT, - sftk_item_expand(&lpk->u.rsa.coefficient)); - break; + keyType = CKK_RSA; + if (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) { + sftk_DeleteAttributeType(key, CKA_NETSCAPE_DB); + } + crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, + sizeof(keyType)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_UNWRAP, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_DECRYPT, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_MODULUS, + sftk_item_expand(&lpk->u.rsa.modulus)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_PUBLIC_EXPONENT, + sftk_item_expand(&lpk->u.rsa.publicExponent)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_PRIVATE_EXPONENT, + sftk_item_expand(&lpk->u.rsa.privateExponent)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_PRIME_1, + sftk_item_expand(&lpk->u.rsa.prime1)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_PRIME_2, + sftk_item_expand(&lpk->u.rsa.prime2)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_EXPONENT_1, + sftk_item_expand(&lpk->u.rsa.exponent1)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_EXPONENT_2, + sftk_item_expand(&lpk->u.rsa.exponent2)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_COEFFICIENT, + sftk_item_expand(&lpk->u.rsa.coefficient)); + break; case NSSLOWKEYDSAKey: - keyType = CKK_DSA; - crv = (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : - CKR_KEY_TYPE_INCONSISTENT; - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_PRIME, - sftk_item_expand(&lpk->u.dsa.params.prime)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SUBPRIME, - sftk_item_expand(&lpk->u.dsa.params.subPrime)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_BASE, - sftk_item_expand(&lpk->u.dsa.params.base)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_VALUE, - sftk_item_expand(&lpk->u.dsa.privateValue)); - if(crv != CKR_OK) break; - break; + keyType = CKK_DSA; + crv = (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : CKR_KEY_TYPE_INCONSISTENT; + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, + sizeof(keyType)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_PRIME, + sftk_item_expand(&lpk->u.dsa.params.prime)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SUBPRIME, + sftk_item_expand(&lpk->u.dsa.params.subPrime)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_BASE, + sftk_item_expand(&lpk->u.dsa.params.base)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_VALUE, + sftk_item_expand(&lpk->u.dsa.privateValue)); + if (crv != CKR_OK) + break; + break; #ifdef notdef case NSSLOWKEYDHKey: - template = dhTemplate; - templateCount = sizeof(dhTemplate)/sizeof(CK_ATTRIBUTE); - keyType = CKK_DH; - break; + template = dhTemplate; + templateCount = sizeof(dhTemplate) / sizeof(CK_ATTRIBUTE); + keyType = CKK_DH; + break; #endif - /* what about fortezza??? */ +/* what about fortezza??? */ #ifndef NSS_DISABLE_ECC case NSSLOWKEYECKey: - keyType = CKK_EC; - crv = (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : - CKR_KEY_TYPE_INCONSISTENT; - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, - sizeof(keyType)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_DERIVE, &cktrue, - sizeof(CK_BBOOL)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_EC_PARAMS, - sftk_item_expand(&lpk->u.ec.ecParams.DEREncoding)); - if(crv != CKR_OK) break; - crv = sftk_AddAttributeType(key, CKA_VALUE, - sftk_item_expand(&lpk->u.ec.privateValue)); - if(crv != CKR_OK) break; - /* XXX Do we need to decode the EC Params here ?? */ - break; + keyType = CKK_EC; + crv = (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK : CKR_KEY_TYPE_INCONSISTENT; + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, + sizeof(keyType)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_SIGN_RECOVER, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_DERIVE, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_EC_PARAMS, + sftk_item_expand(&lpk->u.ec.ecParams.DEREncoding)); + if (crv != CKR_OK) + break; + crv = sftk_AddAttributeType(key, CKA_VALUE, + sftk_item_expand(&lpk->u.ec.privateValue)); + if (crv != CKR_OK) + break; + /* XXX Do we need to decode the EC Params here ?? */ + break; #endif /* NSS_DISABLE_ECC */ - default: - crv = CKR_KEY_TYPE_INCONSISTENT; - break; + default: + crv = CKR_KEY_TYPE_INCONSISTENT; + break; } loser: - if(lpk) { - nsslowkey_DestroyPrivateKey(lpk); + if (lpk) { + nsslowkey_DestroyPrivateKey(lpk); } - if(crv != CKR_OK) { - return SECFailure; + if (crv != CKR_OK) { + return SECFailure; } return SECSuccess; } - /* NSC_UnwrapKey unwraps (decrypts) a wrapped key, creating a new key object. */ -CK_RV NSC_UnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) +CK_RV +NSC_UnwrapKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, + CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) { SFTKObject *key = NULL; SFTKSession *session; CK_ULONG key_length = 0; - unsigned char * buf = NULL; + unsigned char *buf = NULL; CK_RV crv = CKR_OK; int i; CK_ULONG bsize = ulWrappedKeyLen; @@ -5450,99 +5814,102 @@ CK_RV NSC_UnwrapKey(CK_SESSION_HANDLE hSession, */ key = sftk_NewObject(slot); /* fill in the handle later */ if (key == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* * load the template values into the object */ - for (i=0; i < (int) ulAttributeCount; i++) { - if (pTemplate[i].type == CKA_VALUE_LEN) { - key_length = *(CK_ULONG *)pTemplate[i].pValue; - continue; - } + for (i = 0; i < (int)ulAttributeCount; i++) { + if (pTemplate[i].type == CKA_VALUE_LEN) { + key_length = *(CK_ULONG *)pTemplate[i].pValue; + continue; + } if (pTemplate[i].type == CKA_CLASS) { - target_type = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; - } - crv = sftk_AddAttributeType(key,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; + target_type = *(CK_OBJECT_CLASS *)pTemplate[i].pValue; + } + crv = sftk_AddAttributeType(key, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) + break; } if (crv != CKR_OK) { - sftk_FreeObject(key); - return crv; + sftk_FreeObject(key); + return crv; } - crv = sftk_CryptInit(hSession,pMechanism,hUnwrappingKey,CKA_UNWRAP, - CKA_UNWRAP, SFTK_DECRYPT, PR_FALSE); + crv = sftk_CryptInit(hSession, pMechanism, hUnwrappingKey, CKA_UNWRAP, + CKA_UNWRAP, SFTK_DECRYPT, PR_FALSE); if (crv != CKR_OK) { - sftk_FreeObject(key); - return sftk_mapWrap(crv); + sftk_FreeObject(key); + return sftk_mapWrap(crv); } - /* allocate the buffer to decrypt into + /* allocate the buffer to decrypt into * this assumes the unwrapped key is never larger than the * wrapped key. For all the mechanisms we support this is true */ - buf = (unsigned char *)PORT_Alloc( ulWrappedKeyLen); + buf = (unsigned char *)PORT_Alloc(ulWrappedKeyLen); bsize = ulWrappedKeyLen; crv = NSC_Decrypt(hSession, pWrappedKey, ulWrappedKeyLen, buf, &bsize); if (crv != CKR_OK) { - sftk_FreeObject(key); - PORT_Free(buf); - return sftk_mapWrap(crv); - } - - switch(target_type) { - case CKO_SECRET_KEY: - if (!sftk_hasAttribute(key,CKA_KEY_TYPE)) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - - if (key_length == 0 || key_length > bsize) { - key_length = bsize; - } - if (key_length > MAX_KEY_LEN) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - - /* add the value */ - crv = sftk_AddAttributeType(key,CKA_VALUE,buf,key_length); - break; - case CKO_PRIVATE_KEY: - bpki.data = (unsigned char *)buf; - bpki.len = bsize; - crv = CKR_OK; - if(sftk_unwrapPrivateKey(key, &bpki) != SECSuccess) { - crv = CKR_TEMPLATE_INCOMPLETE; - } - break; - default: - crv = CKR_TEMPLATE_INCONSISTENT; - break; + sftk_FreeObject(key); + PORT_Free(buf); + return sftk_mapWrap(crv); + } + + switch (target_type) { + case CKO_SECRET_KEY: + if (!sftk_hasAttribute(key, CKA_KEY_TYPE)) { + crv = CKR_TEMPLATE_INCOMPLETE; + break; + } + + if (key_length == 0 || key_length > bsize) { + key_length = bsize; + } + if (key_length > MAX_KEY_LEN) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + + /* add the value */ + crv = sftk_AddAttributeType(key, CKA_VALUE, buf, key_length); + break; + case CKO_PRIVATE_KEY: + bpki.data = (unsigned char *)buf; + bpki.len = bsize; + crv = CKR_OK; + if (sftk_unwrapPrivateKey(key, &bpki) != SECSuccess) { + crv = CKR_TEMPLATE_INCOMPLETE; + } + break; + default: + crv = CKR_TEMPLATE_INCONSISTENT; + break; } PORT_ZFree(buf, bsize); - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; + } /* get the session */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { - sftk_FreeObject(key); + sftk_FreeObject(key); return CKR_SESSION_HANDLE_INVALID; } /* * handle the base object stuff */ - crv = sftk_handleObject(key,session); + crv = sftk_handleObject(key, session); *phKey = key->handle; sftk_FreeSession(session); sftk_FreeObject(key); return crv; - } /* @@ -5550,9 +5917,9 @@ CK_RV NSC_UnwrapKey(CK_SESSION_HANDLE hSession, * details of each of these key creation. */ static CK_RV -sftk_buildSSLKey(CK_SESSION_HANDLE hSession, SFTKObject *baseKey, - PRBool isMacKey, unsigned char *keyBlock, unsigned int keySize, - CK_OBJECT_HANDLE *keyHandle) +sftk_buildSSLKey(CK_SESSION_HANDLE hSession, SFTKObject *baseKey, + PRBool isMacKey, unsigned char *keyBlock, unsigned int keySize, + CK_OBJECT_HANDLE *keyHandle) { SFTKObject *key; SFTKSession *session; @@ -5565,43 +5932,57 @@ sftk_buildSSLKey(CK_SESSION_HANDLE hSession, SFTKObject *baseKey, * now lets create an object to hang the attributes off of */ *keyHandle = CK_INVALID_HANDLE; - key = sftk_NewObject(baseKey->slot); - if (key == NULL) return CKR_HOST_MEMORY; + key = sftk_NewObject(baseKey->slot); + if (key == NULL) + return CKR_HOST_MEMORY; sftk_narrowToSessionObject(key)->wasDerived = PR_TRUE; - crv = sftk_CopyObject(key,baseKey); - if (crv != CKR_OK) goto loser; + crv = sftk_CopyObject(key, baseKey); + if (crv != CKR_OK) + goto loser; if (isMacKey) { - crv = sftk_forceAttribute(key,CKA_KEY_TYPE,&keyType,sizeof(keyType)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_ENCRYPT,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_DECRYPT,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_SIGN,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_VERIFY,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_WRAP,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - crv = sftk_forceAttribute(key,CKA_UNWRAP,&ckfalse,sizeof(CK_BBOOL)); - if (crv != CKR_OK) goto loser; - } - crv = sftk_forceAttribute(key,CKA_VALUE,keyBlock,keySize); - if (crv != CKR_OK) goto loser; + crv = sftk_forceAttribute(key, CKA_KEY_TYPE, &keyType, sizeof(keyType)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_ENCRYPT, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_DECRYPT, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_SIGN, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_WRAP, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + crv = sftk_forceAttribute(key, CKA_UNWRAP, &ckfalse, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + goto loser; + } + crv = sftk_forceAttribute(key, CKA_VALUE, keyBlock, keySize); + if (crv != CKR_OK) + goto loser; /* get the session */ crv = CKR_HOST_MEMORY; session = sftk_SessionFromHandle(hSession); - if (session == NULL) { goto loser; } + if (session == NULL) { + goto loser; + } - crv = sftk_handleObject(key,session); + crv = sftk_handleObject(key, session); sftk_FreeSession(session); *keyHandle = key->handle; loser: - if (key) sftk_FreeObject(key); + if (key) + sftk_FreeObject(key); return crv; } @@ -5611,20 +5992,20 @@ loser: */ static void sftk_freeSSLKeys(CK_SESSION_HANDLE session, - CK_SSL3_KEY_MAT_OUT *returnedMaterial ) + CK_SSL3_KEY_MAT_OUT *returnedMaterial) { - if (returnedMaterial->hClientMacSecret != CK_INVALID_HANDLE) { - NSC_DestroyObject(session,returnedMaterial->hClientMacSecret); - } - if (returnedMaterial->hServerMacSecret != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hServerMacSecret); - } - if (returnedMaterial->hClientKey != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hClientKey); - } - if (returnedMaterial->hServerKey != CK_INVALID_HANDLE) { - NSC_DestroyObject(session, returnedMaterial->hServerKey); - } + if (returnedMaterial->hClientMacSecret != CK_INVALID_HANDLE) { + NSC_DestroyObject(session, returnedMaterial->hClientMacSecret); + } + if (returnedMaterial->hServerMacSecret != CK_INVALID_HANDLE) { + NSC_DestroyObject(session, returnedMaterial->hServerMacSecret); + } + if (returnedMaterial->hClientKey != CK_INVALID_HANDLE) { + NSC_DestroyObject(session, returnedMaterial->hClientKey); + } + if (returnedMaterial->hServerKey != CK_INVALID_HANDLE) { + NSC_DestroyObject(session, returnedMaterial->hServerKey); + } } /* @@ -5633,7 +6014,7 @@ sftk_freeSSLKeys(CK_SESSION_HANDLE session, * semantics. */ static CK_RV -sftk_DeriveSensitiveCheck(SFTKObject *baseKey,SFTKObject *destKey) +sftk_DeriveSensitiveCheck(SFTKObject *baseKey, SFTKObject *destKey) { PRBool hasSensitive; PRBool sensitive = PR_FALSE; @@ -5643,46 +6024,49 @@ sftk_DeriveSensitiveCheck(SFTKObject *baseKey,SFTKObject *destKey) SFTKAttribute *att; hasSensitive = PR_FALSE; - att = sftk_FindAttribute(destKey,CKA_SENSITIVE); + att = sftk_FindAttribute(destKey, CKA_SENSITIVE); if (att) { hasSensitive = PR_TRUE; - sensitive = (PRBool) *(CK_BBOOL *)att->attrib.pValue; - sftk_FreeAttribute(att); + sensitive = (PRBool) * (CK_BBOOL *)att->attrib.pValue; + sftk_FreeAttribute(att); } hasExtractable = PR_FALSE; - att = sftk_FindAttribute(destKey,CKA_EXTRACTABLE); + att = sftk_FindAttribute(destKey, CKA_EXTRACTABLE); if (att) { hasExtractable = PR_TRUE; - extractable = (PRBool) *(CK_BBOOL *)att->attrib.pValue; - sftk_FreeAttribute(att); + extractable = (PRBool) * (CK_BBOOL *)att->attrib.pValue; + sftk_FreeAttribute(att); } - /* don't make a key more accessible */ - if (sftk_isTrue(baseKey,CKA_SENSITIVE) && hasSensitive && - (sensitive == PR_FALSE)) { - return CKR_KEY_FUNCTION_NOT_PERMITTED; + if (sftk_isTrue(baseKey, CKA_SENSITIVE) && hasSensitive && + (sensitive == PR_FALSE)) { + return CKR_KEY_FUNCTION_NOT_PERMITTED; } - if (!sftk_isTrue(baseKey,CKA_EXTRACTABLE) && hasExtractable && - (extractable == PR_TRUE)) { - return CKR_KEY_FUNCTION_NOT_PERMITTED; + if (!sftk_isTrue(baseKey, CKA_EXTRACTABLE) && hasExtractable && + (extractable == PR_TRUE)) { + return CKR_KEY_FUNCTION_NOT_PERMITTED; } /* inherit parent's sensitivity */ if (!hasSensitive) { - att = sftk_FindAttribute(baseKey,CKA_SENSITIVE); - if (att == NULL) return CKR_KEY_TYPE_INCONSISTENT; - crv = sftk_defaultAttribute(destKey,sftk_attr_expand(&att->attrib)); - sftk_FreeAttribute(att); - if (crv != CKR_OK) return crv; + att = sftk_FindAttribute(baseKey, CKA_SENSITIVE); + if (att == NULL) + return CKR_KEY_TYPE_INCONSISTENT; + crv = sftk_defaultAttribute(destKey, sftk_attr_expand(&att->attrib)); + sftk_FreeAttribute(att); + if (crv != CKR_OK) + return crv; } if (!hasExtractable) { - att = sftk_FindAttribute(baseKey,CKA_EXTRACTABLE); - if (att == NULL) return CKR_KEY_TYPE_INCONSISTENT; - crv = sftk_defaultAttribute(destKey,sftk_attr_expand(&att->attrib)); - sftk_FreeAttribute(att); - if (crv != CKR_OK) return crv; + att = sftk_FindAttribute(baseKey, CKA_EXTRACTABLE); + if (att == NULL) + return CKR_KEY_TYPE_INCONSISTENT; + crv = sftk_defaultAttribute(destKey, sftk_attr_expand(&att->attrib)); + sftk_FreeAttribute(att); + if (crv != CKR_OK) + return crv; } /* we should inherit the parent's always extractable/ never sensitive info, @@ -5693,22 +6077,22 @@ sftk_DeriveSensitiveCheck(SFTKObject *baseKey,SFTKObject *destKey) /* * make known fixed PKCS #11 key types to their sizes in bytes - */ + */ unsigned long -sftk_MapKeySize(CK_KEY_TYPE keyType) +sftk_MapKeySize(CK_KEY_TYPE keyType) { switch (keyType) { - case CKK_CDMF: - return 8; - case CKK_DES: - return 8; - case CKK_DES2: - return 16; - case CKK_DES3: - return 24; - /* IDEA and CAST need to be added */ - default: - break; + case CKK_CDMF: + return 8; + case CKK_DES: + return 8; + case CKK_DES2: + return 16; + case CKK_DES3: + return 24; + /* IDEA and CAST need to be added */ + default: + break; } return 0; } @@ -5724,10 +6108,11 @@ sftk_MapKeySize(CK_KEY_TYPE keyType) * Output: * key: Pointer to a buffer containing derived key, if return value is SECSuccess. */ -static CK_RV sftk_compute_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, SECItem *SharedSecret, - CK_BYTE_PTR SharedInfo, CK_ULONG SharedInfoLen, - SECStatus Hash(unsigned char *, const unsigned char *, PRUint32), - CK_ULONG HashLen) +static CK_RV +sftk_compute_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, SECItem *SharedSecret, + CK_BYTE_PTR SharedInfo, CK_ULONG SharedInfoLen, + SECStatus Hash(unsigned char *, const unsigned char *, PRUint32), + CK_ULONG HashLen) { unsigned char *buffer = NULL, *output_buffer = NULL; PRUint32 buffer_len, max_counter, i; @@ -5738,26 +6123,26 @@ static CK_RV sftk_compute_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, SECIte * greatly increased if the code below did not limit the 4-byte counter * to a maximum value of 255. */ if (key_len > 254 * HashLen) - return CKR_ARGUMENTS_BAD; + return CKR_ARGUMENTS_BAD; if (SharedInfo == NULL) - SharedInfoLen = 0; + SharedInfoLen = 0; buffer_len = SharedSecret->len + 4 + SharedInfoLen; buffer = (CK_BYTE *)PORT_Alloc(buffer_len); if (buffer == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } - max_counter = key_len/HashLen; + max_counter = key_len / HashLen; if (key_len > max_counter * HashLen) - max_counter++; + max_counter++; output_buffer = (CK_BYTE *)PORT_Alloc(max_counter * HashLen); if (output_buffer == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } /* Populate buffer with SharedSecret || Counter || [SharedInfo] @@ -5768,61 +6153,62 @@ static CK_RV sftk_compute_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, SECIte buffer[SharedSecret->len + 2] = 0; buffer[SharedSecret->len + 3] = 1; if (SharedInfo) { - PORT_Memcpy(&buffer[SharedSecret->len + 4], SharedInfo, SharedInfoLen); + PORT_Memcpy(&buffer[SharedSecret->len + 4], SharedInfo, SharedInfoLen); } - for(i=0; i < max_counter; i++) { - rv = Hash(&output_buffer[i * HashLen], buffer, buffer_len); - if (rv != SECSuccess) { - /* 'Hash' should not fail. */ - crv = CKR_FUNCTION_FAILED; - goto loser; - } + for (i = 0; i < max_counter; i++) { + rv = Hash(&output_buffer[i * HashLen], buffer, buffer_len); + if (rv != SECSuccess) { + /* 'Hash' should not fail. */ + crv = CKR_FUNCTION_FAILED; + goto loser; + } - /* Increment counter (assumes max_counter < 255) */ - buffer[SharedSecret->len + 3]++; + /* Increment counter (assumes max_counter < 255) */ + buffer[SharedSecret->len + 3]++; } PORT_ZFree(buffer, buffer_len); if (key_len < max_counter * HashLen) { - PORT_Memset(output_buffer + key_len, 0, max_counter * HashLen - key_len); + PORT_Memset(output_buffer + key_len, 0, max_counter * HashLen - key_len); } *key = output_buffer; return CKR_OK; - loser: - if (buffer) { - PORT_ZFree(buffer, buffer_len); - } - if (output_buffer) { - PORT_ZFree(output_buffer, max_counter * HashLen); - } - return crv; +loser: + if (buffer) { + PORT_ZFree(buffer, buffer_len); + } + if (output_buffer) { + PORT_ZFree(output_buffer, max_counter * HashLen); + } + return crv; } -static CK_RV sftk_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, - SECItem *SharedSecret, - CK_BYTE_PTR SharedInfo, CK_ULONG SharedInfoLen, - CK_EC_KDF_TYPE kdf) +static CK_RV +sftk_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, + SECItem *SharedSecret, + CK_BYTE_PTR SharedInfo, CK_ULONG SharedInfoLen, + CK_EC_KDF_TYPE kdf) { if (kdf == CKD_SHA1_KDF) - return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, - SharedInfoLen, SHA1_HashBuf, SHA1_LENGTH); + return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, + SharedInfoLen, SHA1_HashBuf, SHA1_LENGTH); else if (kdf == CKD_SHA224_KDF) - return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, - SharedInfoLen, SHA224_HashBuf, SHA224_LENGTH); + return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, + SharedInfoLen, SHA224_HashBuf, SHA224_LENGTH); else if (kdf == CKD_SHA256_KDF) - return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, - SharedInfoLen, SHA256_HashBuf, SHA256_LENGTH); + return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, + SharedInfoLen, SHA256_HashBuf, SHA256_LENGTH); else if (kdf == CKD_SHA384_KDF) - return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, - SharedInfoLen, SHA384_HashBuf, SHA384_LENGTH); + return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, + SharedInfoLen, SHA384_HashBuf, SHA384_LENGTH); else if (kdf == CKD_SHA512_KDF) - return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, - SharedInfoLen, SHA512_HashBuf, SHA512_LENGTH); + return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo, + SharedInfoLen, SHA512_HashBuf, SHA512_LENGTH); else - return CKR_MECHANISM_INVALID; + return CKR_MECHANISM_INVALID; } #endif /* NSS_DISABLE_ECC */ @@ -5830,59 +6216,59 @@ static CK_RV sftk_ANSI_X9_63_kdf(CK_BYTE **key, CK_ULONG key_len, * SSL Key generation given pre master secret */ #define NUM_MIXERS 9 -static const char * const mixers[NUM_MIXERS] = { - "A", - "BB", - "CCC", - "DDDD", - "EEEEE", - "FFFFFF", +static const char *const mixers[NUM_MIXERS] = { + "A", + "BB", + "CCC", + "DDDD", + "EEEEE", + "FFFFFF", "GGGGGGG", "HHHHHHHH", - "IIIIIIIII" }; + "IIIIIIIII" +}; #define SSL3_PMS_LENGTH 48 #define SSL3_MASTER_SECRET_LENGTH 48 #define SSL3_RANDOM_LENGTH 32 - /* NSC_DeriveKey derives a key from a base key, creating a new key object. */ -CK_RV NSC_DeriveKey( CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey) +CK_RV +NSC_DeriveKey(CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey) { - SFTKSession * session; - SFTKSlot * slot = sftk_SlotFromSessionHandle(hSession); - SFTKObject * key; - SFTKObject * sourceKey; - SFTKAttribute * att = NULL; - SFTKAttribute * att2 = NULL; - unsigned char * buf; - SHA1Context * sha; - MD5Context * md5; - MD2Context * md2; - CK_ULONG macSize; - CK_ULONG tmpKeySize; - CK_ULONG IVSize; - CK_ULONG keySize = 0; - CK_RV crv = CKR_OK; - CK_BBOOL cktrue = CK_TRUE; - CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; - CK_OBJECT_CLASS classType = CKO_SECRET_KEY; + SFTKSession *session; + SFTKSlot *slot = sftk_SlotFromSessionHandle(hSession); + SFTKObject *key; + SFTKObject *sourceKey; + SFTKAttribute *att = NULL; + SFTKAttribute *att2 = NULL; + unsigned char *buf; + SHA1Context *sha; + MD5Context *md5; + MD2Context *md2; + CK_ULONG macSize; + CK_ULONG tmpKeySize; + CK_ULONG IVSize; + CK_ULONG keySize = 0; + CK_RV crv = CKR_OK; + CK_BBOOL cktrue = CK_TRUE; + CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; + CK_OBJECT_CLASS classType = CKO_SECRET_KEY; CK_KEY_DERIVATION_STRING_DATA *stringPtr; CK_MECHANISM_TYPE mechanism = pMechanism->mechanism; - PRBool isTLS = PR_FALSE; - PRBool isDH = PR_FALSE; - HASH_HashType tlsPrfHash = HASH_AlgNULL; - SECStatus rv; - int i; - unsigned int outLen; - unsigned char sha_out[SHA1_LENGTH]; - unsigned char key_block[NUM_MIXERS * MD5_LENGTH]; - unsigned char key_block2[MD5_LENGTH]; - PRBool isFIPS; - HASH_HashType hashType; - PRBool extractValue = PR_TRUE; + PRBool isTLS = PR_FALSE; + PRBool isDH = PR_FALSE; + HASH_HashType tlsPrfHash = HASH_AlgNULL; + SECStatus rv; + int i; + unsigned int outLen; + unsigned char sha_out[SHA1_LENGTH]; + unsigned char key_block[NUM_MIXERS * SFTK_MAX_MAC_LENGTH]; + PRBool isFIPS; + HASH_HashType hashType; + PRBool extractValue = PR_TRUE; CHECK_FORK(); @@ -5892,75 +6278,80 @@ CK_RV NSC_DeriveKey( CK_SESSION_HANDLE hSession, /* * now lets create an object to hang the attributes off of */ - if (phKey) *phKey = CK_INVALID_HANDLE; + if (phKey) + *phKey = CK_INVALID_HANDLE; key = sftk_NewObject(slot); /* fill in the handle later */ if (key == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } isFIPS = (slot->slotID == FIPS_SLOT_ID); /* * load the template values into the object */ - for (i=0; i < (int) ulAttributeCount; i++) { - crv = sftk_AddAttributeType(key,sftk_attr_expand(&pTemplate[i])); - if (crv != CKR_OK) break; + for (i = 0; i < (int)ulAttributeCount; i++) { + crv = sftk_AddAttributeType(key, sftk_attr_expand(&pTemplate[i])); + if (crv != CKR_OK) + break; - if (pTemplate[i].type == CKA_KEY_TYPE) { - keyType = *(CK_KEY_TYPE *)pTemplate[i].pValue; - } - if (pTemplate[i].type == CKA_VALUE_LEN) { - keySize = *(CK_ULONG *)pTemplate[i].pValue; - } + if (pTemplate[i].type == CKA_KEY_TYPE) { + keyType = *(CK_KEY_TYPE *)pTemplate[i].pValue; + } + if (pTemplate[i].type == CKA_VALUE_LEN) { + keySize = *(CK_ULONG *)pTemplate[i].pValue; + } + } + if (crv != CKR_OK) { + sftk_FreeObject(key); + return crv; } - if (crv != CKR_OK) { sftk_FreeObject(key); return crv; } if (keySize == 0) { - keySize = sftk_MapKeySize(keyType); + keySize = sftk_MapKeySize(keyType); } switch (mechanism) { - case CKM_NSS_JPAKE_ROUND2_SHA1: /* fall through */ - case CKM_NSS_JPAKE_ROUND2_SHA256: /* fall through */ - case CKM_NSS_JPAKE_ROUND2_SHA384: /* fall through */ - case CKM_NSS_JPAKE_ROUND2_SHA512: - extractValue = PR_FALSE; - classType = CKO_PRIVATE_KEY; - break; - case CKM_NSS_JPAKE_FINAL_SHA1: /* fall through */ - case CKM_NSS_JPAKE_FINAL_SHA256: /* fall through */ - case CKM_NSS_JPAKE_FINAL_SHA384: /* fall through */ - case CKM_NSS_JPAKE_FINAL_SHA512: - extractValue = PR_FALSE; - /* fall through */ - default: - classType = CKO_SECRET_KEY; - } - - crv = sftk_forceAttribute (key,CKA_CLASS,&classType,sizeof(classType)); + case CKM_NSS_JPAKE_ROUND2_SHA1: /* fall through */ + case CKM_NSS_JPAKE_ROUND2_SHA256: /* fall through */ + case CKM_NSS_JPAKE_ROUND2_SHA384: /* fall through */ + case CKM_NSS_JPAKE_ROUND2_SHA512: + extractValue = PR_FALSE; + classType = CKO_PRIVATE_KEY; + break; + case CKM_NSS_JPAKE_FINAL_SHA1: /* fall through */ + case CKM_NSS_JPAKE_FINAL_SHA256: /* fall through */ + case CKM_NSS_JPAKE_FINAL_SHA384: /* fall through */ + case CKM_NSS_JPAKE_FINAL_SHA512: + extractValue = PR_FALSE; + /* fall through */ + default: + classType = CKO_SECRET_KEY; + } + + crv = sftk_forceAttribute(key, CKA_CLASS, &classType, sizeof(classType)); if (crv != CKR_OK) { - sftk_FreeObject(key); - return crv; + sftk_FreeObject(key); + return crv; } - /* look up the base key we're deriving with */ + /* look up the base key we're deriving with */ session = sftk_SessionFromHandle(hSession); if (session == NULL) { - sftk_FreeObject(key); + sftk_FreeObject(key); return CKR_SESSION_HANDLE_INVALID; } - sourceKey = sftk_ObjectFromHandle(hBaseKey,session); + sourceKey = sftk_ObjectFromHandle(hBaseKey, session); sftk_FreeSession(session); if (sourceKey == NULL) { - sftk_FreeObject(key); + sftk_FreeObject(key); return CKR_KEY_HANDLE_INVALID; } if (extractValue) { /* get the value of the base key */ - att = sftk_FindAttribute(sourceKey,CKA_VALUE); + att = sftk_FindAttribute(sourceKey, CKA_VALUE); if (att == NULL) { sftk_FreeObject(key); sftk_FreeObject(sourceKey); @@ -5969,1283 +6360,1197 @@ CK_RV NSC_DeriveKey( CK_SESSION_HANDLE hSession, } switch (mechanism) { - /* - * generate the master secret - */ - case CKM_TLS12_MASTER_KEY_DERIVE: - case CKM_TLS12_MASTER_KEY_DERIVE_DH: - case CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256: - case CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256: - case CKM_TLS_MASTER_KEY_DERIVE: - case CKM_TLS_MASTER_KEY_DERIVE_DH: - case CKM_SSL3_MASTER_KEY_DERIVE: - case CKM_SSL3_MASTER_KEY_DERIVE_DH: - { - CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ssl3_master; - SSL3RSAPreMasterSecret * rsa_pms; - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - - if ((mechanism == CKM_TLS12_MASTER_KEY_DERIVE) || - (mechanism == CKM_TLS12_MASTER_KEY_DERIVE_DH)) { - CK_TLS12_MASTER_KEY_DERIVE_PARAMS *tls12_master = - (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *) pMechanism->pParameter; - tlsPrfHash = GetHashTypeFromMechanism(tls12_master->prfHashMechanism); - if (tlsPrfHash == HASH_AlgNULL) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - } else if ((mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256) || - (mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) { - tlsPrfHash = HASH_AlgSHA256; - } - - if ((mechanism != CKM_SSL3_MASTER_KEY_DERIVE) && - (mechanism != CKM_SSL3_MASTER_KEY_DERIVE_DH)) { - isTLS = PR_TRUE; - } - if ((mechanism == CKM_SSL3_MASTER_KEY_DERIVE_DH) || - (mechanism == CKM_TLS_MASTER_KEY_DERIVE_DH) || - (mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256) || - (mechanism == CKM_TLS12_MASTER_KEY_DERIVE_DH)) { - isDH = PR_TRUE; - } - - /* first do the consistency checks */ - if (!isDH && (att->attrib.ulValueLen != SSL3_PMS_LENGTH)) { - crv = CKR_KEY_TYPE_INCONSISTENT; - break; - } - att2 = sftk_FindAttribute(sourceKey,CKA_KEY_TYPE); - if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != - CKK_GENERIC_SECRET)) { - if (att2) sftk_FreeAttribute(att2); - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - sftk_FreeAttribute(att2); - if (keyType != CKK_GENERIC_SECRET) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - if ((keySize != 0) && (keySize != SSL3_MASTER_SECRET_LENGTH)) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - - /* finally do the key gen */ - ssl3_master = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) - pMechanism->pParameter; - - PORT_Memcpy(crsrdata, - ssl3_master->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, - ssl3_master->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); - - if (ssl3_master->pVersion) { - SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); - rsa_pms = (SSL3RSAPreMasterSecret *) att->attrib.pValue; - /* don't leak more key material then necessary for SSL to work */ - if ((sessKey == NULL) || sessKey->wasDerived) { - ssl3_master->pVersion->major = 0xff; - ssl3_master->pVersion->minor = 0xff; - } else { - ssl3_master->pVersion->major = rsa_pms->client_version[0]; - ssl3_master->pVersion->minor = rsa_pms->client_version[1]; - } - } - if (ssl3_master->RandomInfo.ulClientRandomLen != SSL3_RANDOM_LENGTH) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - if (ssl3_master->RandomInfo.ulServerRandomLen != SSL3_RANDOM_LENGTH) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - - if (isTLS) { - SECStatus status; - SECItem crsr = { siBuffer, NULL, 0 }; - SECItem master = { siBuffer, NULL, 0 }; - SECItem pms = { siBuffer, NULL, 0 }; - - crsr.data = crsrdata; - crsr.len = sizeof crsrdata; - master.data = key_block; - master.len = SSL3_MASTER_SECRET_LENGTH; - pms.data = (unsigned char*)att->attrib.pValue; - pms.len = att->attrib.ulValueLen; - - if (tlsPrfHash != HASH_AlgNULL) { - status = TLS_P_hash(tlsPrfHash, &pms, "master secret", - &crsr, &master, isFIPS); - } else { - status = TLS_PRF(&pms, "master secret", &crsr, &master, isFIPS); - } - if (status != SECSuccess) { - crv = CKR_FUNCTION_FAILED; - break; - } - } else { - /* now allocate the hash contexts */ - md5 = MD5_NewContext(); - if (md5 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - sha = SHA1_NewContext(); - if (sha == NULL) { - PORT_Free(md5); - crv = CKR_HOST_MEMORY; - break; - } - for (i = 0; i < 3; i++) { - SHA1_Begin(sha); - SHA1_Update(sha, (unsigned char*) mixers[i], strlen(mixers[i])); - SHA1_Update(sha, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - SHA1_Update(sha, crsrdata, sizeof crsrdata); - SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - - MD5_Begin(md5); - MD5_Update(md5, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD5_Update(md5, sha_out, outLen); - MD5_End(md5, &key_block[i*MD5_LENGTH], &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - } - PORT_Free(md5); - PORT_Free(sha); - } - - /* store the results */ - crv = sftk_forceAttribute - (key,CKA_VALUE,key_block,SSL3_MASTER_SECRET_LENGTH); - if (crv != CKR_OK) break; - keyType = CKK_GENERIC_SECRET; - crv = sftk_forceAttribute (key,CKA_KEY_TYPE,&keyType,sizeof(keyType)); - if (isTLS) { - /* TLS's master secret is used to "sign" finished msgs with PRF. */ - /* XXX This seems like a hack. But SFTK_Derive only accepts - * one "operation" argument. */ - crv = sftk_forceAttribute(key,CKA_SIGN, &cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - crv = sftk_forceAttribute(key,CKA_VERIFY,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - /* While we're here, we might as well force this, too. */ - crv = sftk_forceAttribute(key,CKA_DERIVE,&cktrue,sizeof(CK_BBOOL)); - if (crv != CKR_OK) break; - } - break; - } - - /* Extended master key derivation [draft-ietf-tls-session-hash] */ - case CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE: - case CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH: - { - CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS *ems_params; - SSL3RSAPreMasterSecret *rsa_pms; - SECStatus status; - SECItem pms = { siBuffer, NULL, 0 }; - SECItem seed = { siBuffer, NULL, 0 }; - SECItem master = { siBuffer, NULL, 0 }; - - ems_params = (CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS*) - pMechanism->pParameter; - - /* First do the consistency checks */ - if ((mechanism == CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE) && - (att->attrib.ulValueLen != SSL3_PMS_LENGTH)) { - crv = CKR_KEY_TYPE_INCONSISTENT; + /* + * generate the master secret + */ + case CKM_TLS12_MASTER_KEY_DERIVE: + case CKM_TLS12_MASTER_KEY_DERIVE_DH: + case CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256: + case CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256: + case CKM_TLS_MASTER_KEY_DERIVE: + case CKM_TLS_MASTER_KEY_DERIVE_DH: + case CKM_SSL3_MASTER_KEY_DERIVE: + case CKM_SSL3_MASTER_KEY_DERIVE_DH: { + CK_SSL3_MASTER_KEY_DERIVE_PARAMS *ssl3_master; + SSL3RSAPreMasterSecret *rsa_pms; + unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; + + if ((mechanism == CKM_TLS12_MASTER_KEY_DERIVE) || + (mechanism == CKM_TLS12_MASTER_KEY_DERIVE_DH)) { + CK_TLS12_MASTER_KEY_DERIVE_PARAMS *tls12_master = + (CK_TLS12_MASTER_KEY_DERIVE_PARAMS *)pMechanism->pParameter; + tlsPrfHash = GetHashTypeFromMechanism(tls12_master->prfHashMechanism); + if (tlsPrfHash == HASH_AlgNULL) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + } else if ((mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256) || + (mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) { + tlsPrfHash = HASH_AlgSHA256; + } + + if ((mechanism != CKM_SSL3_MASTER_KEY_DERIVE) && + (mechanism != CKM_SSL3_MASTER_KEY_DERIVE_DH)) { + isTLS = PR_TRUE; + } + if ((mechanism == CKM_SSL3_MASTER_KEY_DERIVE_DH) || + (mechanism == CKM_TLS_MASTER_KEY_DERIVE_DH) || + (mechanism == CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256) || + (mechanism == CKM_TLS12_MASTER_KEY_DERIVE_DH)) { + isDH = PR_TRUE; + } + + /* first do the consistency checks */ + if (!isDH && (att->attrib.ulValueLen != SSL3_PMS_LENGTH)) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att2 = sftk_FindAttribute(sourceKey, CKA_KEY_TYPE); + if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != + CKK_GENERIC_SECRET)) { + if (att2) + sftk_FreeAttribute(att2); + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + sftk_FreeAttribute(att2); + if (keyType != CKK_GENERIC_SECRET) { + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + if ((keySize != 0) && (keySize != SSL3_MASTER_SECRET_LENGTH)) { + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + + /* finally do the key gen */ + ssl3_master = (CK_SSL3_MASTER_KEY_DERIVE_PARAMS *) + pMechanism->pParameter; + + PORT_Memcpy(crsrdata, + ssl3_master->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); + PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, + ssl3_master->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); + + if (ssl3_master->pVersion) { + SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); + rsa_pms = (SSL3RSAPreMasterSecret *)att->attrib.pValue; + /* don't leak more key material then necessary for SSL to work */ + if ((sessKey == NULL) || sessKey->wasDerived) { + ssl3_master->pVersion->major = 0xff; + ssl3_master->pVersion->minor = 0xff; + } else { + ssl3_master->pVersion->major = rsa_pms->client_version[0]; + ssl3_master->pVersion->minor = rsa_pms->client_version[1]; + } + } + if (ssl3_master->RandomInfo.ulClientRandomLen != SSL3_RANDOM_LENGTH) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + if (ssl3_master->RandomInfo.ulServerRandomLen != SSL3_RANDOM_LENGTH) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + + if (isTLS) { + SECStatus status; + SECItem crsr = { siBuffer, NULL, 0 }; + SECItem master = { siBuffer, NULL, 0 }; + SECItem pms = { siBuffer, NULL, 0 }; + + crsr.data = crsrdata; + crsr.len = sizeof crsrdata; + master.data = key_block; + master.len = SSL3_MASTER_SECRET_LENGTH; + pms.data = (unsigned char *)att->attrib.pValue; + pms.len = att->attrib.ulValueLen; + + if (tlsPrfHash != HASH_AlgNULL) { + status = TLS_P_hash(tlsPrfHash, &pms, "master secret", + &crsr, &master, isFIPS); + } else { + status = TLS_PRF(&pms, "master secret", &crsr, &master, isFIPS); + } + if (status != SECSuccess) { + crv = CKR_FUNCTION_FAILED; + break; + } + } else { + /* now allocate the hash contexts */ + md5 = MD5_NewContext(); + if (md5 == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + sha = SHA1_NewContext(); + if (sha == NULL) { + PORT_Free(md5); + crv = CKR_HOST_MEMORY; + break; + } + for (i = 0; i < 3; i++) { + SHA1_Begin(sha); + SHA1_Update(sha, (unsigned char *)mixers[i], strlen(mixers[i])); + SHA1_Update(sha, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + SHA1_Update(sha, crsrdata, sizeof crsrdata); + SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); + PORT_Assert(outLen == SHA1_LENGTH); + + MD5_Begin(md5); + MD5_Update(md5, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + MD5_Update(md5, sha_out, outLen); + MD5_End(md5, &key_block[i * MD5_LENGTH], &outLen, MD5_LENGTH); + PORT_Assert(outLen == MD5_LENGTH); + } + PORT_Free(md5); + PORT_Free(sha); + } + + /* store the results */ + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, SSL3_MASTER_SECRET_LENGTH); + if (crv != CKR_OK) + break; + keyType = CKK_GENERIC_SECRET; + crv = sftk_forceAttribute(key, CKA_KEY_TYPE, &keyType, sizeof(keyType)); + if (isTLS) { + /* TLS's master secret is used to "sign" finished msgs with PRF. */ + /* XXX This seems like a hack. But SFTK_Derive only accepts + * one "operation" argument. */ + crv = sftk_forceAttribute(key, CKA_SIGN, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + crv = sftk_forceAttribute(key, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + /* While we're here, we might as well force this, too. */ + crv = sftk_forceAttribute(key, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL)); + if (crv != CKR_OK) + break; + } break; } - att2 = sftk_FindAttribute(sourceKey,CKA_KEY_TYPE); - if ((att2 == NULL) || - (*(CK_KEY_TYPE *)att2->attrib.pValue != CKK_GENERIC_SECRET)) { - if (att2) sftk_FreeAttribute(att2); - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + + /* Extended master key derivation [draft-ietf-tls-session-hash] */ + case CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE: + case CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH: { + CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS *ems_params; + SSL3RSAPreMasterSecret *rsa_pms; + SECStatus status; + SECItem pms = { siBuffer, NULL, 0 }; + SECItem seed = { siBuffer, NULL, 0 }; + SECItem master = { siBuffer, NULL, 0 }; + + ems_params = (CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS *) + pMechanism->pParameter; + + /* First do the consistency checks */ + if ((mechanism == CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE) && + (att->attrib.ulValueLen != SSL3_PMS_LENGTH)) { + crv = CKR_KEY_TYPE_INCONSISTENT; + break; + } + att2 = sftk_FindAttribute(sourceKey, CKA_KEY_TYPE); + if ((att2 == NULL) || + (*(CK_KEY_TYPE *)att2->attrib.pValue != CKK_GENERIC_SECRET)) { + if (att2) + sftk_FreeAttribute(att2); + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + sftk_FreeAttribute(att2); + if (keyType != CKK_GENERIC_SECRET) { + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + if ((keySize != 0) && (keySize != SSL3_MASTER_SECRET_LENGTH)) { + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + + /* Do the key derivation */ + pms.data = (unsigned char *)att->attrib.pValue; + pms.len = att->attrib.ulValueLen; + seed.data = ems_params->pSessionHash; + seed.len = ems_params->ulSessionHashLen; + master.data = key_block; + master.len = SSL3_MASTER_SECRET_LENGTH; + if (ems_params->prfHashMechanism == CKM_TLS_PRF) { + /* + * In this case, the session hash is the concatenation of SHA-1 + * and MD5, so it should be 36 bytes long. + */ + if (seed.len != MD5_LENGTH + SHA1_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + + status = TLS_PRF(&pms, "extended master secret", + &seed, &master, isFIPS); + } else { + const SECHashObject *hashObj; + + tlsPrfHash = GetHashTypeFromMechanism(ems_params->prfHashMechanism); + if (tlsPrfHash == HASH_AlgNULL) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + + hashObj = HASH_GetRawHashObject(tlsPrfHash); + if (seed.len != hashObj->length) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + + status = TLS_P_hash(tlsPrfHash, &pms, "extended master secret", + &seed, &master, isFIPS); + } + if (status != SECSuccess) { + crv = CKR_FUNCTION_FAILED; + break; + } + + /* Reflect the version if required */ + if (ems_params->pVersion) { + SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); + rsa_pms = (SSL3RSAPreMasterSecret *)att->attrib.pValue; + /* don't leak more key material than necessary for SSL to work */ + if ((sessKey == NULL) || sessKey->wasDerived) { + ems_params->pVersion->major = 0xff; + ems_params->pVersion->minor = 0xff; + } else { + ems_params->pVersion->major = rsa_pms->client_version[0]; + ems_params->pVersion->minor = rsa_pms->client_version[1]; + } + } + + /* Store the results */ + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, + SSL3_MASTER_SECRET_LENGTH); break; } - sftk_FreeAttribute(att2); - if (keyType != CKK_GENERIC_SECRET) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + + case CKM_TLS12_KEY_AND_MAC_DERIVE: + case CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256: + case CKM_TLS_KEY_AND_MAC_DERIVE: + case CKM_SSL3_KEY_AND_MAC_DERIVE: { + CK_SSL3_KEY_MAT_PARAMS *ssl3_keys; + CK_SSL3_KEY_MAT_OUT *ssl3_keys_out; + CK_ULONG effKeySize; + unsigned int block_needed; + unsigned char srcrdata[SSL3_RANDOM_LENGTH * 2]; + unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; + + if (mechanism == CKM_TLS12_KEY_AND_MAC_DERIVE) { + CK_TLS12_KEY_MAT_PARAMS *tls12_keys = + (CK_TLS12_KEY_MAT_PARAMS *)pMechanism->pParameter; + tlsPrfHash = GetHashTypeFromMechanism(tls12_keys->prfHashMechanism); + if (tlsPrfHash == HASH_AlgNULL) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + } else if (mechanism == CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256) { + tlsPrfHash = HASH_AlgSHA256; + } + + if (mechanism != CKM_SSL3_KEY_AND_MAC_DERIVE) { + isTLS = PR_TRUE; + } + + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + if (att->attrib.ulValueLen != SSL3_MASTER_SECRET_LENGTH) { + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + att2 = sftk_FindAttribute(sourceKey, CKA_KEY_TYPE); + if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != + CKK_GENERIC_SECRET)) { + if (att2) + sftk_FreeAttribute(att2); + crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + break; + } + sftk_FreeAttribute(att2); + md5 = MD5_NewContext(); + if (md5 == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + sha = SHA1_NewContext(); + if (sha == NULL) { + MD5_DestroyContext(md5, PR_TRUE); + crv = CKR_HOST_MEMORY; + break; + } + ssl3_keys = (CK_SSL3_KEY_MAT_PARAMS *)pMechanism->pParameter; + + PORT_Memcpy(srcrdata, + ssl3_keys->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); + PORT_Memcpy(srcrdata + SSL3_RANDOM_LENGTH, + ssl3_keys->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); + + PORT_Memcpy(crsrdata, + ssl3_keys->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); + PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, + ssl3_keys->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); + + /* + * clear out our returned keys so we can recover on failure + */ + ssl3_keys_out = ssl3_keys->pReturnedKeyMaterial; + ssl3_keys_out->hClientMacSecret = CK_INVALID_HANDLE; + ssl3_keys_out->hServerMacSecret = CK_INVALID_HANDLE; + ssl3_keys_out->hClientKey = CK_INVALID_HANDLE; + ssl3_keys_out->hServerKey = CK_INVALID_HANDLE; + + /* + * How much key material do we need? + */ + macSize = ssl3_keys->ulMacSizeInBits / 8; + effKeySize = ssl3_keys->ulKeySizeInBits / 8; + IVSize = ssl3_keys->ulIVSizeInBits / 8; + if (keySize == 0) { + effKeySize = keySize; + } + + /* bIsExport must be false. */ + if (ssl3_keys->bIsExport) { + MD5_DestroyContext(md5, PR_TRUE); + SHA1_DestroyContext(sha, PR_TRUE); + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + + block_needed = 2 * (macSize + effKeySize + IVSize); + PORT_Assert(block_needed <= sizeof key_block); + if (block_needed > sizeof key_block) + block_needed = sizeof key_block; + + /* + * generate the key material: This looks amazingly similar to the + * PMS code, and is clearly crying out for a function to provide it. + */ + if (isTLS) { + SECStatus status; + SECItem srcr = { siBuffer, NULL, 0 }; + SECItem keyblk = { siBuffer, NULL, 0 }; + SECItem master = { siBuffer, NULL, 0 }; + + srcr.data = srcrdata; + srcr.len = sizeof srcrdata; + keyblk.data = key_block; + keyblk.len = block_needed; + master.data = (unsigned char *)att->attrib.pValue; + master.len = att->attrib.ulValueLen; + + if (tlsPrfHash != HASH_AlgNULL) { + status = TLS_P_hash(tlsPrfHash, &master, "key expansion", + &srcr, &keyblk, isFIPS); + } else { + status = TLS_PRF(&master, "key expansion", &srcr, &keyblk, + isFIPS); + } + if (status != SECSuccess) { + goto key_and_mac_derive_fail; + } + } else { + unsigned int block_bytes = 0; + /* key_block = + * MD5(master_secret + SHA('A' + master_secret + + * ServerHello.random + ClientHello.random)) + + * MD5(master_secret + SHA('BB' + master_secret + + * ServerHello.random + ClientHello.random)) + + * MD5(master_secret + SHA('CCC' + master_secret + + * ServerHello.random + ClientHello.random)) + + * [...]; + */ + for (i = 0; i < NUM_MIXERS && block_bytes < block_needed; i++) { + SHA1_Begin(sha); + SHA1_Update(sha, (unsigned char *)mixers[i], strlen(mixers[i])); + SHA1_Update(sha, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + SHA1_Update(sha, srcrdata, sizeof srcrdata); + SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); + PORT_Assert(outLen == SHA1_LENGTH); + MD5_Begin(md5); + MD5_Update(md5, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + MD5_Update(md5, sha_out, outLen); + MD5_End(md5, &key_block[i * MD5_LENGTH], &outLen, MD5_LENGTH); + PORT_Assert(outLen == MD5_LENGTH); + block_bytes += outLen; + } + } + + /* + * Put the key material where it goes. + */ + i = 0; /* now shows how much consumed */ + + /* + * The key_block is partitioned as follows: + * client_write_MAC_secret[CipherSpec.hash_size] + */ + crv = sftk_buildSSLKey(hSession, key, PR_TRUE, &key_block[i], macSize, + &ssl3_keys_out->hClientMacSecret); + if (crv != CKR_OK) + goto key_and_mac_derive_fail; + + i += macSize; + + /* + * server_write_MAC_secret[CipherSpec.hash_size] + */ + crv = sftk_buildSSLKey(hSession, key, PR_TRUE, &key_block[i], macSize, + &ssl3_keys_out->hServerMacSecret); + if (crv != CKR_OK) { + goto key_and_mac_derive_fail; + } + i += macSize; + + if (keySize) { + /* + ** Generate Domestic write keys and IVs. + ** client_write_key[CipherSpec.key_material] + */ + crv = sftk_buildSSLKey(hSession, key, PR_FALSE, &key_block[i], + keySize, &ssl3_keys_out->hClientKey); + if (crv != CKR_OK) { + goto key_and_mac_derive_fail; + } + i += keySize; + + /* + ** server_write_key[CipherSpec.key_material] + */ + crv = sftk_buildSSLKey(hSession, key, PR_FALSE, &key_block[i], + keySize, &ssl3_keys_out->hServerKey); + if (crv != CKR_OK) { + goto key_and_mac_derive_fail; + } + i += keySize; + + /* + ** client_write_IV[CipherSpec.IV_size] + */ + if (IVSize > 0) { + PORT_Memcpy(ssl3_keys_out->pIVClient, + &key_block[i], IVSize); + i += IVSize; + } + + /* + ** server_write_IV[CipherSpec.IV_size] + */ + if (IVSize > 0) { + PORT_Memcpy(ssl3_keys_out->pIVServer, + &key_block[i], IVSize); + i += IVSize; + } + PORT_Assert(i <= sizeof key_block); + } + + crv = CKR_OK; + + if (0) { + key_and_mac_derive_fail: + if (crv == CKR_OK) + crv = CKR_FUNCTION_FAILED; + sftk_freeSSLKeys(hSession, ssl3_keys_out); + } + MD5_DestroyContext(md5, PR_TRUE); + SHA1_DestroyContext(sha, PR_TRUE); + sftk_FreeObject(key); + key = NULL; break; } - if ((keySize != 0) && (keySize != SSL3_MASTER_SECRET_LENGTH)) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; + + case CKM_CONCATENATE_BASE_AND_KEY: { + SFTKObject *newKey; + + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + session = sftk_SessionFromHandle(hSession); + if (session == NULL) { + crv = CKR_SESSION_HANDLE_INVALID; + break; + } + + newKey = sftk_ObjectFromHandle(*(CK_OBJECT_HANDLE *) + pMechanism->pParameter, + session); + sftk_FreeSession(session); + if (newKey == NULL) { + crv = CKR_KEY_HANDLE_INVALID; + break; + } + + if (sftk_isTrue(newKey, CKA_SENSITIVE)) { + crv = sftk_forceAttribute(newKey, CKA_SENSITIVE, &cktrue, + sizeof(CK_BBOOL)); + if (crv != CKR_OK) { + sftk_FreeObject(newKey); + break; + } + } + + att2 = sftk_FindAttribute(newKey, CKA_VALUE); + if (att2 == NULL) { + sftk_FreeObject(newKey); + crv = CKR_KEY_HANDLE_INVALID; + break; + } + tmpKeySize = att->attrib.ulValueLen + att2->attrib.ulValueLen; + if (keySize == 0) + keySize = tmpKeySize; + if (keySize > tmpKeySize) { + sftk_FreeObject(newKey); + sftk_FreeAttribute(att2); + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + buf = (unsigned char *)PORT_Alloc(tmpKeySize); + if (buf == NULL) { + sftk_FreeAttribute(att2); + sftk_FreeObject(newKey); + crv = CKR_HOST_MEMORY; + break; + } + + PORT_Memcpy(buf, att->attrib.pValue, att->attrib.ulValueLen); + PORT_Memcpy(buf + att->attrib.ulValueLen, + att2->attrib.pValue, att2->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, buf, keySize); + PORT_ZFree(buf, tmpKeySize); + sftk_FreeAttribute(att2); + sftk_FreeObject(newKey); break; } - /* Do the key derivation */ - pms.data = (unsigned char*) att->attrib.pValue; - pms.len = att->attrib.ulValueLen; - seed.data = ems_params->pSessionHash; - seed.len = ems_params->ulSessionHashLen; - master.data = key_block; - master.len = SSL3_MASTER_SECRET_LENGTH; - if (ems_params-> prfHashMechanism == CKM_TLS_PRF) { - /* - * In this case, the session hash is the concatenation of SHA-1 - * and MD5, so it should be 36 bytes long. - */ - if (seed.len != MD5_LENGTH + SHA1_LENGTH) { + case CKM_CONCATENATE_BASE_AND_DATA: + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; + tmpKeySize = att->attrib.ulValueLen + stringPtr->ulLen; + if (keySize == 0) + keySize = tmpKeySize; + if (keySize > tmpKeySize) { crv = CKR_TEMPLATE_INCONSISTENT; break; } + buf = (unsigned char *)PORT_Alloc(tmpKeySize); + if (buf == NULL) { + crv = CKR_HOST_MEMORY; + break; + } - status = TLS_PRF(&pms, "extended master secret", - &seed, &master, isFIPS); - } else { - const SECHashObject *hashObj; + PORT_Memcpy(buf, att->attrib.pValue, att->attrib.ulValueLen); + PORT_Memcpy(buf + att->attrib.ulValueLen, stringPtr->pData, + stringPtr->ulLen); - tlsPrfHash = GetHashTypeFromMechanism(ems_params->prfHashMechanism); - if (tlsPrfHash == HASH_AlgNULL) { - crv = CKR_MECHANISM_PARAM_INVALID; + crv = sftk_forceAttribute(key, CKA_VALUE, buf, keySize); + PORT_ZFree(buf, tmpKeySize); + break; + case CKM_CONCATENATE_DATA_AND_BASE: + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; + tmpKeySize = att->attrib.ulValueLen + stringPtr->ulLen; + if (keySize == 0) + keySize = tmpKeySize; + if (keySize > tmpKeySize) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + buf = (unsigned char *)PORT_Alloc(tmpKeySize); + if (buf == NULL) { + crv = CKR_HOST_MEMORY; break; } - hashObj = HASH_GetRawHashObject(tlsPrfHash); - if (seed.len != hashObj->length) { + PORT_Memcpy(buf, stringPtr->pData, stringPtr->ulLen); + PORT_Memcpy(buf + stringPtr->ulLen, att->attrib.pValue, + att->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, buf, keySize); + PORT_ZFree(buf, tmpKeySize); + break; + case CKM_XOR_BASE_AND_DATA: + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; + tmpKeySize = PR_MIN(att->attrib.ulValueLen, stringPtr->ulLen); + if (keySize == 0) + keySize = tmpKeySize; + if (keySize > tmpKeySize) { crv = CKR_TEMPLATE_INCONSISTENT; break; } + buf = (unsigned char *)PORT_Alloc(keySize); + if (buf == NULL) { + crv = CKR_HOST_MEMORY; + break; + } - status = TLS_P_hash(tlsPrfHash, &pms, "extended master secret", - &seed, &master, isFIPS); - } - if (status != SECSuccess) { - crv = CKR_FUNCTION_FAILED; + PORT_Memcpy(buf, att->attrib.pValue, keySize); + for (i = 0; i < (int)keySize; i++) { + buf[i] ^= stringPtr->pData[i]; + } + + crv = sftk_forceAttribute(key, CKA_VALUE, buf, keySize); + PORT_ZFree(buf, keySize); break; - } - /* Reflect the version if required */ - if (ems_params->pVersion) { - SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); - rsa_pms = (SSL3RSAPreMasterSecret *) att->attrib.pValue; - /* don't leak more key material than necessary for SSL to work */ - if ((sessKey == NULL) || sessKey->wasDerived) { - ems_params->pVersion->major = 0xff; - ems_params->pVersion->minor = 0xff; - } else { - ems_params->pVersion->major = rsa_pms->client_version[0]; - ems_params->pVersion->minor = rsa_pms->client_version[1]; + case CKM_EXTRACT_KEY_FROM_KEY: { + /* the following assumes 8 bits per byte */ + CK_ULONG extract = *(CK_EXTRACT_PARAMS *)pMechanism->pParameter; + CK_ULONG shift = extract & 0x7; /* extract mod 8 the fast way */ + CK_ULONG offset = extract >> 3; /* extract div 8 the fast way */ + + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv != CKR_OK) + break; + + if (keySize == 0) { + crv = CKR_TEMPLATE_INCOMPLETE; + break; } + /* make sure we have enough bits in the original key */ + if (att->attrib.ulValueLen < + (offset + keySize + ((shift != 0) ? 1 : 0))) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + buf = (unsigned char *)PORT_Alloc(keySize); + if (buf == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + + /* copy the bits we need into the new key */ + for (i = 0; i < (int)keySize; i++) { + unsigned char *value = + ((unsigned char *)att->attrib.pValue) + offset + i; + if (shift) { + buf[i] = (value[0] << (shift)) | (value[1] >> (8 - shift)); + } else { + buf[i] = value[0]; + } + } + + crv = sftk_forceAttribute(key, CKA_VALUE, buf, keySize); + PORT_ZFree(buf, keySize); + break; } + case CKM_MD2_KEY_DERIVATION: + if (keySize == 0) + keySize = MD2_LENGTH; + if (keySize > MD2_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + /* now allocate the hash contexts */ + md2 = MD2_NewContext(); + if (md2 == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + MD2_Begin(md2); + MD2_Update(md2, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + MD2_End(md2, key_block, &outLen, MD2_LENGTH); + MD2_DestroyContext(md2, PR_TRUE); - /* Store the results */ - crv = sftk_forceAttribute(key, CKA_VALUE, key_block, - SSL3_MASTER_SECRET_LENGTH); - break; - } - - case CKM_TLS12_KEY_AND_MAC_DERIVE: - case CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256: - case CKM_TLS_KEY_AND_MAC_DERIVE: - case CKM_SSL3_KEY_AND_MAC_DERIVE: - { - CK_SSL3_KEY_MAT_PARAMS *ssl3_keys; - CK_SSL3_KEY_MAT_OUT * ssl3_keys_out; - CK_ULONG effKeySize; - unsigned int block_needed; - unsigned char srcrdata[SSL3_RANDOM_LENGTH * 2]; - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - - if (mechanism == CKM_TLS12_KEY_AND_MAC_DERIVE) { - CK_TLS12_KEY_MAT_PARAMS *tls12_keys = - (CK_TLS12_KEY_MAT_PARAMS *) pMechanism->pParameter; - tlsPrfHash = GetHashTypeFromMechanism(tls12_keys->prfHashMechanism); - if (tlsPrfHash == HASH_AlgNULL) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - } else if (mechanism == CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256) { - tlsPrfHash = HASH_AlgSHA256; - } - - if (mechanism != CKM_SSL3_KEY_AND_MAC_DERIVE) { - isTLS = PR_TRUE; - } - - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - if (att->attrib.ulValueLen != SSL3_MASTER_SECRET_LENGTH) { - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - att2 = sftk_FindAttribute(sourceKey,CKA_KEY_TYPE); - if ((att2 == NULL) || (*(CK_KEY_TYPE *)att2->attrib.pValue != - CKK_GENERIC_SECRET)) { - if (att2) sftk_FreeAttribute(att2); - crv = CKR_KEY_FUNCTION_NOT_PERMITTED; - break; - } - sftk_FreeAttribute(att2); - md5 = MD5_NewContext(); - if (md5 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - sha = SHA1_NewContext(); - if (sha == NULL) { - PORT_Free(md5); - crv = CKR_HOST_MEMORY; - break; - } - ssl3_keys = (CK_SSL3_KEY_MAT_PARAMS *) pMechanism->pParameter; - - PORT_Memcpy(srcrdata, - ssl3_keys->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); - PORT_Memcpy(srcrdata + SSL3_RANDOM_LENGTH, - ssl3_keys->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); - - PORT_Memcpy(crsrdata, - ssl3_keys->RandomInfo.pClientRandom, SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, - ssl3_keys->RandomInfo.pServerRandom, SSL3_RANDOM_LENGTH); - - /* - * clear out our returned keys so we can recover on failure - */ - ssl3_keys_out = ssl3_keys->pReturnedKeyMaterial; - ssl3_keys_out->hClientMacSecret = CK_INVALID_HANDLE; - ssl3_keys_out->hServerMacSecret = CK_INVALID_HANDLE; - ssl3_keys_out->hClientKey = CK_INVALID_HANDLE; - ssl3_keys_out->hServerKey = CK_INVALID_HANDLE; - - /* - * How much key material do we need? - */ - macSize = ssl3_keys->ulMacSizeInBits/8; - effKeySize = ssl3_keys->ulKeySizeInBits/8; - IVSize = ssl3_keys->ulIVSizeInBits/8; - if (keySize == 0) { - effKeySize = keySize; - } - block_needed = 2 * (macSize + effKeySize + - ((!ssl3_keys->bIsExport) * IVSize)); - PORT_Assert(block_needed <= sizeof key_block); - if (block_needed > sizeof key_block) - block_needed = sizeof key_block; - - /* - * generate the key material: This looks amazingly similar to the - * PMS code, and is clearly crying out for a function to provide it. - */ - if (isTLS) { - SECStatus status; - SECItem srcr = { siBuffer, NULL, 0 }; - SECItem keyblk = { siBuffer, NULL, 0 }; - SECItem master = { siBuffer, NULL, 0 }; - - srcr.data = srcrdata; - srcr.len = sizeof srcrdata; - keyblk.data = key_block; - keyblk.len = block_needed; - master.data = (unsigned char*)att->attrib.pValue; - master.len = att->attrib.ulValueLen; - - if (tlsPrfHash != HASH_AlgNULL) { - status = TLS_P_hash(tlsPrfHash, &master, "key expansion", - &srcr, &keyblk, isFIPS); - } else { - status = TLS_PRF(&master, "key expansion", &srcr, &keyblk, - isFIPS); - } - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - } else { - unsigned int block_bytes = 0; - /* key_block = - * MD5(master_secret + SHA('A' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('BB' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('CCC' + master_secret + - * ServerHello.random + ClientHello.random)) + - * [...]; - */ - for (i = 0; i < NUM_MIXERS && block_bytes < block_needed; i++) { - SHA1_Begin(sha); - SHA1_Update(sha, (unsigned char*) mixers[i], strlen(mixers[i])); - SHA1_Update(sha, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - SHA1_Update(sha, srcrdata, sizeof srcrdata); - SHA1_End(sha, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - MD5_Begin(md5); - MD5_Update(md5, (const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD5_Update(md5, sha_out, outLen); - MD5_End(md5, &key_block[i*MD5_LENGTH], &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - block_bytes += outLen; - } - } - - /* - * Put the key material where it goes. - */ - i = 0; /* now shows how much consumed */ - - /* - * The key_block is partitioned as follows: - * client_write_MAC_secret[CipherSpec.hash_size] - */ - crv = sftk_buildSSLKey(hSession,key,PR_TRUE,&key_block[i],macSize, - &ssl3_keys_out->hClientMacSecret); - if (crv != CKR_OK) - goto key_and_mac_derive_fail; - - i += macSize; - - /* - * server_write_MAC_secret[CipherSpec.hash_size] - */ - crv = sftk_buildSSLKey(hSession,key,PR_TRUE,&key_block[i],macSize, - &ssl3_keys_out->hServerMacSecret); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += macSize; - - if (keySize) { - if (!ssl3_keys->bIsExport) { - /* - ** Generate Domestic write keys and IVs. - ** client_write_key[CipherSpec.key_material] - */ - crv = sftk_buildSSLKey(hSession,key,PR_FALSE,&key_block[i], - keySize, &ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += keySize; - - /* - ** server_write_key[CipherSpec.key_material] - */ - crv = sftk_buildSSLKey(hSession,key,PR_FALSE,&key_block[i], - keySize, &ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - i += keySize; - - /* - ** client_write_IV[CipherSpec.IV_size] - */ - if (IVSize > 0) { - PORT_Memcpy(ssl3_keys_out->pIVClient, - &key_block[i], IVSize); - i += IVSize; - } - - /* - ** server_write_IV[CipherSpec.IV_size] - */ - if (IVSize > 0) { - PORT_Memcpy(ssl3_keys_out->pIVServer, - &key_block[i], IVSize); - i += IVSize; - } - PORT_Assert(i <= sizeof key_block); - - } else if (!isTLS) { - - /* - ** Generate SSL3 Export write keys and IVs. - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = MD5(client_write_key + - ** ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, &key_block[i], effKeySize); - MD5_Update(md5, crsrdata, sizeof crsrdata); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - crv = sftk_buildSSLKey(hSession,key,PR_FALSE,key_block2, - keySize,&ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = MD5(server_write_key + - ** ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, &key_block[i], effKeySize); - MD5_Update(md5, srcrdata, sizeof srcrdata); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - crv = sftk_buildSSLKey(hSession,key,PR_FALSE,key_block2, - keySize,&ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** client_write_IV = - ** MD5(ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, crsrdata, sizeof crsrdata); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - PORT_Memcpy(ssl3_keys_out->pIVClient, key_block2, IVSize); - - /* - ** server_write_IV = - ** MD5(ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5); - MD5_Update(md5, srcrdata, sizeof srcrdata); - MD5_End(md5, key_block2, &outLen, MD5_LENGTH); - PORT_Memcpy(ssl3_keys_out->pIVServer, key_block2, IVSize); - - } else { - - /* - ** Generate TLS 1.0 Export write keys and IVs. - */ - SECStatus status; - SECItem secret = { siBuffer, NULL, 0 }; - SECItem crsr = { siBuffer, NULL, 0 }; - SECItem keyblk = { siBuffer, NULL, 0 }; - - /* - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = PRF(client_write_key, - ** "client write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - crsr.data = crsrdata; - crsr.len = sizeof crsrdata; - keyblk.data = key_block2; - keyblk.len = sizeof key_block2; - status = TLS_PRF(&secret, "client write key", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - crv = sftk_buildSSLKey(hSession, key, PR_FALSE, key_block2, - keySize, &ssl3_keys_out->hClientKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = PRF(server_write_key, - ** "server write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - keyblk.data = key_block2; - keyblk.len = sizeof key_block2; - status = TLS_PRF(&secret, "server write key", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - crv = sftk_buildSSLKey(hSession, key, PR_FALSE, key_block2, - keySize, &ssl3_keys_out->hServerKey); - if (crv != CKR_OK) { - goto key_and_mac_derive_fail; - } - - /* - ** iv_block = PRF("", "IV block", - ** client_random + server_random); - ** client_write_IV[SecurityParameters.IV_size] - ** server_write_IV[SecurityParameters.IV_size] - */ - if (IVSize) { - secret.data = NULL; - secret.len = 0; - keyblk.data = &key_block[i]; - keyblk.len = 2 * IVSize; - status = TLS_PRF(&secret, "IV block", &crsr, &keyblk, - isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - PORT_Memcpy(ssl3_keys_out->pIVClient, keyblk.data, IVSize); - PORT_Memcpy(ssl3_keys_out->pIVServer, keyblk.data + IVSize, - IVSize); - } - } - } - - crv = CKR_OK; - - if (0) { -key_and_mac_derive_fail: - if (crv == CKR_OK) - crv = CKR_FUNCTION_FAILED; - sftk_freeSSLKeys(hSession, ssl3_keys_out); - } - MD5_DestroyContext(md5, PR_TRUE); - SHA1_DestroyContext(sha, PR_TRUE); - sftk_FreeObject(key); - key = NULL; - break; - } - - case CKM_CONCATENATE_BASE_AND_KEY: - { - SFTKObject *newKey; - - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - session = sftk_SessionFromHandle(hSession); - if (session == NULL) { - crv = CKR_SESSION_HANDLE_INVALID; - break; - } - - newKey = sftk_ObjectFromHandle(*(CK_OBJECT_HANDLE *) - pMechanism->pParameter,session); - sftk_FreeSession(session); - if ( newKey == NULL) { - crv = CKR_KEY_HANDLE_INVALID; - break; - } - - if (sftk_isTrue(newKey,CKA_SENSITIVE)) { - crv = sftk_forceAttribute(newKey,CKA_SENSITIVE,&cktrue, - sizeof(CK_BBOOL)); - if (crv != CKR_OK) { - sftk_FreeObject(newKey); - break; - } - } - - att2 = sftk_FindAttribute(newKey,CKA_VALUE); - if (att2 == NULL) { - sftk_FreeObject(newKey); - crv = CKR_KEY_HANDLE_INVALID; - break; - } - tmpKeySize = att->attrib.ulValueLen+att2->attrib.ulValueLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - sftk_FreeObject(newKey); - sftk_FreeAttribute(att2); - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - sftk_FreeAttribute(att2); - sftk_FreeObject(newKey); - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,att->attrib.pValue,att->attrib.ulValueLen); - PORT_Memcpy(buf+att->attrib.ulValueLen, - att2->attrib.pValue,att2->attrib.ulValueLen); - - crv = sftk_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - sftk_FreeAttribute(att2); - sftk_FreeObject(newKey); - break; - } - - case CKM_CONCATENATE_BASE_AND_DATA: - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *) pMechanism->pParameter; - tmpKeySize = att->attrib.ulValueLen+stringPtr->ulLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,att->attrib.pValue,att->attrib.ulValueLen); - PORT_Memcpy(buf+att->attrib.ulValueLen,stringPtr->pData, - stringPtr->ulLen); - - crv = sftk_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - break; - case CKM_CONCATENATE_DATA_AND_BASE: - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; - tmpKeySize = att->attrib.ulValueLen+stringPtr->ulLen; - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(tmpKeySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - PORT_Memcpy(buf,stringPtr->pData,stringPtr->ulLen); - PORT_Memcpy(buf+stringPtr->ulLen,att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,tmpKeySize); - break; - case CKM_XOR_BASE_AND_DATA: - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - stringPtr = (CK_KEY_DERIVATION_STRING_DATA *)pMechanism->pParameter; - tmpKeySize = PR_MIN(att->attrib.ulValueLen,stringPtr->ulLen); - if (keySize == 0) keySize = tmpKeySize; - if (keySize > tmpKeySize) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - buf = (unsigned char*)PORT_Alloc(keySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - - PORT_Memcpy(buf,att->attrib.pValue,keySize); - for (i=0; i < (int)keySize; i++) { - buf[i] ^= stringPtr->pData[i]; - } - - crv = sftk_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,keySize); - break; - - case CKM_EXTRACT_KEY_FROM_KEY: - { - /* the following assumes 8 bits per byte */ - CK_ULONG extract = *(CK_EXTRACT_PARAMS *)pMechanism->pParameter; - CK_ULONG shift = extract & 0x7; /* extract mod 8 the fast way */ - CK_ULONG offset = extract >> 3; /* extract div 8 the fast way */ - - crv = sftk_DeriveSensitiveCheck(sourceKey,key); - if (crv != CKR_OK) break; - - if (keySize == 0) { - crv = CKR_TEMPLATE_INCOMPLETE; - break; - } - /* make sure we have enough bits in the original key */ - if (att->attrib.ulValueLen < - (offset + keySize + ((shift != 0)? 1 :0)) ) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - buf = (unsigned char*)PORT_Alloc(keySize); - if (buf == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - - /* copy the bits we need into the new key */ - for (i=0; i < (int)keySize; i++) { - unsigned char *value = - ((unsigned char *)att->attrib.pValue)+offset+i; - if (shift) { - buf[i] = (value[0] << (shift)) | (value[1] >> (8 - shift)); - } else { - buf[i] = value[0]; - } - } - - crv = sftk_forceAttribute (key,CKA_VALUE,buf,keySize); - PORT_ZFree(buf,keySize); - break; - } - case CKM_MD2_KEY_DERIVATION: - if (keySize == 0) keySize = MD2_LENGTH; - if (keySize > MD2_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - /* now allocate the hash contexts */ - md2 = MD2_NewContext(); - if (md2 == NULL) { - crv = CKR_HOST_MEMORY; - break; - } - MD2_Begin(md2); - MD2_Update(md2,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - MD2_End(md2,key_block,&outLen,MD2_LENGTH); - MD2_DestroyContext(md2, PR_TRUE); - - crv = sftk_forceAttribute (key,CKA_VALUE,key_block,keySize); - break; - case CKM_MD5_KEY_DERIVATION: - if (keySize == 0) keySize = MD5_LENGTH; - if (keySize > MD5_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - MD5_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute (key,CKA_VALUE,key_block,keySize); - break; - case CKM_SHA1_KEY_DERIVATION: - if (keySize == 0) keySize = SHA1_LENGTH; - if (keySize > SHA1_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - SHA1_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_SHA224_KEY_DERIVATION: - if (keySize == 0) keySize = SHA224_LENGTH; - if (keySize > SHA224_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - SHA224_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_SHA256_KEY_DERIVATION: - if (keySize == 0) keySize = SHA256_LENGTH; - if (keySize > SHA256_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - SHA256_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_SHA384_KEY_DERIVATION: - if (keySize == 0) keySize = SHA384_LENGTH; - if (keySize > SHA384_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - SHA384_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_SHA512_KEY_DERIVATION: - if (keySize == 0) keySize = SHA512_LENGTH; - if (keySize > SHA512_LENGTH) { - crv = CKR_TEMPLATE_INCONSISTENT; - break; - } - SHA512_HashBuf(key_block,(const unsigned char*)att->attrib.pValue, - att->attrib.ulValueLen); - - crv = sftk_forceAttribute(key,CKA_VALUE,key_block,keySize); - break; - - case CKM_DH_PKCS_DERIVE: - { - SECItem derived, dhPublic; - SECItem dhPrime, dhValue; - /* sourceKey - values for the local existing low key */ - /* get prime and value attributes */ - crv = sftk_Attribute2SecItem(NULL, &dhPrime, sourceKey, CKA_PRIME); - if (crv != SECSuccess) break; - crv = sftk_Attribute2SecItem(NULL, &dhValue, sourceKey, CKA_VALUE); - if (crv != SECSuccess) { - PORT_Free(dhPrime.data); - break; - } - - dhPublic.data = pMechanism->pParameter; - dhPublic.len = pMechanism->ulParameterLen; - - /* calculate private value - oct */ - rv = DH_Derive(&dhPublic, &dhPrime, &dhValue, &derived, keySize); - - PORT_Free(dhPrime.data); - PORT_Free(dhValue.data); - - if (rv == SECSuccess) { - sftk_forceAttribute(key, CKA_VALUE, derived.data, derived.len); - PORT_ZFree(derived.data, derived.len); - } else - crv = CKR_HOST_MEMORY; - - break; - } + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); + break; + case CKM_MD5_KEY_DERIVATION: + if (keySize == 0) + keySize = MD5_LENGTH; + if (keySize > MD5_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + MD5_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); -#ifndef NSS_DISABLE_ECC - case CKM_ECDH1_DERIVE: - case CKM_ECDH1_COFACTOR_DERIVE: - { - SECItem ecScalar, ecPoint; - SECItem tmp; - PRBool withCofactor = PR_FALSE; - unsigned char *secret; - unsigned char *keyData = NULL; - unsigned int secretlen, curveLen, pubKeyLen; - CK_ECDH1_DERIVE_PARAMS *mechParams; - NSSLOWKEYPrivateKey *privKey; - PLArenaPool *arena = NULL; - - /* Check mechanism parameters */ - mechParams = (CK_ECDH1_DERIVE_PARAMS *) pMechanism->pParameter; - if ((pMechanism->ulParameterLen != sizeof(CK_ECDH1_DERIVE_PARAMS)) || - ((mechParams->kdf == CKD_NULL) && - ((mechParams->ulSharedDataLen != 0) || - (mechParams->pSharedData != NULL)))) { - crv = CKR_MECHANISM_PARAM_INVALID; - break; - } - - privKey = sftk_GetPrivKey(sourceKey, CKK_EC, &crv); - if (privKey == NULL) { - break; - } - - /* Now we are working with a non-NULL private key */ - SECITEM_CopyItem(NULL, &ecScalar, &privKey->u.ec.privateValue); - - ecPoint.data = mechParams->pPublicData; - ecPoint.len = mechParams->ulPublicDataLen; - - curveLen = (privKey->u.ec.ecParams.fieldID.size +7)/8; - pubKeyLen = (2*curveLen) + 1; - - /* if the len is too small, can't be a valid point */ - if (ecPoint.len < pubKeyLen) { - goto ec_loser; - } - /* if the len is too large, must be an encoded point (length is - * equal case just falls through */ - if (ecPoint.len > pubKeyLen) { - SECItem newPoint; - - arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); - if (arena == NULL) { - goto ec_loser; - } - - rv = SEC_QuickDERDecodeItem(arena, &newPoint, - SEC_ASN1_GET(SEC_OctetStringTemplate), - &ecPoint); - if (rv != SECSuccess) { - goto ec_loser; - } - ecPoint = newPoint; - } - - if (mechanism == CKM_ECDH1_COFACTOR_DERIVE) { - withCofactor = PR_TRUE; - } else { - /* When not using cofactor derivation, one should - * validate the public key to avoid small subgroup - * attacks. - */ - if (EC_ValidatePublicKey(&privKey->u.ec.ecParams, &ecPoint) - != SECSuccess) { - goto ec_loser; - } - } - - rv = ECDH_Derive(&ecPoint, &privKey->u.ec.ecParams, &ecScalar, - withCofactor, &tmp); - PORT_Free(ecScalar.data); - ecScalar.data = NULL; - if (privKey != sourceKey->objectInfo) { - nsslowkey_DestroyPrivateKey(privKey); - privKey=NULL; - } - if (arena) { - PORT_FreeArena(arena,PR_FALSE); - arena=NULL; - } - - if (rv != SECSuccess) { - crv = sftk_MapCryptError(PORT_GetError()); - break; - } - - - /* - * apply the kdf function. - */ - if (mechParams->kdf == CKD_NULL) { - /* - * tmp is the raw data created by ECDH_Derive, - * secret and secretlen are the values we will - * eventually pass as our generated key. - */ - secret = tmp.data; - secretlen = tmp.len; - } else { - secretlen = keySize; - crv = sftk_ANSI_X9_63_kdf(&secret, keySize, - &tmp, mechParams->pSharedData, - mechParams->ulSharedDataLen, mechParams->kdf); - PORT_ZFree(tmp.data, tmp.len); - if (crv != CKR_OK) { - break; - } - tmp.data = secret; - tmp.len = secretlen; - } - - /* - * if keySize is supplied, then we are generating a key of a specific - * length. This is done by taking the least significant 'keySize' - * bytes from the unsigned value calculated by ECDH. Note: this may - * mean padding temp with extra leading zeros from what ECDH_Derive - * already returned (which itself may contain leading zeros). - */ - if (keySize) { - if (secretlen < keySize) { - keyData = PORT_ZAlloc(keySize); - if (!keyData) { - PORT_ZFree(tmp.data, tmp.len); - crv = CKR_HOST_MEMORY; - break; - } - PORT_Memcpy(&keyData[keySize-secretlen],secret,secretlen); - secret = keyData; - } else { - secret += (secretlen - keySize); - } - secretlen = keySize; - } - - sftk_forceAttribute(key, CKA_VALUE, secret, secretlen); - PORT_ZFree(tmp.data, tmp.len); - if (keyData) { - PORT_ZFree(keyData, keySize); - } - break; - -ec_loser: - crv = CKR_ARGUMENTS_BAD; - PORT_Free(ecScalar.data); - if (privKey != sourceKey->objectInfo) - nsslowkey_DestroyPrivateKey(privKey); - if (arena) { - PORT_FreeArena(arena, PR_FALSE); - } - break; - - } -#endif /* NSS_DISABLE_ECC */ + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); + break; + case CKM_SHA1_KEY_DERIVATION: + if (keySize == 0) + keySize = SHA1_LENGTH; + if (keySize > SHA1_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + SHA1_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); - /* See RFC 5869 and CK_NSS_HKDFParams for documentation. */ - case CKM_NSS_HKDF_SHA1: hashType = HASH_AlgSHA1; goto hkdf; - case CKM_NSS_HKDF_SHA256: hashType = HASH_AlgSHA256; goto hkdf; - case CKM_NSS_HKDF_SHA384: hashType = HASH_AlgSHA384; goto hkdf; - case CKM_NSS_HKDF_SHA512: hashType = HASH_AlgSHA512; goto hkdf; -hkdf: { - const CK_NSS_HKDFParams * params = - (const CK_NSS_HKDFParams *) pMechanism->pParameter; - const SECHashObject * rawHash; - unsigned hashLen; - CK_BYTE buf[HASH_LENGTH_MAX]; - CK_BYTE * prk; /* psuedo-random key */ - CK_ULONG prkLen; - CK_BYTE * okm; /* output keying material */ - - rawHash = HASH_GetRawHashObject(hashType); - if (rawHash == NULL || rawHash->length > sizeof buf) { - crv = CKR_FUNCTION_FAILED; + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); break; - } - hashLen = rawHash->length; - if (pMechanism->ulParameterLen != sizeof(CK_NSS_HKDFParams) || - !params || (!params->bExpand && !params->bExtract) || - (params->bExtract && params->ulSaltLen > 0 && !params->pSalt) || - (params->bExpand && params->ulInfoLen > 0 && !params->pInfo)) { - crv = CKR_MECHANISM_PARAM_INVALID; + case CKM_SHA224_KEY_DERIVATION: + if (keySize == 0) + keySize = SHA224_LENGTH; + if (keySize > SHA224_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + SHA224_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); break; - } - if (keySize == 0 || keySize > sizeof key_block || - (!params->bExpand && keySize > hashLen) || - (params->bExpand && keySize > 255 * hashLen)) { - crv = CKR_TEMPLATE_INCONSISTENT; + + case CKM_SHA256_KEY_DERIVATION: + if (keySize == 0) + keySize = SHA256_LENGTH; + if (keySize > SHA256_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + SHA256_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); break; - } - crv = sftk_DeriveSensitiveCheck(sourceKey, key); - if (crv != CKR_OK) + + case CKM_SHA384_KEY_DERIVATION: + if (keySize == 0) + keySize = SHA384_LENGTH; + if (keySize > SHA384_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + SHA384_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); break; - /* HKDF-Extract(salt, base key value) */ - if (params->bExtract) { - CK_BYTE * salt; - CK_ULONG saltLen; - HMACContext * hmac; - unsigned int bufLen; + case CKM_SHA512_KEY_DERIVATION: + if (keySize == 0) + keySize = SHA512_LENGTH; + if (keySize > SHA512_LENGTH) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } + SHA512_HashBuf(key_block, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + + crv = sftk_forceAttribute(key, CKA_VALUE, key_block, keySize); + break; - salt = params->pSalt; - saltLen = params->ulSaltLen; - if (salt == NULL) { - saltLen = hashLen; - salt = buf; - memset(salt, 0, saltLen); + case CKM_DH_PKCS_DERIVE: { + SECItem derived, dhPublic; + SECItem dhPrime, dhValue; + /* sourceKey - values for the local existing low key */ + /* get prime and value attributes */ + crv = sftk_Attribute2SecItem(NULL, &dhPrime, sourceKey, CKA_PRIME); + if (crv != SECSuccess) + break; + crv = sftk_Attribute2SecItem(NULL, &dhValue, sourceKey, CKA_VALUE); + if (crv != SECSuccess) { + PORT_Free(dhPrime.data); + break; } - hmac = HMAC_Create(rawHash, salt, saltLen, isFIPS); - if (!hmac) { + + dhPublic.data = pMechanism->pParameter; + dhPublic.len = pMechanism->ulParameterLen; + + /* calculate private value - oct */ + rv = DH_Derive(&dhPublic, &dhPrime, &dhValue, &derived, keySize); + + PORT_Free(dhPrime.data); + PORT_Free(dhValue.data); + + if (rv == SECSuccess) { + sftk_forceAttribute(key, CKA_VALUE, derived.data, derived.len); + PORT_ZFree(derived.data, derived.len); + } else crv = CKR_HOST_MEMORY; + + break; + } + +#ifndef NSS_DISABLE_ECC + case CKM_ECDH1_DERIVE: + case CKM_ECDH1_COFACTOR_DERIVE: { + SECItem ecScalar, ecPoint; + SECItem tmp; + PRBool withCofactor = PR_FALSE; + unsigned char *secret; + unsigned char *keyData = NULL; + unsigned int secretlen, pubKeyLen; + CK_ECDH1_DERIVE_PARAMS *mechParams; + NSSLOWKEYPrivateKey *privKey; + PLArenaPool *arena = NULL; + + /* Check mechanism parameters */ + mechParams = (CK_ECDH1_DERIVE_PARAMS *)pMechanism->pParameter; + if ((pMechanism->ulParameterLen != sizeof(CK_ECDH1_DERIVE_PARAMS)) || + ((mechParams->kdf == CKD_NULL) && + ((mechParams->ulSharedDataLen != 0) || + (mechParams->pSharedData != NULL)))) { + crv = CKR_MECHANISM_PARAM_INVALID; break; } - HMAC_Begin(hmac); - HMAC_Update(hmac, (const unsigned char*) att->attrib.pValue, - att->attrib.ulValueLen); - HMAC_Finish(hmac, buf, &bufLen, sizeof(buf)); - HMAC_Destroy(hmac, PR_TRUE); - PORT_Assert(bufLen == rawHash->length); - prk = buf; - prkLen = bufLen; - } else { - /* PRK = base key value */ - prk = (CK_BYTE*) att->attrib.pValue; - prkLen = att->attrib.ulValueLen; - } - - /* HKDF-Expand */ - if (!params->bExpand) { - okm = prk; - } else { - /* T(1) = HMAC-Hash(prk, "" | info | 0x01) - * T(n) = HMAC-Hash(prk, T(n-1) | info | n - * key material = T(1) | ... | T(n) - */ - HMACContext * hmac; - CK_BYTE i; - unsigned iterations = PR_ROUNDUP(keySize, hashLen) / hashLen; - hmac = HMAC_Create(rawHash, prk, prkLen, isFIPS); - if (hmac == NULL) { - crv = CKR_HOST_MEMORY; + + privKey = sftk_GetPrivKey(sourceKey, CKK_EC, &crv); + if (privKey == NULL) { break; } - for (i = 1; i <= iterations; ++i) { - unsigned len; - HMAC_Begin(hmac); - if (i > 1) { - HMAC_Update(hmac, key_block + ((i-2) * hashLen), hashLen); + + /* Now we are working with a non-NULL private key */ + SECITEM_CopyItem(NULL, &ecScalar, &privKey->u.ec.privateValue); + + ecPoint.data = mechParams->pPublicData; + ecPoint.len = mechParams->ulPublicDataLen; + + pubKeyLen = privKey->u.ec.ecParams.pointSize; + + /* if the len is too small, can't be a valid point */ + if (ecPoint.len < pubKeyLen) { + goto ec_loser; + } + /* if the len is too large, must be an encoded point (length is + * equal case just falls through */ + if (ecPoint.len > pubKeyLen) { + SECItem newPoint; + + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (arena == NULL) { + goto ec_loser; } - if (params->ulInfoLen != 0) { - HMAC_Update(hmac, params->pInfo, params->ulInfoLen); + + rv = SEC_QuickDERDecodeItem(arena, &newPoint, + SEC_ASN1_GET(SEC_OctetStringTemplate), + &ecPoint); + if (rv != SECSuccess) { + goto ec_loser; } - HMAC_Update(hmac, &i, 1); - HMAC_Finish(hmac, key_block + ((i-1) * hashLen), &len, - hashLen); - PORT_Assert(len == hashLen); + ecPoint = newPoint; } - HMAC_Destroy(hmac, PR_TRUE); - okm = key_block; + + if (mechanism == CKM_ECDH1_COFACTOR_DERIVE) { + withCofactor = PR_TRUE; + } else { + /* When not using cofactor derivation, one should + * validate the public key to avoid small subgroup + * attacks. + */ + if (EC_ValidatePublicKey(&privKey->u.ec.ecParams, &ecPoint) != SECSuccess) { + goto ec_loser; + } + } + + rv = ECDH_Derive(&ecPoint, &privKey->u.ec.ecParams, &ecScalar, + withCofactor, &tmp); + PORT_Free(ecScalar.data); + ecScalar.data = NULL; + if (privKey != sourceKey->objectInfo) { + nsslowkey_DestroyPrivateKey(privKey); + privKey = NULL; + } + if (arena) { + PORT_FreeArena(arena, PR_FALSE); + arena = NULL; + } + + if (rv != SECSuccess) { + crv = sftk_MapCryptError(PORT_GetError()); + break; + } + + /* + * apply the kdf function. + */ + if (mechParams->kdf == CKD_NULL) { + /* + * tmp is the raw data created by ECDH_Derive, + * secret and secretlen are the values we will + * eventually pass as our generated key. + */ + secret = tmp.data; + secretlen = tmp.len; + } else { + secretlen = keySize; + crv = sftk_ANSI_X9_63_kdf(&secret, keySize, + &tmp, mechParams->pSharedData, + mechParams->ulSharedDataLen, mechParams->kdf); + PORT_ZFree(tmp.data, tmp.len); + if (crv != CKR_OK) { + break; + } + tmp.data = secret; + tmp.len = secretlen; + } + + /* + * if keySize is supplied, then we are generating a key of a specific + * length. This is done by taking the least significant 'keySize' + * bytes from the unsigned value calculated by ECDH. Note: this may + * mean padding temp with extra leading zeros from what ECDH_Derive + * already returned (which itself may contain leading zeros). + */ + if (keySize) { + if (secretlen < keySize) { + keyData = PORT_ZAlloc(keySize); + if (!keyData) { + PORT_ZFree(tmp.data, tmp.len); + crv = CKR_HOST_MEMORY; + break; + } + PORT_Memcpy(&keyData[keySize - secretlen], secret, secretlen); + secret = keyData; + } else { + secret += (secretlen - keySize); + } + secretlen = keySize; + } + + sftk_forceAttribute(key, CKA_VALUE, secret, secretlen); + PORT_ZFree(tmp.data, tmp.len); + if (keyData) { + PORT_ZFree(keyData, keySize); + } + break; + + ec_loser: + crv = CKR_ARGUMENTS_BAD; + PORT_Free(ecScalar.data); + if (privKey != sourceKey->objectInfo) + nsslowkey_DestroyPrivateKey(privKey); + if (arena) { + PORT_FreeArena(arena, PR_FALSE); + } + break; } - /* key material = prk */ - crv = sftk_forceAttribute(key, CKA_VALUE, okm, keySize); - break; - } /* end of CKM_NSS_HKDF_* */ - - case CKM_NSS_JPAKE_ROUND2_SHA1: hashType = HASH_AlgSHA1; goto jpake2; - case CKM_NSS_JPAKE_ROUND2_SHA256: hashType = HASH_AlgSHA256; goto jpake2; - case CKM_NSS_JPAKE_ROUND2_SHA384: hashType = HASH_AlgSHA384; goto jpake2; - case CKM_NSS_JPAKE_ROUND2_SHA512: hashType = HASH_AlgSHA512; goto jpake2; -jpake2: - if (pMechanism->pParameter == NULL || - pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKERound2Params)) - crv = CKR_MECHANISM_PARAM_INVALID; - if (crv == CKR_OK && sftk_isTrue(key, CKA_TOKEN)) - crv = CKR_TEMPLATE_INCONSISTENT; - if (crv == CKR_OK) +#endif /* NSS_DISABLE_ECC */ + + /* See RFC 5869 and CK_NSS_HKDFParams for documentation. */ + case CKM_NSS_HKDF_SHA1: + hashType = HASH_AlgSHA1; + goto hkdf; + case CKM_NSS_HKDF_SHA256: + hashType = HASH_AlgSHA256; + goto hkdf; + case CKM_NSS_HKDF_SHA384: + hashType = HASH_AlgSHA384; + goto hkdf; + case CKM_NSS_HKDF_SHA512: + hashType = HASH_AlgSHA512; + goto hkdf; + hkdf : { + const CK_NSS_HKDFParams *params = + (const CK_NSS_HKDFParams *)pMechanism->pParameter; + const SECHashObject *rawHash; + unsigned hashLen; + CK_BYTE buf[HASH_LENGTH_MAX]; + CK_BYTE *prk; /* psuedo-random key */ + CK_ULONG prkLen; + CK_BYTE *okm; /* output keying material */ + + rawHash = HASH_GetRawHashObject(hashType); + if (rawHash == NULL || rawHash->length > sizeof buf) { + crv = CKR_FUNCTION_FAILED; + break; + } + hashLen = rawHash->length; + + if (pMechanism->ulParameterLen != sizeof(CK_NSS_HKDFParams) || + !params || (!params->bExpand && !params->bExtract) || + (params->bExtract && params->ulSaltLen > 0 && !params->pSalt) || + (params->bExpand && params->ulInfoLen > 0 && !params->pInfo)) { + crv = CKR_MECHANISM_PARAM_INVALID; + break; + } + if (keySize == 0 || keySize > sizeof key_block || + (!params->bExpand && keySize > hashLen) || + (params->bExpand && keySize > 255 * hashLen)) { + crv = CKR_TEMPLATE_INCONSISTENT; + break; + } crv = sftk_DeriveSensitiveCheck(sourceKey, key); - if (crv == CKR_OK) - crv = jpake_Round2(hashType, - (CK_NSS_JPAKERound2Params *) pMechanism->pParameter, - sourceKey, key); - break; + if (crv != CKR_OK) + break; - case CKM_NSS_JPAKE_FINAL_SHA1: hashType = HASH_AlgSHA1; goto jpakeFinal; - case CKM_NSS_JPAKE_FINAL_SHA256: hashType = HASH_AlgSHA256; goto jpakeFinal; - case CKM_NSS_JPAKE_FINAL_SHA384: hashType = HASH_AlgSHA384; goto jpakeFinal; - case CKM_NSS_JPAKE_FINAL_SHA512: hashType = HASH_AlgSHA512; goto jpakeFinal; -jpakeFinal: - if (pMechanism->pParameter == NULL || - pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKEFinalParams)) - crv = CKR_MECHANISM_PARAM_INVALID; - /* We purposely do not do the derive sensitivity check; we want to be - able to derive non-sensitive keys while allowing the ROUND1 and - ROUND2 keys to be sensitive (which they always are, since they are - in the CKO_PRIVATE_KEY class). The caller must include CKA_SENSITIVE - in the template in order for the resultant keyblock key to be - sensitive. - */ - if (crv == CKR_OK) - crv = jpake_Final(hashType, - (CK_NSS_JPAKEFinalParams *) pMechanism->pParameter, - sourceKey, key); - break; + /* HKDF-Extract(salt, base key value) */ + if (params->bExtract) { + CK_BYTE *salt; + CK_ULONG saltLen; + HMACContext *hmac; + unsigned int bufLen; + + salt = params->pSalt; + saltLen = params->ulSaltLen; + if (salt == NULL) { + saltLen = hashLen; + salt = buf; + memset(salt, 0, saltLen); + } + hmac = HMAC_Create(rawHash, salt, saltLen, isFIPS); + if (!hmac) { + crv = CKR_HOST_MEMORY; + break; + } + HMAC_Begin(hmac); + HMAC_Update(hmac, (const unsigned char *)att->attrib.pValue, + att->attrib.ulValueLen); + HMAC_Finish(hmac, buf, &bufLen, sizeof(buf)); + HMAC_Destroy(hmac, PR_TRUE); + PORT_Assert(bufLen == rawHash->length); + prk = buf; + prkLen = bufLen; + } else { + /* PRK = base key value */ + prk = (CK_BYTE *)att->attrib.pValue; + prkLen = att->attrib.ulValueLen; + } + + /* HKDF-Expand */ + if (!params->bExpand) { + okm = prk; + } else { + /* T(1) = HMAC-Hash(prk, "" | info | 0x01) + * T(n) = HMAC-Hash(prk, T(n-1) | info | n + * key material = T(1) | ... | T(n) + */ + HMACContext *hmac; + CK_BYTE i; + unsigned iterations = PR_ROUNDUP(keySize, hashLen) / hashLen; + hmac = HMAC_Create(rawHash, prk, prkLen, isFIPS); + if (hmac == NULL) { + crv = CKR_HOST_MEMORY; + break; + } + for (i = 1; i <= iterations; ++i) { + unsigned len; + HMAC_Begin(hmac); + if (i > 1) { + HMAC_Update(hmac, key_block + ((i - 2) * hashLen), hashLen); + } + if (params->ulInfoLen != 0) { + HMAC_Update(hmac, params->pInfo, params->ulInfoLen); + } + HMAC_Update(hmac, &i, 1); + HMAC_Finish(hmac, key_block + ((i - 1) * hashLen), &len, + hashLen); + PORT_Assert(len == hashLen); + } + HMAC_Destroy(hmac, PR_TRUE); + okm = key_block; + } + /* key material = prk */ + crv = sftk_forceAttribute(key, CKA_VALUE, okm, keySize); + break; + } /* end of CKM_NSS_HKDF_* */ + + case CKM_NSS_JPAKE_ROUND2_SHA1: + hashType = HASH_AlgSHA1; + goto jpake2; + case CKM_NSS_JPAKE_ROUND2_SHA256: + hashType = HASH_AlgSHA256; + goto jpake2; + case CKM_NSS_JPAKE_ROUND2_SHA384: + hashType = HASH_AlgSHA384; + goto jpake2; + case CKM_NSS_JPAKE_ROUND2_SHA512: + hashType = HASH_AlgSHA512; + goto jpake2; + jpake2: + if (pMechanism->pParameter == NULL || + pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKERound2Params)) + crv = CKR_MECHANISM_PARAM_INVALID; + if (crv == CKR_OK && sftk_isTrue(key, CKA_TOKEN)) + crv = CKR_TEMPLATE_INCONSISTENT; + if (crv == CKR_OK) + crv = sftk_DeriveSensitiveCheck(sourceKey, key); + if (crv == CKR_OK) + crv = jpake_Round2(hashType, + (CK_NSS_JPAKERound2Params *)pMechanism->pParameter, + sourceKey, key); + break; + + case CKM_NSS_JPAKE_FINAL_SHA1: + hashType = HASH_AlgSHA1; + goto jpakeFinal; + case CKM_NSS_JPAKE_FINAL_SHA256: + hashType = HASH_AlgSHA256; + goto jpakeFinal; + case CKM_NSS_JPAKE_FINAL_SHA384: + hashType = HASH_AlgSHA384; + goto jpakeFinal; + case CKM_NSS_JPAKE_FINAL_SHA512: + hashType = HASH_AlgSHA512; + goto jpakeFinal; + jpakeFinal: + if (pMechanism->pParameter == NULL || + pMechanism->ulParameterLen != sizeof(CK_NSS_JPAKEFinalParams)) + crv = CKR_MECHANISM_PARAM_INVALID; + /* We purposely do not do the derive sensitivity check; we want to be + able to derive non-sensitive keys while allowing the ROUND1 and + ROUND2 keys to be sensitive (which they always are, since they are + in the CKO_PRIVATE_KEY class). The caller must include CKA_SENSITIVE + in the template in order for the resultant keyblock key to be + sensitive. + */ + if (crv == CKR_OK) + crv = jpake_Final(hashType, + (CK_NSS_JPAKEFinalParams *)pMechanism->pParameter, + sourceKey, key); + break; - default: - crv = CKR_MECHANISM_INVALID; + default: + crv = CKR_MECHANISM_INVALID; } if (att) { sftk_FreeAttribute(att); } sftk_FreeObject(sourceKey); - if (crv != CKR_OK) { - if (key) sftk_FreeObject(key); - return crv; + if (crv != CKR_OK) { + if (key) + sftk_FreeObject(key); + return crv; } /* link the key object into the list */ if (key) { - SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); - PORT_Assert(sessKey); - /* get the session */ - sessKey->wasDerived = PR_TRUE; - session = sftk_SessionFromHandle(hSession); - if (session == NULL) { - sftk_FreeObject(key); - return CKR_HOST_MEMORY; - } - - crv = sftk_handleObject(key,session); - sftk_FreeSession(session); - *phKey = key->handle; - sftk_FreeObject(key); + SFTKSessionObject *sessKey = sftk_narrowToSessionObject(key); + PORT_Assert(sessKey); + /* get the session */ + sessKey->wasDerived = PR_TRUE; + session = sftk_SessionFromHandle(hSession); + if (session == NULL) { + sftk_FreeObject(key); + return CKR_HOST_MEMORY; + } + + crv = sftk_handleObject(key, session); + sftk_FreeSession(session); + *phKey = key->handle; + sftk_FreeObject(key); } return crv; } - -/* NSC_GetFunctionStatus obtains an updated status of a function running +/* NSC_GetFunctionStatus obtains an updated status of a function running * in parallel with an application. */ -CK_RV NSC_GetFunctionStatus(CK_SESSION_HANDLE hSession) +CK_RV +NSC_GetFunctionStatus(CK_SESSION_HANDLE hSession) { CHECK_FORK(); @@ -7253,20 +7558,22 @@ CK_RV NSC_GetFunctionStatus(CK_SESSION_HANDLE hSession) } /* NSC_CancelFunction cancels a function running in parallel */ -CK_RV NSC_CancelFunction(CK_SESSION_HANDLE hSession) +CK_RV +NSC_CancelFunction(CK_SESSION_HANDLE hSession) { CHECK_FORK(); return CKR_FUNCTION_NOT_PARALLEL; } -/* NSC_GetOperationState saves the state of the cryptographic - *operation in a session. +/* NSC_GetOperationState saves the state of the cryptographic + * operation in a session. * NOTE: This code only works for digest functions for now. eventually need * to add full flatten/resurect to our state stuff so that all types of state * can be saved */ -CK_RV NSC_GetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) +CK_RV +NSC_GetOperationState(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) { SFTKSessionContext *context; SFTKSession *session; @@ -7277,39 +7584,38 @@ CK_RV NSC_GetOperationState(CK_SESSION_HANDLE hSession, /* make sure we're legal */ crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_TRUE, &session); - if (crv != CKR_OK) return crv; + if (crv != CKR_OK) + return crv; - *pulOperationStateLen = context->cipherInfoLen + sizeof(CK_MECHANISM_TYPE) - + sizeof(SFTKContextType); + *pulOperationStateLen = context->cipherInfoLen + sizeof(CK_MECHANISM_TYPE) + sizeof(SFTKContextType); if (pOperationState == NULL) { sftk_FreeSession(session); - return CKR_OK; + return CKR_OK; } else { - if (pOSLen < *pulOperationStateLen) { - return CKR_BUFFER_TOO_SMALL; - } + if (pOSLen < *pulOperationStateLen) { + return CKR_BUFFER_TOO_SMALL; + } } - PORT_Memcpy(pOperationState,&context->type,sizeof(SFTKContextType)); + PORT_Memcpy(pOperationState, &context->type, sizeof(SFTKContextType)); pOperationState += sizeof(SFTKContextType); - PORT_Memcpy(pOperationState,&context->currentMech, - sizeof(CK_MECHANISM_TYPE)); + PORT_Memcpy(pOperationState, &context->currentMech, + sizeof(CK_MECHANISM_TYPE)); pOperationState += sizeof(CK_MECHANISM_TYPE); - PORT_Memcpy(pOperationState,context->cipherInfo,context->cipherInfoLen); + PORT_Memcpy(pOperationState, context->cipherInfo, context->cipherInfoLen); sftk_FreeSession(session); return CKR_OK; } +#define sftk_Decrement(stateSize, len) \ + stateSize = ((stateSize) > (CK_ULONG)(len)) ? ((stateSize) - (CK_ULONG)(len)) : 0; -#define sftk_Decrement(stateSize,len) \ - stateSize = ((stateSize) > (CK_ULONG)(len)) ? \ - ((stateSize) - (CK_ULONG)(len)) : 0; - -/* NSC_SetOperationState restores the state of the cryptographic +/* NSC_SetOperationState restores the state of the cryptographic * operation in a session. This is coded like it can restore lots of * states, but it only works for truly flat cipher structures. */ -CK_RV NSC_SetOperationState(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, - CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) +CK_RV +NSC_SetOperationState(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, + CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) { SFTKSessionContext *context; SFTKSession *session; @@ -7320,122 +7626,130 @@ CK_RV NSC_SetOperationState(CK_SESSION_HANDLE hSession, CHECK_FORK(); while (ulOperationStateLen != 0) { - /* get what type of state we're dealing with... */ - PORT_Memcpy(&type,pOperationState, sizeof(SFTKContextType)); - - /* fix up session contexts based on type */ - session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; - context = sftk_ReturnContextByType(session, type); - sftk_SetContextByType(session, type, NULL); - if (context) { - sftk_FreeContext(context); - } - pOperationState += sizeof(SFTKContextType); - sftk_Decrement(ulOperationStateLen,sizeof(SFTKContextType)); - - - /* get the mechanism structure */ - PORT_Memcpy(&mech.mechanism,pOperationState,sizeof(CK_MECHANISM_TYPE)); - pOperationState += sizeof(CK_MECHANISM_TYPE); - sftk_Decrement(ulOperationStateLen, sizeof(CK_MECHANISM_TYPE)); - /* should be filled in... but not necessary for hash */ - mech.pParameter = NULL; - mech.ulParameterLen = 0; - switch (type) { - case SFTK_HASH: - crv = NSC_DigestInit(hSession,&mech); - if (crv != CKR_OK) break; - crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_TRUE, - NULL); - if (crv != CKR_OK) break; - PORT_Memcpy(context->cipherInfo,pOperationState, - context->cipherInfoLen); - pOperationState += context->cipherInfoLen; - sftk_Decrement(ulOperationStateLen,context->cipherInfoLen); - break; - default: - /* do sign/encrypt/decrypt later */ - crv = CKR_SAVED_STATE_INVALID; - } - sftk_FreeSession(session); - if (crv != CKR_OK) break; + /* get what type of state we're dealing with... */ + PORT_Memcpy(&type, pOperationState, sizeof(SFTKContextType)); + + /* fix up session contexts based on type */ + session = sftk_SessionFromHandle(hSession); + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; + context = sftk_ReturnContextByType(session, type); + sftk_SetContextByType(session, type, NULL); + if (context) { + sftk_FreeContext(context); + } + pOperationState += sizeof(SFTKContextType); + sftk_Decrement(ulOperationStateLen, sizeof(SFTKContextType)); + + /* get the mechanism structure */ + PORT_Memcpy(&mech.mechanism, pOperationState, sizeof(CK_MECHANISM_TYPE)); + pOperationState += sizeof(CK_MECHANISM_TYPE); + sftk_Decrement(ulOperationStateLen, sizeof(CK_MECHANISM_TYPE)); + /* should be filled in... but not necessary for hash */ + mech.pParameter = NULL; + mech.ulParameterLen = 0; + switch (type) { + case SFTK_HASH: + crv = NSC_DigestInit(hSession, &mech); + if (crv != CKR_OK) + break; + crv = sftk_GetContext(hSession, &context, SFTK_HASH, PR_TRUE, + NULL); + if (crv != CKR_OK) + break; + PORT_Memcpy(context->cipherInfo, pOperationState, + context->cipherInfoLen); + pOperationState += context->cipherInfoLen; + sftk_Decrement(ulOperationStateLen, context->cipherInfoLen); + break; + default: + /* do sign/encrypt/decrypt later */ + crv = CKR_SAVED_STATE_INVALID; + } + sftk_FreeSession(session); + if (crv != CKR_OK) + break; } return crv; } /* Dual-function cryptographic operations */ -/* NSC_DigestEncryptUpdate continues a multiple-part digesting and encryption +/* NSC_DigestEncryptUpdate continues a multiple-part digesting and encryption * operation. */ -CK_RV NSC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) +CK_RV +NSC_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { CK_RV crv; CHECK_FORK(); - crv = NSC_EncryptUpdate(hSession,pPart,ulPartLen, pEncryptedPart, - pulEncryptedPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_DigestUpdate(hSession,pPart,ulPartLen); + crv = NSC_EncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, + pulEncryptedPartLen); + if (crv != CKR_OK) + return crv; + crv = NSC_DigestUpdate(hSession, pPart, ulPartLen); return crv; } - -/* NSC_DecryptDigestUpdate continues a multiple-part decryption and +/* NSC_DecryptDigestUpdate continues a multiple-part decryption and * digesting operation. */ -CK_RV NSC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, - CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) +CK_RV +NSC_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, + CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { CK_RV crv; CHECK_FORK(); - crv = NSC_DecryptUpdate(hSession,pEncryptedPart, ulEncryptedPartLen, - pPart, pulPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_DigestUpdate(hSession,pPart,*pulPartLen); + crv = NSC_DecryptUpdate(hSession, pEncryptedPart, ulEncryptedPartLen, + pPart, pulPartLen); + if (crv != CKR_OK) + return crv; + crv = NSC_DigestUpdate(hSession, pPart, *pulPartLen); return crv; } - -/* NSC_SignEncryptUpdate continues a multiple-part signing and +/* NSC_SignEncryptUpdate continues a multiple-part signing and * encryption operation. */ -CK_RV NSC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, - CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, - CK_ULONG_PTR pulEncryptedPartLen) +CK_RV +NSC_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, + CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, + CK_ULONG_PTR pulEncryptedPartLen) { CK_RV crv; CHECK_FORK(); - crv = NSC_EncryptUpdate(hSession,pPart,ulPartLen, pEncryptedPart, - pulEncryptedPartLen); - if (crv != CKR_OK) return crv; - crv = NSC_SignUpdate(hSession,pPart,ulPartLen); + crv = NSC_EncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, + pulEncryptedPartLen); + if (crv != CKR_OK) + return crv; + crv = NSC_SignUpdate(hSession, pPart, ulPartLen); return crv; } - -/* NSC_DecryptVerifyUpdate continues a multiple-part decryption +/* NSC_DecryptVerifyUpdate continues a multiple-part decryption * and verify operation. */ -CK_RV NSC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, - CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, - CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) +CK_RV +NSC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, + CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, + CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { CK_RV crv; CHECK_FORK(); - crv = NSC_DecryptUpdate(hSession,pEncryptedData, ulEncryptedDataLen, - pData, pulDataLen); - if (crv != CKR_OK) return crv; + crv = NSC_DecryptUpdate(hSession, pEncryptedData, ulEncryptedDataLen, + pData, pulDataLen); + if (crv != CKR_OK) + return crv; crv = NSC_VerifyUpdate(hSession, pData, *pulDataLen); return crv; @@ -7444,7 +7758,8 @@ CK_RV NSC_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, /* NSC_DigestKey continues a multi-part message-digesting operation, * by digesting the value of a secret key as part of the data already digested. */ -CK_RV NSC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) +CK_RV +NSC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { SFTKSession *session = NULL; SFTKObject *key = NULL; @@ -7454,27 +7769,29 @@ CK_RV NSC_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) CHECK_FORK(); session = sftk_SessionFromHandle(hSession); - if (session == NULL) return CKR_SESSION_HANDLE_INVALID; + if (session == NULL) + return CKR_SESSION_HANDLE_INVALID; - key = sftk_ObjectFromHandle(hKey,session); + key = sftk_ObjectFromHandle(hKey, session); sftk_FreeSession(session); - if (key == NULL) return CKR_KEY_HANDLE_INVALID; + if (key == NULL) + return CKR_KEY_HANDLE_INVALID; /* PUT ANY DIGEST KEY RESTRICTION CHECKS HERE */ /* make sure it's a valid key for this operation */ if (key->objclass != CKO_SECRET_KEY) { - sftk_FreeObject(key); - return CKR_KEY_TYPE_INCONSISTENT; + sftk_FreeObject(key); + return CKR_KEY_TYPE_INCONSISTENT; } /* get the key value */ - att = sftk_FindAttribute(key,CKA_VALUE); + att = sftk_FindAttribute(key, CKA_VALUE); sftk_FreeObject(key); if (!att) { - return CKR_KEY_HANDLE_INVALID; + return CKR_KEY_HANDLE_INVALID; } - crv = NSC_DigestUpdate(hSession,(CK_BYTE_PTR)att->attrib.pValue, - att->attrib.ulValueLen); + crv = NSC_DigestUpdate(hSession, (CK_BYTE_PTR)att->attrib.pValue, + att->attrib.ulValueLen); sftk_FreeAttribute(att); return crv; } diff --git a/nss/lib/softoken/pkcs11i.h b/nss/lib/softoken/pkcs11i.h index 1023a00..c5f21c3 100644 --- a/nss/lib/softoken/pkcs11i.h +++ b/nss/lib/softoken/pkcs11i.h @@ -10,14 +10,15 @@ #include "nssilock.h" #include "seccomon.h" #include "secoidt.h" -#include "lowkeyti.h" +#include "lowkeyti.h" #include "pkcs11t.h" -#include "sftkdbt.h" +#include "sftkdbt.h" +#include "chacha20poly1305.h" #include "hasht.h" -/* - * Configuration Defines +/* + * Configuration Defines * * The following defines affect the space verse speed trade offs of * the PKCS #11 module. For the most part the current settings are optimized @@ -25,24 +26,24 @@ * the expense of space. */ -/* +/* * The attribute allocation strategy is static allocation: * Attributes are pre-allocated as part of the session object and used from * the object array. */ -#define MAX_OBJS_ATTRS 45 /* number of attributes to preallocate in - * the object (must me the absolute max) */ -#define ATTR_SPACE 50 /* Maximum size of attribute data before extra - * data needs to be allocated. This is set to - * enough space to hold an SSL MASTER secret */ - -#define NSC_STRICT PR_FALSE /* forces the code to do strict template - * matching when doing C_FindObject on token - * objects. This will slow down search in - * NSS. */ +#define MAX_OBJS_ATTRS 45 /* number of attributes to preallocate in \ + * the object (must me the absolute max) */ +#define ATTR_SPACE 50 /* Maximum size of attribute data before extra \ + * data needs to be allocated. This is set to \ + * enough space to hold an SSL MASTER secret */ + +#define NSC_STRICT PR_FALSE /* forces the code to do strict template \ + * matching when doing C_FindObject on token \ + * objects. This will slow down search in \ + * NSS. */ /* default search block allocations and increments */ -#define NSC_CERT_BLOCK_SIZE 50 -#define NSC_SEARCH_BLOCK_SIZE 5 +#define NSC_CERT_BLOCK_SIZE 50 +#define NSC_SEARCH_BLOCK_SIZE 5 #define NSC_SLOT_LIST_BLOCK_SIZE 10 #define NSC_FIPS_MODULE 1 @@ -51,21 +52,21 @@ /* these are data base storage hashes, not cryptographic hashes.. The define * the effective size of the various object hash tables */ /* clients care more about memory usage than lookup performance on - * cyrptographic objects. Clients also have less objects around to play with + * cyrptographic objects. Clients also have less objects around to play with * * we eventually should make this configurable at runtime! Especially now that * NSS is a shared library. */ -#define SPACE_ATTRIBUTE_HASH_SIZE 32 +#define SPACE_ATTRIBUTE_HASH_SIZE 32 #define SPACE_SESSION_OBJECT_HASH_SIZE 32 #define SPACE_SESSION_HASH_SIZE 32 #define TIME_ATTRIBUTE_HASH_SIZE 32 #define TIME_SESSION_OBJECT_HASH_SIZE 1024 #define TIME_SESSION_HASH_SIZE 1024 -#define MAX_OBJECT_LIST_SIZE 800 - /* how many objects to keep on the free list - * before we start freeing them */ -#define MAX_KEY_LEN 256 /* maximum symmetric key length in bytes */ +#define MAX_OBJECT_LIST_SIZE 800 +/* how many objects to keep on the free list + * before we start freeing them */ +#define MAX_KEY_LEN 256 /* maximum symmetric key length in bytes */ /* * LOG2_BUCKETS_PER_SESSION_LOCK must be a prime number. @@ -104,16 +105,17 @@ typedef struct SFTKHashSignInfoStr SFTKHashSignInfo; typedef struct SFTKOAEPEncryptInfoStr SFTKOAEPEncryptInfo; typedef struct SFTKOAEPDecryptInfoStr SFTKOAEPDecryptInfo; typedef struct SFTKSSLMACInfoStr SFTKSSLMACInfo; +typedef struct SFTKChaCha20Poly1305InfoStr SFTKChaCha20Poly1305Info; typedef struct SFTKItemTemplateStr SFTKItemTemplate; /* define function pointer typdefs for pointer tables */ typedef void (*SFTKDestroy)(void *, PRBool); typedef void (*SFTKBegin)(void *); -typedef SECStatus (*SFTKCipher)(void *,void *,unsigned int *,unsigned int, - void *, unsigned int); -typedef SECStatus (*SFTKVerify)(void *,void *,unsigned int,void *,unsigned int); -typedef void (*SFTKHash)(void *,const void *,unsigned int); -typedef void (*SFTKEnd)(void *,void *,unsigned int *,unsigned int); +typedef SECStatus (*SFTKCipher)(void *, void *, unsigned int *, unsigned int, + void *, unsigned int); +typedef SECStatus (*SFTKVerify)(void *, void *, unsigned int, void *, unsigned int); +typedef void (*SFTKHash)(void *, const void *, unsigned int); +typedef void (*SFTKEnd)(void *, void *, unsigned int *, unsigned int); typedef void (*SFTKFree)(void *); /* Value to tell if an attribute is modifiable or not. @@ -123,10 +125,10 @@ typedef void (*SFTKFree)(void *); * ALWAYS: attribute can always be changed. */ typedef enum { - SFTK_NEVER = 0, - SFTK_ONCOPY = 1, - SFTK_SENSITIVE = 2, - SFTK_ALWAYS = 3 + SFTK_NEVER = 0, + SFTK_ONCOPY = 1, + SFTK_SENSITIVE = 2, + SFTK_ALWAYS = 3 } SFTKModifyType; /* @@ -134,39 +136,38 @@ typedef enum { * deleting an object. */ typedef enum { - SFTK_DestroyFailure, - SFTK_Destroyed, - SFTK_Busy + SFTK_DestroyFailure, + SFTK_Destroyed, + SFTK_Busy } SFTKFreeStatus; /* * attribute values of an object. */ struct SFTKAttributeStr { - SFTKAttribute *next; - SFTKAttribute *prev; - PRBool freeAttr; - PRBool freeData; + SFTKAttribute *next; + SFTKAttribute *prev; + PRBool freeAttr; + PRBool freeData; /*must be called handle to make sftkqueue_find work */ - CK_ATTRIBUTE_TYPE handle; - CK_ATTRIBUTE attrib; + CK_ATTRIBUTE_TYPE handle; + CK_ATTRIBUTE attrib; unsigned char space[ATTR_SPACE]; }; - /* * doubly link list of objects */ struct SFTKObjectListStr { SFTKObjectList *next; SFTKObjectList *prev; - SFTKObject *parent; + SFTKObject *parent; }; struct SFTKObjectFreeListStr { - SFTKObject *head; - PZLock *lock; - int count; + SFTKObject *head; + PZLock *lock; + int count; }; /* @@ -174,54 +175,53 @@ struct SFTKObjectFreeListStr { */ struct SFTKObjectStr { SFTKObject *next; - SFTKObject *prev; - CK_OBJECT_CLASS objclass; - CK_OBJECT_HANDLE handle; - int refCount; - PZLock *refLock; - SFTKSlot *slot; - void *objectInfo; - SFTKFree infoFree; + SFTKObject *prev; + CK_OBJECT_CLASS objclass; + CK_OBJECT_HANDLE handle; + int refCount; + PZLock *refLock; + SFTKSlot *slot; + void *objectInfo; + SFTKFree infoFree; }; struct SFTKTokenObjectStr { - SFTKObject obj; - SECItem dbKey; + SFTKObject obj; + SECItem dbKey; }; struct SFTKSessionObjectStr { - SFTKObject obj; + SFTKObject obj; SFTKObjectList sessionList; - PZLock *attributeLock; - SFTKSession *session; - PRBool wasDerived; + PZLock *attributeLock; + SFTKSession *session; + PRBool wasDerived; int nextAttr; - SFTKAttribute attrList[MAX_OBJS_ATTRS]; - PRBool optimizeSpace; - unsigned int hashSize; - SFTKAttribute *head[1]; + SFTKAttribute attrList[MAX_OBJS_ATTRS]; + PRBool optimizeSpace; + unsigned int hashSize; + SFTKAttribute *head[1]; }; /* * struct to deal with a temparary list of objects */ struct SFTKObjectListElementStr { - SFTKObjectListElement *next; - SFTKObject *object; + SFTKObjectListElement *next; + SFTKObject *object; }; /* * Area to hold Search results */ struct SFTKSearchResultsStr { - CK_OBJECT_HANDLE *handles; - int size; - int index; - int array_size; + CK_OBJECT_HANDLE *handles; + int size; + int index; + int array_size; }; - -/* +/* * the universal crypto/hash/sign/verify context structure */ typedef enum { @@ -249,50 +249,50 @@ typedef enum { * multi=0 hashInfo=X *** shouldn't happen *** */ struct SFTKSessionContextStr { - SFTKContextType type; - PRBool multi; /* is multipart */ - PRBool rsa; /* is rsa */ - PRBool doPad; /* use PKCS padding for block ciphers */ - unsigned int blockSize; /* blocksize for padding */ - unsigned int padDataLength; /* length of the valid data in padbuf */ + SFTKContextType type; + PRBool multi; /* is multipart */ + PRBool rsa; /* is rsa */ + PRBool doPad; /* use PKCS padding for block ciphers */ + unsigned int blockSize; /* blocksize for padding */ + unsigned int padDataLength; /* length of the valid data in padbuf */ /** latest incomplete block of data for block cipher */ - unsigned char padBuf[SFTK_MAX_BLOCK_SIZE]; + unsigned char padBuf[SFTK_MAX_BLOCK_SIZE]; /** result of MAC'ing of latest full block of data with block cipher */ - unsigned char macBuf[SFTK_MAX_BLOCK_SIZE]; - CK_ULONG macSize; /* size of a general block cipher mac*/ - void *cipherInfo; - void *hashInfo; - unsigned int cipherInfoLen; - CK_MECHANISM_TYPE currentMech; - SFTKCipher update; - SFTKHash hashUpdate; - SFTKEnd end; - SFTKDestroy destroy; - SFTKDestroy hashdestroy; - SFTKVerify verify; - unsigned int maxLen; - SFTKObject *key; + unsigned char macBuf[SFTK_MAX_BLOCK_SIZE]; + CK_ULONG macSize; /* size of a general block cipher mac*/ + void *cipherInfo; + void *hashInfo; + unsigned int cipherInfoLen; + CK_MECHANISM_TYPE currentMech; + SFTKCipher update; + SFTKHash hashUpdate; + SFTKEnd end; + SFTKDestroy destroy; + SFTKDestroy hashdestroy; + SFTKVerify verify; + unsigned int maxLen; + SFTKObject *key; }; /* * Sessions (have objects) */ struct SFTKSessionStr { - SFTKSession *next; - SFTKSession *prev; - CK_SESSION_HANDLE handle; - int refCount; - PZLock *objectLock; - int objectIDCount; - CK_SESSION_INFO info; - CK_NOTIFY notify; - CK_VOID_PTR appData; - SFTKSlot *slot; - SFTKSearchResults *search; - SFTKSessionContext *enc_context; - SFTKSessionContext *hash_context; - SFTKSessionContext *sign_context; - SFTKObjectList *objects[1]; + SFTKSession *next; + SFTKSession *prev; + CK_SESSION_HANDLE handle; + int refCount; + PZLock *objectLock; + int objectIDCount; + CK_SESSION_INFO info; + CK_NOTIFY notify; + CK_VOID_PTR appData; + SFTKSlot *slot; + SFTKSearchResults *search; + SFTKSessionContext *enc_context; + SFTKSessionContext *hash_context; + SFTKSessionContext *sign_context; + SFTKObjectList *objects[1]; }; /* @@ -312,66 +312,66 @@ struct SFTKSessionStr { * next to the fields: * invariant - This value is set when the slot is first created and * never changed until it is destroyed. - * per load - This value is set when the slot is first created, or + * per load - This value is set when the slot is first created, or * when the slot is used to open another directory. Between open and close * this field does not change. * variable - This value changes through the normal process of slot operation. - * - reset. The value of this variable is cleared during an open/close + * - reset. The value of this variable is cleared during an open/close * cycles. * - preserved. The value of this variable is preserved over open/close * cycles. */ struct SFTKSlotStr { - CK_SLOT_ID slotID; /* invariant */ - PZLock *slotLock; /* invariant */ - PZLock **sessionLock; /* invariant */ - unsigned int numSessionLocks; /* invariant */ - unsigned long sessionLockMask; /* invariant */ - PZLock *objectLock; /* invariant */ - PRLock *pwCheckLock; /* invariant */ - PRBool present; /* variable -set */ - PRBool hasTokens; /* per load */ - PRBool isLoggedIn; /* variable - reset */ - PRBool ssoLoggedIn; /* variable - reset */ - PRBool needLogin; /* per load */ - PRBool DB_loaded; /* per load */ - PRBool readOnly; /* per load */ - PRBool optimizeSpace; /* invariant */ - SFTKDBHandle *certDB; /* per load */ - SFTKDBHandle *keyDB; /* per load */ - int minimumPinLen; /* per load */ - PRInt32 sessionIDCount; /* atomically incremented */ - /* (preserved) */ - int sessionIDConflict; /* not protected by a lock */ - /* (preserved) */ - int sessionCount; /* variable - reset */ - PRInt32 rwSessionCount; /* set by atomic operations */ - /* (reset) */ - int sessionObjectHandleCount;/* variable - perserved */ - int index; /* invariant */ - PLHashTable *tokObjHashTable; /* invariant */ - SFTKObject **sessObjHashTable; /* variable - reset */ - unsigned int sessObjHashSize; /* invariant */ - SFTKSession **head; /* variable -reset */ - unsigned int sessHashSize; /* invariant */ - char tokDescription[33]; /* per load */ - char updateTokDescription[33]; /* per load */ - char slotDescription[65]; /* invariant */ + CK_SLOT_ID slotID; /* invariant */ + PZLock *slotLock; /* invariant */ + PZLock **sessionLock; /* invariant */ + unsigned int numSessionLocks; /* invariant */ + unsigned long sessionLockMask; /* invariant */ + PZLock *objectLock; /* invariant */ + PRLock *pwCheckLock; /* invariant */ + PRBool present; /* variable -set */ + PRBool hasTokens; /* per load */ + PRBool isLoggedIn; /* variable - reset */ + PRBool ssoLoggedIn; /* variable - reset */ + PRBool needLogin; /* per load */ + PRBool DB_loaded; /* per load */ + PRBool readOnly; /* per load */ + PRBool optimizeSpace; /* invariant */ + SFTKDBHandle *certDB; /* per load */ + SFTKDBHandle *keyDB; /* per load */ + int minimumPinLen; /* per load */ + PRInt32 sessionIDCount; /* atomically incremented */ + /* (preserved) */ + int sessionIDConflict; /* not protected by a lock */ + /* (preserved) */ + int sessionCount; /* variable - reset */ + PRInt32 rwSessionCount; /* set by atomic operations */ + /* (reset) */ + int sessionObjectHandleCount; /* variable - perserved */ + CK_ULONG index; /* invariant */ + PLHashTable *tokObjHashTable; /* invariant */ + SFTKObject **sessObjHashTable; /* variable - reset */ + unsigned int sessObjHashSize; /* invariant */ + SFTKSession **head; /* variable -reset */ + unsigned int sessHashSize; /* invariant */ + char tokDescription[33]; /* per load */ + char updateTokDescription[33]; /* per load */ + char slotDescription[65]; /* invariant */ }; /* * special joint operations Contexts */ struct SFTKHashVerifyInfoStr { - SECOidTag hashOid; - void *params; - NSSLOWKEYPublicKey *key; + SECOidTag hashOid; + void *params; + NSSLOWKEYPublicKey *key; }; struct SFTKHashSignInfoStr { - SECOidTag hashOid; - void *params; - NSSLOWKEYPrivateKey *key; + SECOidTag hashOid; + void *params; + NSSLOWKEYPrivateKey *key; }; /** @@ -389,57 +389,67 @@ struct SFTKOAEPDecryptInfoStr { /* context for the Final SSLMAC message */ struct SFTKSSLMACInfoStr { - void *hashContext; - SFTKBegin begin; - SFTKHash update; - SFTKEnd end; - CK_ULONG macSize; - int padSize; - unsigned char key[MAX_KEY_LEN]; - unsigned int keySize; + void *hashContext; + SFTKBegin begin; + SFTKHash update; + SFTKEnd end; + CK_ULONG macSize; + int padSize; + unsigned char key[MAX_KEY_LEN]; + unsigned int keySize; +}; + +/* SFTKChaCha20Poly1305Info saves the key, tag length, nonce, + * and additional data for a ChaCha20+Poly1305 AEAD operation. */ +struct SFTKChaCha20Poly1305InfoStr { + ChaCha20Poly1305Context freeblCtx; + unsigned char nonce[12]; + unsigned char ad[16]; + unsigned char *adOverflow; + unsigned int adLen; }; /* * Template based on SECItems, suitable for passing as arrays */ struct SFTKItemTemplateStr { - CK_ATTRIBUTE_TYPE type; - SECItem *item; + CK_ATTRIBUTE_TYPE type; + SECItem *item; }; /* macro for setting SFTKTemplates. */ #define SFTK_SET_ITEM_TEMPLATE(templ, count, itemPtr, attr) \ - templ[count].type = attr; \ - templ[count].item = itemPtr + templ[count].type = attr; \ + templ[count].item = itemPtr #define SFTK_MAX_ITEM_TEMPLATE 10 /* * session handle modifiers */ -#define SFTK_SESSION_SLOT_MASK 0xff000000L +#define SFTK_SESSION_SLOT_MASK 0xff000000L /* * object handle modifiers */ -#define SFTK_TOKEN_MASK 0x80000000L -#define SFTK_TOKEN_MAGIC 0x80000000L -#define SFTK_TOKEN_TYPE_MASK 0x70000000L +#define SFTK_TOKEN_MASK 0x80000000L +#define SFTK_TOKEN_MAGIC 0x80000000L +#define SFTK_TOKEN_TYPE_MASK 0x70000000L /* keydb (high bit == 0) */ -#define SFTK_TOKEN_TYPE_PRIV 0x10000000L -#define SFTK_TOKEN_TYPE_PUB 0x20000000L -#define SFTK_TOKEN_TYPE_KEY 0x30000000L +#define SFTK_TOKEN_TYPE_PRIV 0x10000000L +#define SFTK_TOKEN_TYPE_PUB 0x20000000L +#define SFTK_TOKEN_TYPE_KEY 0x30000000L /* certdb (high bit == 1) */ -#define SFTK_TOKEN_TYPE_TRUST 0x40000000L -#define SFTK_TOKEN_TYPE_CRL 0x50000000L -#define SFTK_TOKEN_TYPE_SMIME 0x60000000L -#define SFTK_TOKEN_TYPE_CERT 0x70000000L +#define SFTK_TOKEN_TYPE_TRUST 0x40000000L +#define SFTK_TOKEN_TYPE_CRL 0x50000000L +#define SFTK_TOKEN_TYPE_SMIME 0x60000000L +#define SFTK_TOKEN_TYPE_CERT 0x70000000L -#define SFTK_TOKEN_KRL_HANDLE (SFTK_TOKEN_MAGIC|SFTK_TOKEN_TYPE_CRL|1) +#define SFTK_TOKEN_KRL_HANDLE (SFTK_TOKEN_MAGIC | SFTK_TOKEN_TYPE_CRL | 1) /* how big (in bytes) a password/pin we can deal with */ -#define SFTK_MAX_PIN 255 +#define SFTK_MAX_PIN 255 /* minimum password/pin length (in Unicode characters) in FIPS mode */ -#define FIPS_MIN_PIN 7 +#define FIPS_MIN_PIN 7 /* slot ID's */ #define NETSCAPE_SLOT_ID 1 @@ -448,77 +458,89 @@ struct SFTKItemTemplateStr { /* slot helper macros */ #define sftk_SlotFromSession(sp) ((sp)->slot) -#define sftk_isToken(id) (((id) & SFTK_TOKEN_MASK) == SFTK_TOKEN_MAGIC) +#define sftk_isToken(id) (((id)&SFTK_TOKEN_MASK) == SFTK_TOKEN_MAGIC) /* the session hash multiplier (see bug 201081) */ #define SHMULTIPLIER 1791398085 /* queueing helper macros */ -#define sftk_hash(value,size) \ - ((PRUint32)((value) * SHMULTIPLIER) & (size-1)) -#define sftkqueue_add(element,id,head,hash_size) \ - { int tmp = sftk_hash(id,hash_size); \ - (element)->next = (head)[tmp]; \ - (element)->prev = NULL; \ - if ((head)[tmp]) (head)[tmp]->prev = (element); \ - (head)[tmp] = (element); } -#define sftkqueue_find(element,id,head,hash_size) \ - for( (element) = (head)[sftk_hash(id,hash_size)]; (element) != NULL; \ - (element) = (element)->next) { \ - if ((element)->handle == (id)) { break; } } -#define sftkqueue_is_queued(element,id,head,hash_size) \ - ( ((element)->next) || ((element)->prev) || \ - ((head)[sftk_hash(id,hash_size)] == (element)) ) -#define sftkqueue_delete(element,id,head,hash_size) \ - if ((element)->next) (element)->next->prev = (element)->prev; \ - if ((element)->prev) (element)->prev->next = (element)->next; \ - else (head)[sftk_hash(id,hash_size)] = ((element)->next); \ - (element)->next = NULL; \ - (element)->prev = NULL; \ +#define sftk_hash(value, size) \ + ((PRUint32)((value)*SHMULTIPLIER) & (size - 1)) +#define sftkqueue_add(element, id, head, hash_size) \ + { \ + int tmp = sftk_hash(id, hash_size); \ + (element)->next = (head)[tmp]; \ + (element)->prev = NULL; \ + if ((head)[tmp]) \ + (head)[tmp]->prev = (element); \ + (head)[tmp] = (element); \ + } +#define sftkqueue_find(element, id, head, hash_size) \ + for ((element) = (head)[sftk_hash(id, hash_size)]; (element) != NULL; \ + (element) = (element)->next) { \ + if ((element)->handle == (id)) { \ + break; \ + } \ + } +#define sftkqueue_is_queued(element, id, head, hash_size) \ + (((element)->next) || ((element)->prev) || \ + ((head)[sftk_hash(id, hash_size)] == (element))) +#define sftkqueue_delete(element, id, head, hash_size) \ + if ((element)->next) \ + (element)->next->prev = (element)->prev; \ + if ((element)->prev) \ + (element)->prev->next = (element)->next; \ + else \ + (head)[sftk_hash(id, hash_size)] = ((element)->next); \ + (element)->next = NULL; \ + (element)->prev = NULL; #define sftkqueue_init_element(element) \ (element)->prev = NULL; #define sftkqueue_add2(element, id, index, head) \ { \ - (element)->next = (head)[index]; \ - if ((head)[index]) \ - (head)[index]->prev = (element); \ - (head)[index] = (element); \ + (element)->next = (head)[index]; \ + if ((head)[index]) \ + (head)[index]->prev = (element); \ + (head)[index] = (element); \ } #define sftkqueue_find2(element, id, index, head) \ - for ( (element) = (head)[index]; \ - (element) != NULL; \ - (element) = (element)->next) { \ - if ((element)->handle == (id)) { break; } \ + for ((element) = (head)[index]; \ + (element) != NULL; \ + (element) = (element)->next) { \ + if ((element)->handle == (id)) { \ + break; \ + } \ } #define sftkqueue_delete2(element, id, index, head) \ - if ((element)->next) (element)->next->prev = (element)->prev; \ - if ((element)->prev) (element)->prev->next = (element)->next; \ - else (head)[index] = ((element)->next); + if ((element)->next) \ + (element)->next->prev = (element)->prev; \ + if ((element)->prev) \ + (element)->prev->next = (element)->next; \ + else \ + (head)[index] = ((element)->next); #define sftkqueue_clear_deleted_element(element) \ - (element)->next = NULL; \ - (element)->prev = NULL; \ - + (element)->next = NULL; \ + (element)->prev = NULL; /* sessionID (handle) is used to determine session lock bucket */ #ifdef NOSPREAD -/* NOSPREAD: (ID>>L2LPB) & (perbucket-1) */ -#define SFTK_SESSION_LOCK(slot,handle) \ - ((slot)->sessionLock[((handle) >> LOG2_BUCKETS_PER_SESSION_LOCK) \ - & (slot)->sessionLockMask]) +/* NOSPREAD: (ID>>L2LPB) & (perbucket-1) */ +#define SFTK_SESSION_LOCK(slot, handle) \ + ((slot)->sessionLock[((handle) >> LOG2_BUCKETS_PER_SESSION_LOCK) & (slot)->sessionLockMask]) #else -/* SPREAD: ID & (perbucket-1) */ -#define SFTK_SESSION_LOCK(slot,handle) \ +/* SPREAD: ID & (perbucket-1) */ +#define SFTK_SESSION_LOCK(slot, handle) \ ((slot)->sessionLock[(handle) & (slot)->sessionLockMask]) #endif /* expand an attribute & secitem structures out */ -#define sftk_attr_expand(ap) (ap)->type,(ap)->pValue,(ap)->ulValueLen -#define sftk_item_expand(ip) (ip)->data,(ip)->len +#define sftk_attr_expand(ap) (ap)->type, (ap)->pValue, (ap)->ulValueLen +#define sftk_item_expand(ip) (ip)->data, (ip)->len typedef struct sftk_token_parametersStr { CK_SLOT_ID slotID; @@ -532,7 +554,7 @@ typedef struct sftk_token_parametersStr { char *tokdes; char *slotdes; char *updtokdes; - int minPW; + int minPW; PRBool readOnly; PRBool noCertDB; PRBool noKeyDB; @@ -547,7 +569,7 @@ typedef struct sftk_parametersStr { char *updateID; char *secmodName; char *man; - char *libdes; + char *libdes; PRBool readOnly; PRBool noModDB; PRBool noCertDB; @@ -558,7 +580,6 @@ typedef struct sftk_parametersStr { int token_count; } sftk_parameters; - /* path stuff (was machine dependent) used by dbinit.c and pk11db.c */ #define CERT_DB_FMT "%scert%s.db" #define KEY_DB_FMT "%skey%s.db" @@ -569,55 +590,56 @@ SEC_BEGIN_PROTOS extern PRBool nsf_init; extern CK_RV nsc_CommonInitialize(CK_VOID_PTR pReserved, PRBool isFIPS); extern CK_RV nsc_CommonFinalize(CK_VOID_PTR pReserved, PRBool isFIPS); -extern PRBool sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV* crv); -extern CK_RV nsc_CommonGetSlotList(CK_BBOOL tokPresent, - CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex); +extern PRBool sftk_ForkReset(CK_VOID_PTR pReserved, CK_RV *crv); +extern CK_RV nsc_CommonGetSlotList(CK_BBOOL tokPresent, + CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount, int moduleIndex); /* slot initialization, reinit, shutdown and destruction */ extern CK_RV SFTK_SlotInit(char *configdir, char *updatedir, char *updateID, - sftk_token_parameters *params, int moduleIndex); + sftk_token_parameters *params, int moduleIndex); extern CK_RV SFTK_SlotReInit(SFTKSlot *slot, char *configdir, - char *updatedir, char *updateID, - sftk_token_parameters *params, int moduleIndex); + char *updatedir, char *updateID, + sftk_token_parameters *params, int moduleIndex); extern CK_RV SFTK_DestroySlotData(SFTKSlot *slot); extern CK_RV SFTK_ShutdownSlot(SFTKSlot *slot); extern CK_RV sftk_CloseAllSessions(SFTKSlot *slot, PRBool logout); - /* internal utility functions used by pkcs11.c */ extern SFTKAttribute *sftk_FindAttribute(SFTKObject *object, - CK_ATTRIBUTE_TYPE type); + CK_ATTRIBUTE_TYPE type); extern void sftk_FreeAttribute(SFTKAttribute *attribute); extern CK_RV sftk_AddAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - const void *valPtr, CK_ULONG length); + const void *valPtr, CK_ULONG length); extern CK_RV sftk_Attribute2SecItem(PLArenaPool *arena, SECItem *item, - SFTKObject *object, CK_ATTRIBUTE_TYPE type); -extern CK_RV sftk_MultipleAttribute2SecItem(PLArenaPool *arena, - SFTKObject *object, SFTKItemTemplate *templ, int count); + SFTKObject *object, CK_ATTRIBUTE_TYPE type); +extern CK_RV sftk_MultipleAttribute2SecItem(PLArenaPool *arena, + SFTKObject *object, + SFTKItemTemplate *templ, int count); extern unsigned int sftk_GetLengthInBits(unsigned char *buf, - unsigned int bufLen); -extern CK_RV sftk_ConstrainAttribute(SFTKObject *object, - CK_ATTRIBUTE_TYPE type, int minLength, int maxLength, int minMultiple); + unsigned int bufLen); +extern CK_RV sftk_ConstrainAttribute(SFTKObject *object, + CK_ATTRIBUTE_TYPE type, int minLength, + int maxLength, int minMultiple); extern PRBool sftk_hasAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type); extern PRBool sftk_isTrue(SFTKObject *object, CK_ATTRIBUTE_TYPE type); extern void sftk_DeleteAttributeType(SFTKObject *object, - CK_ATTRIBUTE_TYPE type); + CK_ATTRIBUTE_TYPE type); extern CK_RV sftk_Attribute2SecItem(PLArenaPool *arena, SECItem *item, - SFTKObject *object, CK_ATTRIBUTE_TYPE type); + SFTKObject *object, CK_ATTRIBUTE_TYPE type); extern CK_RV sftk_Attribute2SSecItem(PLArenaPool *arena, SECItem *item, - SFTKObject *object, - CK_ATTRIBUTE_TYPE type); + SFTKObject *object, + CK_ATTRIBUTE_TYPE type); extern SFTKModifyType sftk_modifyType(CK_ATTRIBUTE_TYPE type, - CK_OBJECT_CLASS inClass); + CK_OBJECT_CLASS inClass); extern PRBool sftk_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass); extern char *sftk_getString(SFTKObject *object, CK_ATTRIBUTE_TYPE type); -extern void sftk_nullAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type); +extern void sftk_nullAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type); extern CK_RV sftk_GetULongAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - CK_ULONG *longData); + CK_ULONG *longData); extern CK_RV sftk_forceAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len); + const void *value, unsigned int len); extern CK_RV sftk_defaultAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len); + const void *value, unsigned int len); extern unsigned int sftk_MapTrust(CK_TRUST trust, PRBool clientAuth); extern SFTKObject *sftk_NewObject(SFTKSlot *slot); @@ -626,7 +648,7 @@ extern SFTKFreeStatus sftk_FreeObject(SFTKObject *object); extern CK_RV sftk_DeleteObject(SFTKSession *session, SFTKObject *object); extern void sftk_ReferenceObject(SFTKObject *object); extern SFTKObject *sftk_ObjectFromHandle(CK_OBJECT_HANDLE handle, - SFTKSession *session); + SFTKSession *session); extern void sftk_AddSlotObject(SFTKSlot *slot, SFTKObject *object); extern void sftk_AddObject(SFTKSession *session, SFTKObject *object); /* clear out all the existing object ID to database key mappings. @@ -634,11 +656,11 @@ extern void sftk_AddObject(SFTKSession *session, SFTKObject *object); extern CK_RV SFTK_ClearTokenKeyHashTable(SFTKSlot *slot); extern CK_RV sftk_searchObjectList(SFTKSearchResults *search, - SFTKObject **head, unsigned int size, - PZLock *lock, CK_ATTRIBUTE_PTR inTemplate, - int count, PRBool isLoggedIn); + SFTKObject **head, unsigned int size, + PZLock *lock, CK_ATTRIBUTE_PTR inTemplate, + int count, PRBool isLoggedIn); extern SFTKObjectListElement *sftk_FreeObjectListElement( - SFTKObjectListElement *objectList); + SFTKObjectListElement *objectList); extern void sftk_FreeObjectList(SFTKObjectListElement *objectList); extern void sftk_FreeSearch(SFTKSearchResults *search); extern CK_RV sftk_handleObject(SFTKObject *object, SFTKSession *session); @@ -648,20 +670,20 @@ extern SFTKSlot *sftk_SlotFromSessionHandle(CK_SESSION_HANDLE handle); extern SFTKSession *sftk_SessionFromHandle(CK_SESSION_HANDLE handle); extern void sftk_FreeSession(SFTKSession *session); extern SFTKSession *sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, - CK_VOID_PTR pApplication, CK_FLAGS flags); -extern void sftk_update_state(SFTKSlot *slot,SFTKSession *session); + CK_VOID_PTR pApplication, CK_FLAGS flags); +extern void sftk_update_state(SFTKSlot *slot, SFTKSession *session); extern void sftk_update_all_states(SFTKSlot *slot); extern void sftk_FreeContext(SFTKSessionContext *context); extern void sftk_InitFreeLists(void); extern void sftk_CleanupFreeLists(void); extern NSSLOWKEYPublicKey *sftk_GetPubKey(SFTKObject *object, - CK_KEY_TYPE key_type, CK_RV *crvp); + CK_KEY_TYPE key_type, CK_RV *crvp); extern NSSLOWKEYPrivateKey *sftk_GetPrivKey(SFTKObject *object, - CK_KEY_TYPE key_type, CK_RV *crvp); + CK_KEY_TYPE key_type, CK_RV *crvp); extern void sftk_FormatDESKey(unsigned char *key, int length); extern PRBool sftk_CheckDESKey(unsigned char *key); -extern PRBool sftk_IsWeakKey(unsigned char *key,CK_KEY_TYPE key_type); +extern PRBool sftk_IsWeakKey(unsigned char *key, CK_KEY_TYPE key_type); /* mechanism allows this operation */ extern CK_RV sftk_MechAllowsOperation(CK_MECHANISM_TYPE type, CK_ATTRIBUTE_TYPE op); @@ -676,37 +698,32 @@ NSSLOWKEYPrivateKey *sftk_FindKeyByPublicKey(SFTKSlot *slot, SECItem *dbKey); CK_RV sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS); void sftk_freeParams(sftk_parameters *params); - /* * narrow objects */ -SFTKSessionObject * sftk_narrowToSessionObject(SFTKObject *); -SFTKTokenObject * sftk_narrowToTokenObject(SFTKObject *); +SFTKSessionObject *sftk_narrowToSessionObject(SFTKObject *); +SFTKTokenObject *sftk_narrowToTokenObject(SFTKObject *); /* * token object utilities */ void sftk_addHandle(SFTKSearchResults *search, CK_OBJECT_HANDLE handle); -PRBool sftk_poisonHandle(SFTKSlot *slot, SECItem *dbkey, - CK_OBJECT_HANDLE handle); -SFTKObject * sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, - CK_OBJECT_HANDLE handle); +PRBool sftk_poisonHandle(SFTKSlot *slot, SECItem *dbkey, + CK_OBJECT_HANDLE handle); +SFTKObject *sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, + CK_OBJECT_HANDLE handle); SFTKTokenObject *sftk_convertSessionToToken(SFTKObject *so); - /* J-PAKE (jpakesftk.c) */ -extern -CK_RV jpake_Round1(HASH_HashType hashType, - CK_NSS_JPAKERound1Params * params, - SFTKObject * key); -extern -CK_RV jpake_Round2(HASH_HashType hashType, - CK_NSS_JPAKERound2Params * params, - SFTKObject * sourceKey, SFTKObject * key); -extern -CK_RV jpake_Final(HASH_HashType hashType, - const CK_NSS_JPAKEFinalParams * params, - SFTKObject * sourceKey, SFTKObject * key); +extern CK_RV jpake_Round1(HASH_HashType hashType, + CK_NSS_JPAKERound1Params *params, + SFTKObject *key); +extern CK_RV jpake_Round2(HASH_HashType hashType, + CK_NSS_JPAKERound2Params *params, + SFTKObject *sourceKey, SFTKObject *key); +extern CK_RV jpake_Final(HASH_HashType hashType, + const CK_NSS_JPAKEFinalParams *params, + SFTKObject *sourceKey, SFTKObject *key); /* Constant time MAC functions (hmacct.c) */ @@ -720,14 +737,14 @@ struct sftk_MACConstantTimeCtxStr { unsigned char header[75]; }; typedef struct sftk_MACConstantTimeCtxStr sftk_MACConstantTimeCtx; -sftk_MACConstantTimeCtx* sftk_HMACConstantTime_New( - CK_MECHANISM_PTR mech, SFTKObject *key); -sftk_MACConstantTimeCtx* sftk_SSLv3MACConstantTime_New( - CK_MECHANISM_PTR mech, SFTKObject *key); +sftk_MACConstantTimeCtx *sftk_HMACConstantTime_New( + CK_MECHANISM_PTR mech, SFTKObject *key); +sftk_MACConstantTimeCtx *sftk_SSLv3MACConstantTime_New( + CK_MECHANISM_PTR mech, SFTKObject *key); void sftk_HMACConstantTime_Update(void *pctx, const void *data, unsigned int len); void sftk_SSLv3MACConstantTime_Update(void *pctx, const void *data, unsigned int len); void sftk_MACConstantTime_EndHash( - void *pctx, void *out, unsigned int *outLength, unsigned int maxLength); + void *pctx, void *out, unsigned int *outLength, unsigned int maxLength); void sftk_MACConstantTime_DestroyContext(void *pctx, PRBool); /**************************************** @@ -735,11 +752,11 @@ void sftk_MACConstantTime_DestroyContext(void *pctx, PRBool); */ extern CK_RV -sftk_TLSPRFInit(SFTKSessionContext *context, - SFTKObject * key, - CK_KEY_TYPE key_type, - HASH_HashType hash_alg, - unsigned int out_len); +sftk_TLSPRFInit(SFTKSessionContext *context, + SFTKObject *key, + CK_KEY_TYPE key_type, + HASH_HashType hash_alg, + unsigned int out_len); SEC_END_PROTOS diff --git a/nss/lib/softoken/pkcs11ni.h b/nss/lib/softoken/pkcs11ni.h index 3375102..612842c 100644 --- a/nss/lib/softoken/pkcs11ni.h +++ b/nss/lib/softoken/pkcs11ni.h @@ -17,5 +17,4 @@ #define SFTK_MIN_FIPS_USER_SLOT_ID 101 #define SFTK_MAX_FIPS_USER_SLOT_ID 127 - #endif /* _PKCS11NI_H_ */ diff --git a/nss/lib/softoken/pkcs11u.c b/nss/lib/softoken/pkcs11u.c index de5cbbc..a5694ee 100644 --- a/nss/lib/softoken/pkcs11u.c +++ b/nss/lib/softoken/pkcs11u.c @@ -24,19 +24,19 @@ */ static SFTKAttribute * sftk_NewAttribute(SFTKObject *object, - CK_ATTRIBUTE_TYPE type, const void *value, CK_ULONG len) + CK_ATTRIBUTE_TYPE type, const void *value, CK_ULONG len) { SFTKAttribute *attribute; SFTKSessionObject *so = sftk_narrowToSessionObject(object); int index; - if (so == NULL) { - /* allocate new attribute in a buffer */ - PORT_Assert(0); - return NULL; + if (so == NULL) { + /* allocate new attribute in a buffer */ + PORT_Assert(0); + return NULL; } - /* + /* * We attempt to keep down contention on Malloc and Arena locks by * limiting the number of these calls on high traversed paths. This * is done for attributes by 'allocating' them from a pool already @@ -46,7 +46,8 @@ sftk_NewAttribute(SFTKObject *object, index = so->nextAttr++; PZ_Unlock(so->attributeLock); PORT_Assert(index < MAX_OBJS_ATTRS); - if (index >= MAX_OBJS_ATTRS) return NULL; + if (index >= MAX_OBJS_ATTRS) + return NULL; attribute = &so->attrList[index]; attribute->attrib.type = type; @@ -54,19 +55,19 @@ sftk_NewAttribute(SFTKObject *object, attribute->freeData = PR_FALSE; if (value) { if (len <= ATTR_SPACE) { - attribute->attrib.pValue = attribute->space; - } else { - attribute->attrib.pValue = PORT_Alloc(len); - attribute->freeData = PR_TRUE; - } - if (attribute->attrib.pValue == NULL) { - return NULL; - } - PORT_Memcpy(attribute->attrib.pValue,value,len); - attribute->attrib.ulValueLen = len; + attribute->attrib.pValue = attribute->space; + } else { + attribute->attrib.pValue = PORT_Alloc(len); + attribute->freeData = PR_TRUE; + } + if (attribute->attrib.pValue == NULL) { + return NULL; + } + PORT_Memcpy(attribute->attrib.pValue, value, len); + attribute->attrib.ulValueLen = len; } else { - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; + attribute->attrib.pValue = NULL; + attribute->attrib.ulValueLen = 0; } attribute->attrib.type = type; attribute->handle = type; @@ -82,13 +83,13 @@ static void sftk_DestroyAttribute(SFTKAttribute *attribute) { if (attribute->freeData) { - if (attribute->attrib.pValue) { - /* clear out the data in the attribute value... it may have been - * sensitive data */ - PORT_Memset(attribute->attrib.pValue, 0, - attribute->attrib.ulValueLen); - } - PORT_Free(attribute->attrib.pValue); + if (attribute->attrib.pValue) { + /* clear out the data in the attribute value... it may have been + * sensitive data */ + PORT_Memset(attribute->attrib.pValue, 0, + attribute->attrib.ulValueLen); + } + PORT_Free(attribute->attrib.pValue); } PORT_Free(attribute); } @@ -100,21 +101,21 @@ void sftk_FreeAttribute(SFTKAttribute *attribute) { if (attribute->freeAttr) { - sftk_DestroyAttribute(attribute); - return; + sftk_DestroyAttribute(attribute); + return; } } -static SFTKAttribute * -sftk_FindTokenAttribute(SFTKTokenObject *object,CK_ATTRIBUTE_TYPE type) +static SFTKAttribute * +sftk_FindTokenAttribute(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *myattribute = NULL; SFTKDBHandle *dbHandle = NULL; CK_RV crv = CKR_HOST_MEMORY; - myattribute = (SFTKAttribute*)PORT_Alloc(sizeof(SFTKAttribute)); + myattribute = (SFTKAttribute *)PORT_Alloc(sizeof(SFTKAttribute)); if (myattribute == NULL) { - goto loser; + goto loser; } dbHandle = sftk_getDBForTokenObject(object->obj.slot, object->obj.handle); @@ -128,59 +129,59 @@ sftk_FindTokenAttribute(SFTKTokenObject *object,CK_ATTRIBUTE_TYPE type) myattribute->freeData = PR_FALSE; crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, - &myattribute->attrib, 1); + &myattribute->attrib, 1); /* attribute is bigger than our attribute space buffer, malloc it */ if (crv == CKR_BUFFER_TOO_SMALL) { - myattribute->attrib.pValue = NULL; - crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, - &myattribute->attrib, 1); - if (crv != CKR_OK) { - goto loser; - } - myattribute->attrib.pValue = PORT_Alloc(myattribute->attrib.ulValueLen); - if (myattribute->attrib.pValue == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } - myattribute->freeData = PR_TRUE; - crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, - &myattribute->attrib, 1); - } + myattribute->attrib.pValue = NULL; + crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, + &myattribute->attrib, 1); + if (crv != CKR_OK) { + goto loser; + } + myattribute->attrib.pValue = PORT_Alloc(myattribute->attrib.ulValueLen); + if (myattribute->attrib.pValue == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } + myattribute->freeData = PR_TRUE; + crv = sftkdb_GetAttributeValue(dbHandle, object->obj.handle, + &myattribute->attrib, 1); + } loser: if (dbHandle) { - sftk_freeDB(dbHandle); + sftk_freeDB(dbHandle); } if (crv != CKR_OK) { - if (myattribute) { - myattribute->attrib.ulValueLen = 0; - sftk_FreeAttribute(myattribute); - myattribute = NULL; - } + if (myattribute) { + myattribute->attrib.ulValueLen = 0; + sftk_FreeAttribute(myattribute); + myattribute = NULL; + } } return myattribute; -} +} /* * look up and attribute structure from a type and Object structure. - * The returned attribute is referenced and needs to be freed when + * The returned attribute is referenced and needs to be freed when * it is no longer needed. */ SFTKAttribute * -sftk_FindAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_FindAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object); if (sessObject == NULL) { - return sftk_FindTokenAttribute(sftk_narrowToTokenObject(object),type); + return sftk_FindTokenAttribute(sftk_narrowToTokenObject(object), type); } PZ_Lock(sessObject->attributeLock); - sftkqueue_find(attribute,type,sessObject->head, sessObject->hashSize); + sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize); PZ_Unlock(sessObject->attributeLock); - return(attribute); + return (attribute); } /* @@ -193,19 +194,19 @@ sftk_GetLengthInBits(unsigned char *buf, unsigned int bufLen) unsigned int i; /* Get the real length in bytes */ - for (i=0; i < bufLen; i++) { - unsigned char c = *buf++; - if (c != 0) { - unsigned char m; - for (m=0x80; m > 0 ; m = m >> 1) { - if ((c & m) != 0) { - break; - } - size--; - } - break; - } - size-=8; + for (i = 0; i < bufLen; i++) { + unsigned char c = *buf++; + if (c != 0) { + unsigned char m; + for (m = 0x80; m > 0; m = m >> 1) { + if ((c & m) != 0) { + break; + } + size--; + } + break; + } + size -= 8; } return size; } @@ -219,8 +220,8 @@ sftk_GetLengthInBits(unsigned char *buf, unsigned int bufLen) * if any constraint is '0' that constraint is not checked. */ CK_RV -sftk_ConstrainAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - int minLength, int maxLength, int minMultiple) +sftk_ConstrainAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, + int minLength, int maxLength, int minMultiple) { SFTKAttribute *attribute; int size; @@ -228,24 +229,24 @@ sftk_ConstrainAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, attribute = sftk_FindAttribute(object, type); if (!attribute) { - return CKR_TEMPLATE_INCOMPLETE; + return CKR_TEMPLATE_INCOMPLETE; } - ptr = (unsigned char *) attribute->attrib.pValue; + ptr = (unsigned char *)attribute->attrib.pValue; if (ptr == NULL) { - sftk_FreeAttribute(attribute); - return CKR_ATTRIBUTE_VALUE_INVALID; + sftk_FreeAttribute(attribute); + return CKR_ATTRIBUTE_VALUE_INVALID; } size = sftk_GetLengthInBits(ptr, attribute->attrib.ulValueLen); sftk_FreeAttribute(attribute); - if ((minLength != 0) && (size < minLength)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if ((minLength != 0) && (size < minLength)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } - if ((maxLength != 0) && (size > maxLength)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + if ((maxLength != 0) && (size > maxLength)) { + return CKR_ATTRIBUTE_VALUE_INVALID; } if ((minMultiple != 0) && ((size % minMultiple) != 0)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } return CKR_OK; } @@ -273,17 +274,17 @@ sftk_hasAttributeToken(SFTKTokenObject *object, CK_ATTRIBUTE_TYPE type) * return true if object has attribute */ PRBool -sftk_hasAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_hasAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object); if (sessObject == NULL) { - return sftk_hasAttributeToken(sftk_narrowToTokenObject(object), type); + return sftk_hasAttributeToken(sftk_narrowToTokenObject(object), type); } PZ_Lock(sessObject->attributeLock); - sftkqueue_find(attribute,type,sessObject->head, sessObject->hashSize); + sftkqueue_find(attribute, type, sessObject->head, sessObject->hashSize); PZ_Unlock(sessObject->attributeLock); return (PRBool)(attribute != NULL); @@ -293,49 +294,51 @@ sftk_hasAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type) * add an attribute to an object */ static void -sftk_AddAttribute(SFTKObject *object,SFTKAttribute *attribute) +sftk_AddAttribute(SFTKObject *object, SFTKAttribute *attribute) { SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object); - if (sessObject == NULL) return; + if (sessObject == NULL) + return; PZ_Lock(sessObject->attributeLock); - sftkqueue_add(attribute,attribute->handle, - sessObject->head, sessObject->hashSize); + sftkqueue_add(attribute, attribute->handle, + sessObject->head, sessObject->hashSize); PZ_Unlock(sessObject->attributeLock); } -/* +/* * copy an unsigned attribute into a SECItem. Secitem is allocated in * the specified arena. */ CK_RV -sftk_Attribute2SSecItem(PLArenaPool *arena,SECItem *item,SFTKObject *object, - CK_ATTRIBUTE_TYPE type) +sftk_Attribute2SSecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object, + CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; item->data = NULL; attribute = sftk_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; (void)SECITEM_AllocItem(arena, item, attribute->attrib.ulValueLen); if (item->data == NULL) { - sftk_FreeAttribute(attribute); - return CKR_HOST_MEMORY; + sftk_FreeAttribute(attribute); + return CKR_HOST_MEMORY; } PORT_Memcpy(item->data, attribute->attrib.pValue, item->len); sftk_FreeAttribute(attribute); return CKR_OK; } -/* +/* * fetch multiple attributes into SECItems. Secitem data is allocated in * the specified arena. */ CK_RV sftk_MultipleAttribute2SecItem(PLArenaPool *arena, SFTKObject *object, - SFTKItemTemplate *itemTemplate, int itemTemplateCount) + SFTKItemTemplate *itemTemplate, int itemTemplateCount) { CK_RV crv = CKR_OK; @@ -349,87 +352,86 @@ sftk_MultipleAttribute2SecItem(PLArenaPool *arena, SFTKObject *object, /* session objects, just loop through the list */ if (tokObject == NULL) { - for (i=0; i < itemTemplateCount; i++) { - crv = sftk_Attribute2SecItem(arena,itemTemplate[i].item, object, - itemTemplate[i].type); - if (crv != CKR_OK) { - return crv; - } - } - return CKR_OK; + for (i = 0; i < itemTemplateCount; i++) { + crv = sftk_Attribute2SecItem(arena, itemTemplate[i].item, object, + itemTemplate[i].type); + if (crv != CKR_OK) { + return crv; + } + } + return CKR_OK; } /* don't do any work if none is required */ if (itemTemplateCount == 0) { - return CKR_OK; + return CKR_OK; } /* don't allocate the template unless we need it */ if (itemTemplateCount > SFTK_MAX_ITEM_TEMPLATE) { - template = PORT_NewArray(CK_ATTRIBUTE, itemTemplateCount); + template = PORT_NewArray(CK_ATTRIBUTE, itemTemplateCount); } else { - template = templateSpace; + template = templateSpace; } if (template == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + crv = CKR_HOST_MEMORY; + goto loser; } dbHandle = sftk_getDBForTokenObject(object->slot, object->handle); if (dbHandle == NULL) { - crv = CKR_OBJECT_HANDLE_INVALID; - goto loser; + crv = CKR_OBJECT_HANDLE_INVALID; + goto loser; } /* set up the PKCS #11 template */ - for (i=0; i < itemTemplateCount; i++) { - template[i].type = itemTemplate[i].type; - template[i].pValue = NULL; - template[i].ulValueLen = 0; + for (i = 0; i < itemTemplateCount; i++) { + template[i].type = itemTemplate[i].type; + template[i].pValue = NULL; + template[i].ulValueLen = 0; } /* fetch the attribute lengths */ crv = sftkdb_GetAttributeValue(dbHandle, object->handle, - template, itemTemplateCount); + template, itemTemplateCount); if (crv != CKR_OK) { - goto loser; + goto loser; } /* allocate space for the attributes */ - for (i=0; i < itemTemplateCount ; i++) { - template[i].pValue = PORT_ArenaAlloc(arena, template[i].ulValueLen); - if (template[i].pValue == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } + for (i = 0; i < itemTemplateCount; i++) { + template[i].pValue = PORT_ArenaAlloc(arena, template[i].ulValueLen); + if (template[i].pValue == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } } /* fetch the attributes */ crv = sftkdb_GetAttributeValue(dbHandle, object->handle, - template, itemTemplateCount); + template, itemTemplateCount); if (crv != CKR_OK) { - goto loser; + goto loser; } - /* Fill in the items */ - for (i=0; i < itemTemplateCount; i++) { - itemTemplate[i].item->data = template[i].pValue; - itemTemplate[i].item->len = template[i].ulValueLen; + /* Fill in the items */ + for (i = 0; i < itemTemplateCount; i++) { + itemTemplate[i].item->data = template[i].pValue; + itemTemplate[i].item->len = template[i].ulValueLen; } loser: if (template != templateSpace) { - PORT_Free(template); + PORT_Free(template); } if (dbHandle) { - sftk_freeDB(dbHandle); + sftk_freeDB(dbHandle); } - + return crv; } - /* * delete an attribute from an object */ @@ -439,13 +441,13 @@ sftk_DeleteAttribute(SFTKObject *object, SFTKAttribute *attribute) SFTKSessionObject *sessObject = sftk_narrowToSessionObject(object); if (sessObject == NULL) { - return ; + return; } PZ_Lock(sessObject->attributeLock); - if (sftkqueue_is_queued(attribute,attribute->handle, - sessObject->head, sessObject->hashSize)) { - sftkqueue_delete(attribute,attribute->handle, - sessObject->head, sessObject->hashSize); + if (sftkqueue_is_queued(attribute, attribute->handle, + sessObject->head, sessObject->hashSize)) { + sftkqueue_delete(attribute, attribute->handle, + sessObject->head, sessObject->hashSize); } PZ_Unlock(sessObject->attributeLock); } @@ -455,13 +457,15 @@ sftk_DeleteAttribute(SFTKObject *object, SFTKAttribute *attribute) * of that attribute. */ PRBool -sftk_isTrue(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_isTrue(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; PRBool tok = PR_FALSE; - attribute=sftk_FindAttribute(object,type); - if (attribute == NULL) { return PR_FALSE; } + attribute = sftk_FindAttribute(object, type); + if (attribute == NULL) { + return PR_FALSE; + } tok = (PRBool)(*(CK_BBOOL *)attribute->attrib.pValue); sftk_FreeAttribute(attribute); @@ -474,29 +478,29 @@ sftk_isTrue(SFTKObject *object,CK_ATTRIBUTE_TYPE type) * want to keep this info around in memory in the clear. */ void -sftk_nullAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_nullAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; - attribute=sftk_FindAttribute(object,type); - if (attribute == NULL) return; + attribute = sftk_FindAttribute(object, type); + if (attribute == NULL) + return; if (attribute->attrib.pValue != NULL) { - PORT_Memset(attribute->attrib.pValue,0,attribute->attrib.ulValueLen); - if (attribute->freeData) { - PORT_Free(attribute->attrib.pValue); - } - attribute->freeData = PR_FALSE; - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; + PORT_Memset(attribute->attrib.pValue, 0, attribute->attrib.ulValueLen); + if (attribute->freeData) { + PORT_Free(attribute->attrib.pValue); + } + attribute->freeData = PR_FALSE; + attribute->attrib.pValue = NULL; + attribute->attrib.ulValueLen = 0; } sftk_FreeAttribute(attribute); } - static CK_RV -sftk_forceTokenAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len) +sftk_forceTokenAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len) { CK_ATTRIBUTE attribute; SFTKDBHandle *dbHandle = NULL; @@ -505,7 +509,7 @@ sftk_forceTokenAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, PORT_Assert(to); if (to == NULL) { - return CKR_DEVICE_ERROR; + return CKR_DEVICE_ERROR; } dbHandle = sftk_getDBForTokenObject(object->slot, object->handle); @@ -518,13 +522,13 @@ sftk_forceTokenAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, sftk_freeDB(dbHandle); return crv; } - + /* * force an attribute to a specifc value. */ CK_RV -sftk_forceAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, - const void *value, unsigned int len) +sftk_forceAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, + const void *value, unsigned int len) { SFTKAttribute *attribute; void *att_val = NULL; @@ -539,44 +543,44 @@ sftk_forceAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, return CKR_DEVICE_ERROR; } if (sftk_isToken(object->handle)) { - return sftk_forceTokenAttribute(object,type,value,len); + return sftk_forceTokenAttribute(object, type, value, len); } - attribute=sftk_FindAttribute(object,type); - if (attribute == NULL) return sftk_AddAttributeType(object,type,value,len); - + attribute = sftk_FindAttribute(object, type); + if (attribute == NULL) + return sftk_AddAttributeType(object, type, value, len); if (value) { if (len <= ATTR_SPACE) { - att_val = attribute->space; - } else { - att_val = PORT_Alloc(len); - freeData = PR_TRUE; - } - if (att_val == NULL) { - return CKR_HOST_MEMORY; - } - if (attribute->attrib.pValue == att_val) { - PORT_Memset(attribute->attrib.pValue,0, - attribute->attrib.ulValueLen); - } - PORT_Memcpy(att_val,value,len); + att_val = attribute->space; + } else { + att_val = PORT_Alloc(len); + freeData = PR_TRUE; + } + if (att_val == NULL) { + return CKR_HOST_MEMORY; + } + if (attribute->attrib.pValue == att_val) { + PORT_Memset(attribute->attrib.pValue, 0, + attribute->attrib.ulValueLen); + } + PORT_Memcpy(att_val, value, len); } if (attribute->attrib.pValue != NULL) { - if (attribute->attrib.pValue != att_val) { - PORT_Memset(attribute->attrib.pValue,0, - attribute->attrib.ulValueLen); - } - if (attribute->freeData) { - PORT_Free(attribute->attrib.pValue); - } - attribute->freeData = PR_FALSE; - attribute->attrib.pValue = NULL; - attribute->attrib.ulValueLen = 0; + if (attribute->attrib.pValue != att_val) { + PORT_Memset(attribute->attrib.pValue, 0, + attribute->attrib.ulValueLen); + } + if (attribute->freeData) { + PORT_Free(attribute->attrib.pValue); + } + attribute->freeData = PR_FALSE; + attribute->attrib.pValue = NULL; + attribute->attrib.ulValueLen = 0; } if (att_val) { - attribute->attrib.pValue = att_val; - attribute->attrib.ulValueLen = len; - attribute->freeData = freeData; + attribute->attrib.pValue = att_val; + attribute->attrib.ulValueLen = len; + attribute->freeData = freeData; } sftk_FreeAttribute(attribute); return CKR_OK; @@ -587,24 +591,25 @@ sftk_forceAttribute(SFTKObject *object,CK_ATTRIBUTE_TYPE type, * is allocated and needs to be freed with PORT_Free() When complete. */ char * -sftk_getString(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_getString(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; char *label = NULL; - attribute=sftk_FindAttribute(object,type); - if (attribute == NULL) return NULL; + attribute = sftk_FindAttribute(object, type); + if (attribute == NULL) + return NULL; if (attribute->attrib.pValue != NULL) { - label = (char *) PORT_Alloc(attribute->attrib.ulValueLen+1); - if (label == NULL) { - sftk_FreeAttribute(attribute); - return NULL; - } + label = (char *)PORT_Alloc(attribute->attrib.ulValueLen + 1); + if (label == NULL) { + sftk_FreeAttribute(attribute); + return NULL; + } - PORT_Memcpy(label,attribute->attrib.pValue, - attribute->attrib.ulValueLen); - label[attribute->attrib.ulValueLen] = 0; + PORT_Memcpy(label, attribute->attrib.pValue, + attribute->attrib.ulValueLen); + label[attribute->attrib.ulValueLen] = 0; } sftk_FreeAttribute(attribute); return label; @@ -612,88 +617,88 @@ sftk_getString(SFTKObject *object,CK_ATTRIBUTE_TYPE type) /* * decode when a particular attribute may be modified - * SFTK_NEVER: This attribute must be set at object creation time and + * SFTK_NEVER: This attribute must be set at object creation time and * can never be modified. - * SFTK_ONCOPY: This attribute may be modified only when you copy the + * SFTK_ONCOPY: This attribute may be modified only when you copy the * object. - * SFTK_SENSITIVE: The CKA_SENSITIVE attribute can only be changed from + * SFTK_SENSITIVE: The CKA_SENSITIVE attribute can only be changed from * CK_FALSE to CK_TRUE. - * SFTK_ALWAYS: This attribute can always be modified. - * Some attributes vary their modification type based on the class of the + * SFTK_ALWAYS: This attribute can always be modified. + * Some attributes vary their modification type based on the class of the * object. */ SFTKModifyType sftk_modifyType(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass) { /* if we don't know about it, user user defined, always allow modify */ - SFTKModifyType mtype = SFTK_ALWAYS; - - switch(type) { - /* NEVER */ - case CKA_CLASS: - case CKA_CERTIFICATE_TYPE: - case CKA_KEY_TYPE: - case CKA_MODULUS: - case CKA_MODULUS_BITS: - case CKA_PUBLIC_EXPONENT: - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME: - case CKA_SUBPRIME: - case CKA_BASE: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - case CKA_VALUE_LEN: - case CKA_ALWAYS_SENSITIVE: - case CKA_NEVER_EXTRACTABLE: - case CKA_NETSCAPE_DB: - mtype = SFTK_NEVER; - break; - - /* ONCOPY */ - case CKA_TOKEN: - case CKA_PRIVATE: - case CKA_MODIFIABLE: - mtype = SFTK_ONCOPY; - break; - - /* SENSITIVE */ - case CKA_SENSITIVE: - case CKA_EXTRACTABLE: - mtype = SFTK_SENSITIVE; - break; - - /* ALWAYS */ - case CKA_LABEL: - case CKA_APPLICATION: - case CKA_ID: - case CKA_SERIAL_NUMBER: - case CKA_START_DATE: - case CKA_END_DATE: - case CKA_DERIVE: - case CKA_ENCRYPT: - case CKA_DECRYPT: - case CKA_SIGN: - case CKA_VERIFY: - case CKA_SIGN_RECOVER: - case CKA_VERIFY_RECOVER: - case CKA_WRAP: - case CKA_UNWRAP: - mtype = SFTK_ALWAYS; - break; - - /* DEPENDS ON CLASS */ - case CKA_VALUE: - mtype = (inClass == CKO_DATA) ? SFTK_ALWAYS : SFTK_NEVER; - break; - - case CKA_SUBJECT: - mtype = (inClass == CKO_CERTIFICATE) ? SFTK_NEVER : SFTK_ALWAYS; - break; - default: - break; + SFTKModifyType mtype = SFTK_ALWAYS; + + switch (type) { + /* NEVER */ + case CKA_CLASS: + case CKA_CERTIFICATE_TYPE: + case CKA_KEY_TYPE: + case CKA_MODULUS: + case CKA_MODULUS_BITS: + case CKA_PUBLIC_EXPONENT: + case CKA_PRIVATE_EXPONENT: + case CKA_PRIME: + case CKA_SUBPRIME: + case CKA_BASE: + case CKA_PRIME_1: + case CKA_PRIME_2: + case CKA_EXPONENT_1: + case CKA_EXPONENT_2: + case CKA_COEFFICIENT: + case CKA_VALUE_LEN: + case CKA_ALWAYS_SENSITIVE: + case CKA_NEVER_EXTRACTABLE: + case CKA_NETSCAPE_DB: + mtype = SFTK_NEVER; + break; + + /* ONCOPY */ + case CKA_TOKEN: + case CKA_PRIVATE: + case CKA_MODIFIABLE: + mtype = SFTK_ONCOPY; + break; + + /* SENSITIVE */ + case CKA_SENSITIVE: + case CKA_EXTRACTABLE: + mtype = SFTK_SENSITIVE; + break; + + /* ALWAYS */ + case CKA_LABEL: + case CKA_APPLICATION: + case CKA_ID: + case CKA_SERIAL_NUMBER: + case CKA_START_DATE: + case CKA_END_DATE: + case CKA_DERIVE: + case CKA_ENCRYPT: + case CKA_DECRYPT: + case CKA_SIGN: + case CKA_VERIFY: + case CKA_SIGN_RECOVER: + case CKA_VERIFY_RECOVER: + case CKA_WRAP: + case CKA_UNWRAP: + mtype = SFTK_ALWAYS; + break; + + /* DEPENDS ON CLASS */ + case CKA_VALUE: + mtype = (inClass == CKO_DATA) ? SFTK_ALWAYS : SFTK_NEVER; + break; + + case CKA_SUBJECT: + mtype = (inClass == CKO_CERTIFICATE) ? SFTK_NEVER : SFTK_ALWAYS; + break; + default: + break; } return mtype; } @@ -703,68 +708,70 @@ sftk_modifyType(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass) PRBool sftk_isSensitive(CK_ATTRIBUTE_TYPE type, CK_OBJECT_CLASS inClass) { - switch(type) { - /* ALWAYS */ - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - return PR_TRUE; + switch (type) { + /* ALWAYS */ + case CKA_PRIVATE_EXPONENT: + case CKA_PRIME_1: + case CKA_PRIME_2: + case CKA_EXPONENT_1: + case CKA_EXPONENT_2: + case CKA_COEFFICIENT: + return PR_TRUE; - /* DEPENDS ON CLASS */ - case CKA_VALUE: - /* PRIVATE and SECRET KEYS have SENSITIVE values */ - return (PRBool)((inClass == CKO_PRIVATE_KEY) || (inClass == CKO_SECRET_KEY)); + /* DEPENDS ON CLASS */ + case CKA_VALUE: + /* PRIVATE and SECRET KEYS have SENSITIVE values */ + return (PRBool)((inClass == CKO_PRIVATE_KEY) || (inClass == CKO_SECRET_KEY)); - default: - break; + default: + break; } return PR_FALSE; } -/* +/* * copy an attribute into a SECItem. Secitem is allocated in the specified * arena. */ CK_RV -sftk_Attribute2SecItem(PLArenaPool *arena,SECItem *item,SFTKObject *object, - CK_ATTRIBUTE_TYPE type) +sftk_Attribute2SecItem(PLArenaPool *arena, SECItem *item, SFTKObject *object, + CK_ATTRIBUTE_TYPE type) { int len; SFTKAttribute *attribute; attribute = sftk_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; len = attribute->attrib.ulValueLen; if (arena) { - item->data = (unsigned char *) PORT_ArenaAlloc(arena,len); + item->data = (unsigned char *)PORT_ArenaAlloc(arena, len); } else { - item->data = (unsigned char *) PORT_Alloc(len); + item->data = (unsigned char *)PORT_Alloc(len); } if (item->data == NULL) { - sftk_FreeAttribute(attribute); - return CKR_HOST_MEMORY; + sftk_FreeAttribute(attribute); + return CKR_HOST_MEMORY; } item->len = len; - PORT_Memcpy(item->data,attribute->attrib.pValue, len); + PORT_Memcpy(item->data, attribute->attrib.pValue, len); sftk_FreeAttribute(attribute); return CKR_OK; } CK_RV sftk_GetULongAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, - CK_ULONG *longData) + CK_ULONG *longData) { SFTKAttribute *attribute; attribute = sftk_FindAttribute(object, type); - if (attribute == NULL) return CKR_TEMPLATE_INCOMPLETE; + if (attribute == NULL) + return CKR_TEMPLATE_INCOMPLETE; if (attribute->attrib.ulValueLen != sizeof(CK_ULONG)) { - return CKR_ATTRIBUTE_VALUE_INVALID; + return CKR_ATTRIBUTE_VALUE_INVALID; } *longData = *(CK_ULONG *)attribute->attrib.pValue; @@ -773,23 +780,26 @@ sftk_GetULongAttribute(SFTKObject *object, CK_ATTRIBUTE_TYPE type, } void -sftk_DeleteAttributeType(SFTKObject *object,CK_ATTRIBUTE_TYPE type) +sftk_DeleteAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type) { SFTKAttribute *attribute; attribute = sftk_FindAttribute(object, type); - if (attribute == NULL) return ; - sftk_DeleteAttribute(object,attribute); + if (attribute == NULL) + return; + sftk_DeleteAttribute(object, attribute); sftk_FreeAttribute(attribute); } CK_RV -sftk_AddAttributeType(SFTKObject *object,CK_ATTRIBUTE_TYPE type, - const void *valPtr, CK_ULONG length) +sftk_AddAttributeType(SFTKObject *object, CK_ATTRIBUTE_TYPE type, + const void *valPtr, CK_ULONG length) { SFTKAttribute *attribute; - attribute = sftk_NewAttribute(object,type,valPtr,length); - if (attribute == NULL) { return CKR_HOST_MEMORY; } - sftk_AddAttribute(object,attribute); + attribute = sftk_NewAttribute(object, type, valPtr, length); + if (attribute == NULL) { + return CKR_HOST_MEMORY; + } + sftk_AddAttribute(object, attribute); return CKR_OK; } @@ -810,17 +820,19 @@ sftk_lookupTokenKeyByHandle(SFTKSlot *slot, CK_OBJECT_HANDLE handle) * a new lock. We use separate functions for this just in case I'm wrong. */ static void -sftk_tokenKeyLock(SFTKSlot *slot) { +sftk_tokenKeyLock(SFTKSlot *slot) +{ SKIP_AFTER_FORK(PZ_Lock(slot->objectLock)); } static void -sftk_tokenKeyUnlock(SFTKSlot *slot) { +sftk_tokenKeyUnlock(SFTKSlot *slot) +{ SKIP_AFTER_FORK(PZ_Unlock(slot->objectLock)); } static PRIntn -sftk_freeHashItem(PLHashEntry* entry, PRIntn index, void *arg) +sftk_freeHashItem(PLHashEntry *entry, PRIntn index, void *arg) { SECItem *item = (SECItem *)entry->value; @@ -838,38 +850,36 @@ SFTK_ClearTokenKeyHashTable(SFTKSlot *slot) return CKR_OK; } - /* allocation hooks that allow us to recycle old object structures */ static SFTKObjectFreeList sessionObjectList = { NULL, NULL, 0 }; static SFTKObjectFreeList tokenObjectList = { NULL, NULL, 0 }; SFTKObject * -sftk_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace, - SFTKObjectFreeList *list, unsigned int hashSize, PRBool isSessionObject) +sftk_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace, + SFTKObjectFreeList *list, unsigned int hashSize, PRBool isSessionObject) { SFTKObject *object; int size = 0; if (!optimizeSpace) { - PZ_Lock(list->lock); - object = list->head; - if (object) { - list->head = object->next; - list->count--; - } - PZ_Unlock(list->lock); - if (object) { - object->next = object->prev = NULL; + PZ_Lock(list->lock); + object = list->head; + if (object) { + list->head = object->next; + list->count--; + } + PZ_Unlock(list->lock); + if (object) { + object->next = object->prev = NULL; *hasLocks = PR_TRUE; - return object; - } + return object; + } } - size = isSessionObject ? sizeof(SFTKSessionObject) - + hashSize *sizeof(SFTKAttribute *) : sizeof(SFTKTokenObject); + size = isSessionObject ? sizeof(SFTKSessionObject) + hashSize * sizeof(SFTKAttribute *) : sizeof(SFTKTokenObject); - object = (SFTKObject*)PORT_ZAlloc(size); + object = (SFTKObject *)PORT_ZAlloc(size); if (isSessionObject && object) { - ((SFTKSessionObject *)object)->hashSize = hashSize; + ((SFTKSessionObject *)object)->hashSize = hashSize; } *hasLocks = PR_FALSE; return object; @@ -877,70 +887,74 @@ sftk_GetObjectFromList(PRBool *hasLocks, PRBool optimizeSpace, static void sftk_PutObjectToList(SFTKObject *object, SFTKObjectFreeList *list, - PRBool isSessionObject) { + PRBool isSessionObject) +{ /* the code below is equivalent to : * optimizeSpace = isSessionObject ? object->optimizeSpace : PR_FALSE; * just faster. */ - PRBool optimizeSpace = isSessionObject && - ((SFTKSessionObject *)object)->optimizeSpace; - if (object->refLock && !optimizeSpace - && (list->count < MAX_OBJECT_LIST_SIZE)) { - PZ_Lock(list->lock); - object->next = list->head; - list->head = object; - list->count++; - PZ_Unlock(list->lock); - return; + PRBool optimizeSpace = isSessionObject && + ((SFTKSessionObject *)object)->optimizeSpace; + if (object->refLock && !optimizeSpace && (list->count < MAX_OBJECT_LIST_SIZE)) { + PZ_Lock(list->lock); + object->next = list->head; + list->head = object; + list->count++; + PZ_Unlock(list->lock); + return; } if (isSessionObject) { - SFTKSessionObject *so = (SFTKSessionObject *)object; - PZ_DestroyLock(so->attributeLock); - so->attributeLock = NULL; + SFTKSessionObject *so = (SFTKSessionObject *)object; + PZ_DestroyLock(so->attributeLock); + so->attributeLock = NULL; } if (object->refLock) { - PZ_DestroyLock(object->refLock); - object->refLock = NULL; + PZ_DestroyLock(object->refLock); + object->refLock = NULL; } PORT_Free(object); } static SFTKObject * -sftk_freeObjectData(SFTKObject *object) { - SFTKObject *next = object->next; +sftk_freeObjectData(SFTKObject *object) +{ + SFTKObject *next = object->next; - PORT_Free(object); - return next; + PORT_Free(object); + return next; } static void sftk_InitFreeList(SFTKObjectFreeList *list) { - list->lock = PZ_NewLock(nssILockObject); + if (!list->lock) { + list->lock = PZ_NewLock(nssILockObject); + } } -void sftk_InitFreeLists(void) +void +sftk_InitFreeLists(void) { sftk_InitFreeList(&sessionObjectList); sftk_InitFreeList(&tokenObjectList); } - + static void sftk_CleanupFreeList(SFTKObjectFreeList *list, PRBool isSessionList) { SFTKObject *object; if (!list->lock) { - return; + return; } SKIP_AFTER_FORK(PZ_Lock(list->lock)); - for (object= list->head; object != NULL; - object = sftk_freeObjectData(object)) { - PZ_DestroyLock(object->refLock); - if (isSessionList) { - PZ_DestroyLock(((SFTKSessionObject *)object)->attributeLock); - } + for (object = list->head; object != NULL; + object = sftk_freeObjectData(object)) { + PZ_DestroyLock(object->refLock); + if (isSessionList) { + PZ_DestroyLock(((SFTKSessionObject *)object)->attributeLock); + } } list->count = 0; list->head = NULL; @@ -956,7 +970,6 @@ sftk_CleanupFreeLists(void) sftk_CleanupFreeList(&tokenObjectList, PR_FALSE); } - /* * Create a new object */ @@ -969,46 +982,47 @@ sftk_NewObject(SFTKSlot *slot) unsigned int i; unsigned int hashSize = 0; - hashSize = (slot->optimizeSpace) ? SPACE_ATTRIBUTE_HASH_SIZE : - TIME_ATTRIBUTE_HASH_SIZE; + hashSize = (slot->optimizeSpace) ? SPACE_ATTRIBUTE_HASH_SIZE : TIME_ATTRIBUTE_HASH_SIZE; object = sftk_GetObjectFromList(&hasLocks, slot->optimizeSpace, - &sessionObjectList, hashSize, PR_TRUE); + &sessionObjectList, hashSize, PR_TRUE); if (object == NULL) { - return NULL; + return NULL; } sessObject = (SFTKSessionObject *)object; sessObject->nextAttr = 0; - for (i=0; i < MAX_OBJS_ATTRS; i++) { - sessObject->attrList[i].attrib.pValue = NULL; - sessObject->attrList[i].freeData = PR_FALSE; + for (i = 0; i < MAX_OBJS_ATTRS; i++) { + sessObject->attrList[i].attrib.pValue = NULL; + sessObject->attrList[i].freeData = PR_FALSE; } sessObject->optimizeSpace = slot->optimizeSpace; object->handle = 0; object->next = object->prev = NULL; object->slot = slot; - + object->refCount = 1; sessObject->sessionList.next = NULL; sessObject->sessionList.prev = NULL; sessObject->sessionList.parent = object; sessObject->session = NULL; sessObject->wasDerived = PR_FALSE; - if (!hasLocks) object->refLock = PZ_NewLock(nssILockRefLock); + if (!hasLocks) + object->refLock = PZ_NewLock(nssILockRefLock); if (object->refLock == NULL) { - PORT_Free(object); - return NULL; + PORT_Free(object); + return NULL; } - if (!hasLocks) sessObject->attributeLock = PZ_NewLock(nssILockAttribute); + if (!hasLocks) + sessObject->attributeLock = PZ_NewLock(nssILockAttribute); if (sessObject->attributeLock == NULL) { - PZ_DestroyLock(object->refLock); - PORT_Free(object); - return NULL; + PZ_DestroyLock(object->refLock); + PORT_Free(object); + return NULL; } - for (i=0; i < sessObject->hashSize; i++) { - sessObject->head[i] = NULL; + for (i = 0; i < sessObject->hashSize; i++) { + sessObject->head[i] = NULL; } object->objectInfo = NULL; object->infoFree = NULL; @@ -1018,21 +1032,21 @@ sftk_NewObject(SFTKSlot *slot) static CK_RV sftk_DestroySessionObjectData(SFTKSessionObject *so) { - int i; + int i; - for (i=0; i < MAX_OBJS_ATTRS; i++) { - unsigned char *value = so->attrList[i].attrib.pValue; - if (value) { - PORT_Memset(value,0,so->attrList[i].attrib.ulValueLen); - if (so->attrList[i].freeData) { - PORT_Free(value); - } - so->attrList[i].attrib.pValue = NULL; - so->attrList[i].freeData = PR_FALSE; - } - } -/* PZ_DestroyLock(so->attributeLock);*/ - return CKR_OK; + for (i = 0; i < MAX_OBJS_ATTRS; i++) { + unsigned char *value = so->attrList[i].attrib.pValue; + if (value) { + PORT_Memset(value, 0, so->attrList[i].attrib.ulValueLen); + if (so->attrList[i].freeData) { + PORT_Free(value); + } + so->attrList[i].attrib.pValue = NULL; + so->attrList[i].freeData = PR_FALSE; + } + } + /* PZ_DestroyLock(so->attributeLock);*/ + return CKR_OK; } /* @@ -1050,23 +1064,23 @@ sftk_DestroyObject(SFTKObject *object) /* delete the database value */ if (to) { - if (to->dbKey.data) { - PORT_Free(to->dbKey.data); - to->dbKey.data = NULL; - } - } + if (to->dbKey.data) { + PORT_Free(to->dbKey.data); + to->dbKey.data = NULL; + } + } if (so) { - sftk_DestroySessionObjectData(so); + sftk_DestroySessionObjectData(so); } if (object->objectInfo) { - (*object->infoFree)(object->objectInfo); - object->objectInfo = NULL; - object->infoFree = NULL; + (*object->infoFree)(object->objectInfo); + object->objectInfo = NULL; + object->infoFree = NULL; } if (so) { - sftk_PutObjectToList(object,&sessionObjectList,PR_TRUE); + sftk_PutObjectToList(object, &sessionObjectList, PR_TRUE); } else { - sftk_PutObjectToList(object,&tokenObjectList,PR_FALSE); + sftk_PutObjectToList(object, &tokenObjectList, PR_FALSE); } return crv; } @@ -1086,17 +1100,17 @@ sftk_ObjectFromHandleOnSlot(CK_OBJECT_HANDLE handle, SFTKSlot *slot) PRUint32 index = sftk_hash(handle, slot->sessObjHashSize); if (sftk_isToken(handle)) { - return sftk_NewTokenObject(slot, NULL, handle); + return sftk_NewTokenObject(slot, NULL, handle); } PZ_Lock(slot->objectLock); sftkqueue_find2(object, handle, index, slot->sessObjHashTable); if (object) { - sftk_ReferenceObject(object); + sftk_ReferenceObject(object); } PZ_Unlock(slot->objectLock); - return(object); + return (object); } /* * look up and object structure from a handle. OBJECT_Handles only make @@ -1108,10 +1122,9 @@ sftk_ObjectFromHandle(CK_OBJECT_HANDLE handle, SFTKSession *session) { SFTKSlot *slot = sftk_SlotFromSession(session); - return sftk_ObjectFromHandleOnSlot(handle,slot); + return sftk_ObjectFromHandleOnSlot(handle, slot); } - /* * release a reference to an object handle */ @@ -1122,20 +1135,21 @@ sftk_FreeObject(SFTKObject *object) CK_RV crv; PZ_Lock(object->refLock); - if (object->refCount == 1) destroy = PR_TRUE; + if (object->refCount == 1) + destroy = PR_TRUE; object->refCount--; PZ_Unlock(object->refLock); if (destroy) { - crv = sftk_DestroyObject(object); - if (crv != CKR_OK) { - return SFTK_DestroyFailure; - } - return SFTK_Destroyed; + crv = sftk_DestroyObject(object); + if (crv != CKR_OK) { + return SFTK_DestroyFailure; + } + return SFTK_Destroyed; } return SFTK_Busy; } - + /* * add an object to a slot and session queue. These two functions * adopt the object. @@ -1157,14 +1171,14 @@ sftk_AddObject(SFTKSession *session, SFTKObject *object) SFTKSessionObject *so = sftk_narrowToSessionObject(object); if (so) { - PZ_Lock(session->objectLock); - sftkqueue_add(&so->sessionList,0,session->objects,0); - so->session = session; - PZ_Unlock(session->objectLock); + PZ_Lock(session->objectLock); + sftkqueue_add(&so->sessionList, 0, session->objects, 0); + so->session = session; + PZ_Unlock(session->objectLock); } - sftk_AddSlotObject(slot,object); + sftk_AddSlotObject(slot, object); sftk_ReferenceObject(object); -} +} /* * delete an object from a slot and session queue @@ -1179,24 +1193,24 @@ sftk_DeleteObject(SFTKSession *session, SFTKObject *object) /* Handle Token case */ if (so && so->session) { - SFTKSession *session = so->session; - PZ_Lock(session->objectLock); - sftkqueue_delete(&so->sessionList,0,session->objects,0); - PZ_Unlock(session->objectLock); - PZ_Lock(slot->objectLock); - sftkqueue_delete2(object, object->handle, index, slot->sessObjHashTable); - PZ_Unlock(slot->objectLock); - sftkqueue_clear_deleted_element(object); - sftk_FreeObject(object); /* free the reference owned by the queue */ + SFTKSession *session = so->session; + PZ_Lock(session->objectLock); + sftkqueue_delete(&so->sessionList, 0, session->objects, 0); + PZ_Unlock(session->objectLock); + PZ_Lock(slot->objectLock); + sftkqueue_delete2(object, object->handle, index, slot->sessObjHashTable); + PZ_Unlock(slot->objectLock); + sftkqueue_clear_deleted_element(object); + sftk_FreeObject(object); /* free the reference owned by the queue */ } else { - SFTKDBHandle *handle = sftk_getDBForTokenObject(slot, object->handle); + SFTKDBHandle *handle = sftk_getDBForTokenObject(slot, object->handle); #ifdef DEBUG SFTKTokenObject *to = sftk_narrowToTokenObject(object); - PORT_Assert(to); + PORT_Assert(to); #endif - crv = sftkdb_DestroyObject(handle, object->handle); - sftk_freeDB(handle); - } + crv = sftkdb_DestroyObject(handle, object->handle); + sftk_freeDB(handle); + } return crv; } @@ -1208,144 +1222,144 @@ sftk_DeleteObject(SFTKSession *session, SFTKObject *object) static const CK_ATTRIBUTE_TYPE commonAttrs[] = { CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_MODIFIABLE }; -static const CK_ULONG commonAttrsCount = - sizeof(commonAttrs)/sizeof(commonAttrs[0]); +static const CK_ULONG commonAttrsCount = + sizeof(commonAttrs) / sizeof(commonAttrs[0]); static const CK_ATTRIBUTE_TYPE commonKeyAttrs[] = { CKA_ID, CKA_START_DATE, CKA_END_DATE, CKA_DERIVE, CKA_LOCAL, CKA_KEY_TYPE }; -static const CK_ULONG commonKeyAttrsCount = - sizeof(commonKeyAttrs)/sizeof(commonKeyAttrs[0]); +static const CK_ULONG commonKeyAttrsCount = + sizeof(commonKeyAttrs) / sizeof(commonKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE secretKeyAttrs[] = { CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_ENCRYPT, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, CKA_WRAP, CKA_UNWRAP, CKA_VALUE }; -static const CK_ULONG secretKeyAttrsCount = - sizeof(secretKeyAttrs)/sizeof(secretKeyAttrs[0]); +static const CK_ULONG secretKeyAttrsCount = + sizeof(secretKeyAttrs) / sizeof(secretKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE commonPubKeyAttrs[] = { CKA_ENCRYPT, CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_WRAP, CKA_SUBJECT }; -static const CK_ULONG commonPubKeyAttrsCount = - sizeof(commonPubKeyAttrs)/sizeof(commonPubKeyAttrs[0]); +static const CK_ULONG commonPubKeyAttrsCount = + sizeof(commonPubKeyAttrs) / sizeof(commonPubKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE rsaPubKeyAttrs[] = { CKA_MODULUS, CKA_PUBLIC_EXPONENT }; -static const CK_ULONG rsaPubKeyAttrsCount = - sizeof(rsaPubKeyAttrs)/sizeof(rsaPubKeyAttrs[0]); +static const CK_ULONG rsaPubKeyAttrsCount = + sizeof(rsaPubKeyAttrs) / sizeof(rsaPubKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE dsaPubKeyAttrs[] = { CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE }; -static const CK_ULONG dsaPubKeyAttrsCount = - sizeof(dsaPubKeyAttrs)/sizeof(dsaPubKeyAttrs[0]); +static const CK_ULONG dsaPubKeyAttrsCount = + sizeof(dsaPubKeyAttrs) / sizeof(dsaPubKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE dhPubKeyAttrs[] = { CKA_PRIME, CKA_BASE, CKA_VALUE }; -static const CK_ULONG dhPubKeyAttrsCount = - sizeof(dhPubKeyAttrs)/sizeof(dhPubKeyAttrs[0]); +static const CK_ULONG dhPubKeyAttrsCount = + sizeof(dhPubKeyAttrs) / sizeof(dhPubKeyAttrs[0]); #ifndef NSS_DISABLE_ECC static const CK_ATTRIBUTE_TYPE ecPubKeyAttrs[] = { CKA_EC_PARAMS, CKA_EC_POINT }; -static const CK_ULONG ecPubKeyAttrsCount = - sizeof(ecPubKeyAttrs)/sizeof(ecPubKeyAttrs[0]); +static const CK_ULONG ecPubKeyAttrsCount = + sizeof(ecPubKeyAttrs) / sizeof(ecPubKeyAttrs[0]); #endif static const CK_ATTRIBUTE_TYPE commonPrivKeyAttrs[] = { CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER, CKA_UNWRAP, CKA_SUBJECT, CKA_SENSITIVE, CKA_EXTRACTABLE, CKA_NETSCAPE_DB }; -static const CK_ULONG commonPrivKeyAttrsCount = - sizeof(commonPrivKeyAttrs)/sizeof(commonPrivKeyAttrs[0]); +static const CK_ULONG commonPrivKeyAttrsCount = + sizeof(commonPrivKeyAttrs) / sizeof(commonPrivKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE rsaPrivKeyAttrs[] = { - CKA_MODULUS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, + CKA_MODULUS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT }; -static const CK_ULONG rsaPrivKeyAttrsCount = - sizeof(rsaPrivKeyAttrs)/sizeof(rsaPrivKeyAttrs[0]); +static const CK_ULONG rsaPrivKeyAttrsCount = + sizeof(rsaPrivKeyAttrs) / sizeof(rsaPrivKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE dsaPrivKeyAttrs[] = { CKA_SUBPRIME, CKA_PRIME, CKA_BASE, CKA_VALUE }; -static const CK_ULONG dsaPrivKeyAttrsCount = - sizeof(dsaPrivKeyAttrs)/sizeof(dsaPrivKeyAttrs[0]); +static const CK_ULONG dsaPrivKeyAttrsCount = + sizeof(dsaPrivKeyAttrs) / sizeof(dsaPrivKeyAttrs[0]); static const CK_ATTRIBUTE_TYPE dhPrivKeyAttrs[] = { CKA_PRIME, CKA_BASE, CKA_VALUE }; -static const CK_ULONG dhPrivKeyAttrsCount = - sizeof(dhPrivKeyAttrs)/sizeof(dhPrivKeyAttrs[0]); +static const CK_ULONG dhPrivKeyAttrsCount = + sizeof(dhPrivKeyAttrs) / sizeof(dhPrivKeyAttrs[0]); #ifndef NSS_DISABLE_ECC static const CK_ATTRIBUTE_TYPE ecPrivKeyAttrs[] = { CKA_EC_PARAMS, CKA_VALUE }; -static const CK_ULONG ecPrivKeyAttrsCount = - sizeof(ecPrivKeyAttrs)/sizeof(ecPrivKeyAttrs[0]); +static const CK_ULONG ecPrivKeyAttrsCount = + sizeof(ecPrivKeyAttrs) / sizeof(ecPrivKeyAttrs[0]); #endif static const CK_ATTRIBUTE_TYPE certAttrs[] = { CKA_CERTIFICATE_TYPE, CKA_VALUE, CKA_SUBJECT, CKA_ISSUER, CKA_SERIAL_NUMBER }; -static const CK_ULONG certAttrsCount = - sizeof(certAttrs)/sizeof(certAttrs[0]); +static const CK_ULONG certAttrsCount = + sizeof(certAttrs) / sizeof(certAttrs[0]); static const CK_ATTRIBUTE_TYPE trustAttrs[] = { CKA_ISSUER, CKA_SERIAL_NUMBER, CKA_CERT_SHA1_HASH, CKA_CERT_MD5_HASH, CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, CKA_TRUST_EMAIL_PROTECTION, CKA_TRUST_CODE_SIGNING, CKA_TRUST_STEP_UP_APPROVED }; -static const CK_ULONG trustAttrsCount = - sizeof(trustAttrs)/sizeof(trustAttrs[0]); +static const CK_ULONG trustAttrsCount = + sizeof(trustAttrs) / sizeof(trustAttrs[0]); static const CK_ATTRIBUTE_TYPE smimeAttrs[] = { CKA_SUBJECT, CKA_NETSCAPE_EMAIL, CKA_NETSCAPE_SMIME_TIMESTAMP, CKA_VALUE }; -static const CK_ULONG smimeAttrsCount = - sizeof(smimeAttrs)/sizeof(smimeAttrs[0]); +static const CK_ULONG smimeAttrsCount = + sizeof(smimeAttrs) / sizeof(smimeAttrs[0]); static const CK_ATTRIBUTE_TYPE crlAttrs[] = { CKA_SUBJECT, CKA_VALUE, CKA_NETSCAPE_URL, CKA_NETSCAPE_KRL }; -static const CK_ULONG crlAttrsCount = - sizeof(crlAttrs)/sizeof(crlAttrs[0]); +static const CK_ULONG crlAttrsCount = + sizeof(crlAttrs) / sizeof(crlAttrs[0]); /* copy an object based on it's table */ CK_RV -stfk_CopyTokenAttributes(SFTKObject *destObject,SFTKTokenObject *src_to, - const CK_ATTRIBUTE_TYPE *attrArray, CK_ULONG attrCount) +stfk_CopyTokenAttributes(SFTKObject *destObject, SFTKTokenObject *src_to, + const CK_ATTRIBUTE_TYPE *attrArray, CK_ULONG attrCount) { SFTKAttribute *attribute; SFTKAttribute *newAttribute; CK_RV crv = CKR_OK; unsigned int i; - for (i=0; i < attrCount; i++) { - if (!sftk_hasAttribute(destObject,attrArray[i])) { - attribute =sftk_FindAttribute(&src_to->obj, attrArray[i]); - if (!attribute) { - continue; /* return CKR_ATTRIBUTE_VALUE_INVALID; */ - } - /* we need to copy the attribute since each attribute - * only has one set of link list pointers */ - newAttribute = sftk_NewAttribute( destObject, - sftk_attr_expand(&attribute->attrib)); - sftk_FreeAttribute(attribute); /* free the old attribute */ - if (!newAttribute) { - return CKR_HOST_MEMORY; - } - sftk_AddAttribute(destObject,newAttribute); - } + for (i = 0; i < attrCount; i++) { + if (!sftk_hasAttribute(destObject, attrArray[i])) { + attribute = sftk_FindAttribute(&src_to->obj, attrArray[i]); + if (!attribute) { + continue; /* return CKR_ATTRIBUTE_VALUE_INVALID; */ + } + /* we need to copy the attribute since each attribute + * only has one set of link list pointers */ + newAttribute = sftk_NewAttribute(destObject, + sftk_attr_expand(&attribute->attrib)); + sftk_FreeAttribute(attribute); /* free the old attribute */ + if (!newAttribute) { + return CKR_HOST_MEMORY; + } + sftk_AddAttribute(destObject, newAttribute); + } } return crv; } CK_RV -stfk_CopyTokenPrivateKey(SFTKObject *destObject,SFTKTokenObject *src_to) +stfk_CopyTokenPrivateKey(SFTKObject *destObject, SFTKTokenObject *src_to) { CK_RV crv; CK_KEY_TYPE key_type; @@ -1353,60 +1367,60 @@ stfk_CopyTokenPrivateKey(SFTKObject *destObject,SFTKTokenObject *src_to) /* copy the common attributes for all keys first */ crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs, - commonKeyAttrsCount); + commonKeyAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } /* copy the common attributes for all private keys next */ crv = stfk_CopyTokenAttributes(destObject, src_to, commonPrivKeyAttrs, - commonPrivKeyAttrsCount); + commonPrivKeyAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } - attribute =sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE); + attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE); PORT_Assert(attribute); /* if it wasn't here, ww should have failed - * copying the common attributes */ + * copying the common attributes */ if (!attribute) { - /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but - * the fact is, the only reason we couldn't get the attribute would - * be a memory error or database error (an error in the 'device'). - * if we have a database error code, we could return it here */ - crv = CKR_DEVICE_ERROR; - goto fail; + /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but + * the fact is, the only reason we couldn't get the attribute would + * be a memory error or database error (an error in the 'device'). + * if we have a database error code, we could return it here */ + crv = CKR_DEVICE_ERROR; + goto fail; } key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue; sftk_FreeAttribute(attribute); - + /* finally copy the attributes for various private key types */ switch (key_type) { - case CKK_RSA: - crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPrivKeyAttrs, - rsaPrivKeyAttrsCount); - break; - case CKK_DSA: - crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPrivKeyAttrs, - dsaPrivKeyAttrsCount); - break; - case CKK_DH: - crv = stfk_CopyTokenAttributes(destObject, src_to, dhPrivKeyAttrs, - dhPrivKeyAttrsCount); - break; + case CKK_RSA: + crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPrivKeyAttrs, + rsaPrivKeyAttrsCount); + break; + case CKK_DSA: + crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPrivKeyAttrs, + dsaPrivKeyAttrsCount); + break; + case CKK_DH: + crv = stfk_CopyTokenAttributes(destObject, src_to, dhPrivKeyAttrs, + dhPrivKeyAttrsCount); + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - crv = stfk_CopyTokenAttributes(destObject, src_to, ecPrivKeyAttrs, - ecPrivKeyAttrsCount); - break; + case CKK_EC: + crv = stfk_CopyTokenAttributes(destObject, src_to, ecPrivKeyAttrs, + ecPrivKeyAttrsCount); + break; #endif - default: - crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types - * of token keys into our database. */ + default: + crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types + * of token keys into our database. */ } fail: return crv; } CK_RV -stfk_CopyTokenPublicKey(SFTKObject *destObject,SFTKTokenObject *src_to) +stfk_CopyTokenPublicKey(SFTKObject *destObject, SFTKTokenObject *src_to) { CK_RV crv; CK_KEY_TYPE key_type; @@ -1414,69 +1428,69 @@ stfk_CopyTokenPublicKey(SFTKObject *destObject,SFTKTokenObject *src_to) /* copy the common attributes for all keys first */ crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs, - commonKeyAttrsCount); + commonKeyAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } /* copy the common attributes for all public keys next */ crv = stfk_CopyTokenAttributes(destObject, src_to, commonPubKeyAttrs, - commonPubKeyAttrsCount); + commonPubKeyAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } - attribute =sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE); + attribute = sftk_FindAttribute(&src_to->obj, CKA_KEY_TYPE); PORT_Assert(attribute); /* if it wasn't here, ww should have failed - * copying the common attributes */ + * copying the common attributes */ if (!attribute) { - /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but - * the fact is, the only reason we couldn't get the attribute would - * be a memory error or database error (an error in the 'device'). - * if we have a database error code, we could return it here */ - crv = CKR_DEVICE_ERROR; - goto fail; + /* OK, so CKR_ATTRIBUTE_VALUE_INVALID is the immediate error, but + * the fact is, the only reason we couldn't get the attribute would + * be a memory error or database error (an error in the 'device'). + * if we have a database error code, we could return it here */ + crv = CKR_DEVICE_ERROR; + goto fail; } key_type = *(CK_KEY_TYPE *)attribute->attrib.pValue; sftk_FreeAttribute(attribute); - + /* finally copy the attributes for various public key types */ switch (key_type) { - case CKK_RSA: - crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPubKeyAttrs, - rsaPubKeyAttrsCount); - break; - case CKK_DSA: - crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPubKeyAttrs, - dsaPubKeyAttrsCount); - break; - case CKK_DH: - crv = stfk_CopyTokenAttributes(destObject, src_to, dhPubKeyAttrs, - dhPubKeyAttrsCount); - break; + case CKK_RSA: + crv = stfk_CopyTokenAttributes(destObject, src_to, rsaPubKeyAttrs, + rsaPubKeyAttrsCount); + break; + case CKK_DSA: + crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPubKeyAttrs, + dsaPubKeyAttrsCount); + break; + case CKK_DH: + crv = stfk_CopyTokenAttributes(destObject, src_to, dhPubKeyAttrs, + dhPubKeyAttrsCount); + break; #ifndef NSS_DISABLE_ECC - case CKK_EC: - crv = stfk_CopyTokenAttributes(destObject, src_to, ecPubKeyAttrs, - ecPubKeyAttrsCount); - break; + case CKK_EC: + crv = stfk_CopyTokenAttributes(destObject, src_to, ecPubKeyAttrs, + ecPubKeyAttrsCount); + break; #endif - default: - crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types - * of token keys into our database. */ + default: + crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types + * of token keys into our database. */ } fail: return crv; } CK_RV -stfk_CopyTokenSecretKey(SFTKObject *destObject,SFTKTokenObject *src_to) +stfk_CopyTokenSecretKey(SFTKObject *destObject, SFTKTokenObject *src_to) { CK_RV crv; crv = stfk_CopyTokenAttributes(destObject, src_to, commonKeyAttrs, - commonKeyAttrsCount); + commonKeyAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } crv = stfk_CopyTokenAttributes(destObject, src_to, secretKeyAttrs, - secretKeyAttrsCount); + secretKeyAttrsCount); fail: return crv; } @@ -1487,50 +1501,50 @@ fail: * the token itself. */ CK_RV -sftk_CopyTokenObject(SFTKObject *destObject,SFTKObject *srcObject) +sftk_CopyTokenObject(SFTKObject *destObject, SFTKObject *srcObject) { SFTKTokenObject *src_to = sftk_narrowToTokenObject(srcObject); CK_RV crv; PORT_Assert(src_to); if (src_to == NULL) { - return CKR_DEVICE_ERROR; /* internal state inconsistant */ + return CKR_DEVICE_ERROR; /* internal state inconsistant */ } crv = stfk_CopyTokenAttributes(destObject, src_to, commonAttrs, - commonAttrsCount); + commonAttrsCount); if (crv != CKR_OK) { - goto fail; + goto fail; } switch (src_to->obj.objclass) { - case CKO_CERTIFICATE: - crv = stfk_CopyTokenAttributes(destObject, src_to, certAttrs, - certAttrsCount); - break; - case CKO_NETSCAPE_TRUST: - crv = stfk_CopyTokenAttributes(destObject, src_to, trustAttrs, - trustAttrsCount); - break; - case CKO_NETSCAPE_SMIME: - crv = stfk_CopyTokenAttributes(destObject, src_to, smimeAttrs, - smimeAttrsCount); - break; - case CKO_NETSCAPE_CRL: - crv = stfk_CopyTokenAttributes(destObject, src_to, crlAttrs, - crlAttrsCount); - break; - case CKO_PRIVATE_KEY: - crv = stfk_CopyTokenPrivateKey(destObject,src_to); - break; - case CKO_PUBLIC_KEY: - crv = stfk_CopyTokenPublicKey(destObject,src_to); - break; - case CKO_SECRET_KEY: - crv = stfk_CopyTokenSecretKey(destObject,src_to); - break; - default: - crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types - * of token keys into our database. */ + case CKO_CERTIFICATE: + crv = stfk_CopyTokenAttributes(destObject, src_to, certAttrs, + certAttrsCount); + break; + case CKO_NETSCAPE_TRUST: + crv = stfk_CopyTokenAttributes(destObject, src_to, trustAttrs, + trustAttrsCount); + break; + case CKO_NETSCAPE_SMIME: + crv = stfk_CopyTokenAttributes(destObject, src_to, smimeAttrs, + smimeAttrsCount); + break; + case CKO_NETSCAPE_CRL: + crv = stfk_CopyTokenAttributes(destObject, src_to, crlAttrs, + crlAttrsCount); + break; + case CKO_PRIVATE_KEY: + crv = stfk_CopyTokenPrivateKey(destObject, src_to); + break; + case CKO_PUBLIC_KEY: + crv = stfk_CopyTokenPublicKey(destObject, src_to); + break; + case CKO_SECRET_KEY: + crv = stfk_CopyTokenSecretKey(destObject, src_to); + break; + default: + crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types + * of token keys into our database. */ } fail: return crv; @@ -1542,35 +1556,35 @@ fail: * grabs the attribute locks for the src object for a *long* time. */ CK_RV -sftk_CopyObject(SFTKObject *destObject,SFTKObject *srcObject) +sftk_CopyObject(SFTKObject *destObject, SFTKObject *srcObject) { SFTKAttribute *attribute; SFTKSessionObject *src_so = sftk_narrowToSessionObject(srcObject); unsigned int i; if (src_so == NULL) { - return sftk_CopyTokenObject(destObject,srcObject); + return sftk_CopyTokenObject(destObject, srcObject); } PZ_Lock(src_so->attributeLock); - for(i=0; i < src_so->hashSize; i++) { - attribute = src_so->head[i]; - do { - if (attribute) { - if (!sftk_hasAttribute(destObject,attribute->handle)) { - /* we need to copy the attribute since each attribute - * only has one set of link list pointers */ - SFTKAttribute *newAttribute = sftk_NewAttribute( - destObject,sftk_attr_expand(&attribute->attrib)); - if (newAttribute == NULL) { - PZ_Unlock(src_so->attributeLock); - return CKR_HOST_MEMORY; - } - sftk_AddAttribute(destObject,newAttribute); - } - attribute=attribute->next; - } - } while (attribute != NULL); + for (i = 0; i < src_so->hashSize; i++) { + attribute = src_so->head[i]; + do { + if (attribute) { + if (!sftk_hasAttribute(destObject, attribute->handle)) { + /* we need to copy the attribute since each attribute + * only has one set of link list pointers */ + SFTKAttribute *newAttribute = sftk_NewAttribute( + destObject, sftk_attr_expand(&attribute->attrib)); + if (newAttribute == NULL) { + PZ_Unlock(src_so->attributeLock); + return CKR_HOST_MEMORY; + } + sftk_AddAttribute(destObject, newAttribute); + } + attribute = attribute->next; + } + } while (attribute != NULL); } PZ_Unlock(src_so->attributeLock); @@ -1583,42 +1597,42 @@ sftk_CopyObject(SFTKObject *destObject,SFTKObject *srcObject) /* add an object to a search list */ CK_RV -AddToList(SFTKObjectListElement **list,SFTKObject *object) +AddToList(SFTKObjectListElement **list, SFTKObject *object) { - SFTKObjectListElement *newElem = - (SFTKObjectListElement *)PORT_Alloc(sizeof(SFTKObjectListElement)); + SFTKObjectListElement *newElem = + (SFTKObjectListElement *)PORT_Alloc(sizeof(SFTKObjectListElement)); - if (newElem == NULL) return CKR_HOST_MEMORY; + if (newElem == NULL) + return CKR_HOST_MEMORY; - newElem->next = *list; - newElem->object = object; - sftk_ReferenceObject(object); + newElem->next = *list; + newElem->object = object; + sftk_ReferenceObject(object); *list = newElem; return CKR_OK; } - /* return true if the object matches the template */ PRBool -sftk_objectMatch(SFTKObject *object,CK_ATTRIBUTE_PTR theTemplate,int count) +sftk_objectMatch(SFTKObject *object, CK_ATTRIBUTE_PTR theTemplate, int count) { int i; - for (i=0; i < count; i++) { - SFTKAttribute *attribute = sftk_FindAttribute(object,theTemplate[i].type); - if (attribute == NULL) { - return PR_FALSE; - } - if (attribute->attrib.ulValueLen == theTemplate[i].ulValueLen) { - if (PORT_Memcmp(attribute->attrib.pValue,theTemplate[i].pValue, - theTemplate[i].ulValueLen) == 0) { - sftk_FreeAttribute(attribute); - continue; - } - } + for (i = 0; i < count; i++) { + SFTKAttribute *attribute = sftk_FindAttribute(object, theTemplate[i].type); + if (attribute == NULL) { + return PR_FALSE; + } + if (attribute->attrib.ulValueLen == theTemplate[i].ulValueLen) { + if (PORT_Memcmp(attribute->attrib.pValue, theTemplate[i].pValue, + theTemplate[i].ulValueLen) == 0) { + sftk_FreeAttribute(attribute); + continue; + } + } sftk_FreeAttribute(attribute); - return PR_FALSE; + return PR_FALSE; } return PR_TRUE; } @@ -1627,25 +1641,26 @@ sftk_objectMatch(SFTKObject *object,CK_ATTRIBUTE_PTR theTemplate,int count) * in the object list. */ CK_RV -sftk_searchObjectList(SFTKSearchResults *search,SFTKObject **head, - unsigned int size, PZLock *lock, CK_ATTRIBUTE_PTR theTemplate, - int count, PRBool isLoggedIn) +sftk_searchObjectList(SFTKSearchResults *search, SFTKObject **head, + unsigned int size, PZLock *lock, CK_ATTRIBUTE_PTR theTemplate, + int count, PRBool isLoggedIn) { unsigned int i; SFTKObject *object; CK_RV crv = CKR_OK; - for(i=0; i < size; i++) { + for (i = 0; i < size; i++) { /* We need to hold the lock to copy a consistant version of * the linked list. */ PZ_Lock(lock); - for (object = head[i]; object != NULL; object= object->next) { - if (sftk_objectMatch(object,theTemplate,count)) { - /* don't return objects that aren't yet visible */ - if ((!isLoggedIn) && sftk_isTrue(object,CKA_PRIVATE)) continue; - sftk_addHandle(search,object->handle); - } - } + for (object = head[i]; object != NULL; object = object->next) { + if (sftk_objectMatch(object, theTemplate, count)) { + /* don't return objects that aren't yet visible */ + if ((!isLoggedIn) && sftk_isTrue(object, CKA_PRIVATE)) + continue; + sftk_addHandle(search, object->handle); + } + } PZ_Unlock(lock); } return crv; @@ -1670,7 +1685,8 @@ sftk_FreeObjectList(SFTKObjectListElement *objectList) { SFTKObjectListElement *ol; - for (ol= objectList; ol != NULL; ol = sftk_FreeObjectListElement(ol)) {} + for (ol = objectList; ol != NULL; ol = sftk_FreeObjectListElement(ol)) { + } } /* @@ -1680,7 +1696,7 @@ void sftk_FreeSearch(SFTKSearchResults *search) { if (search->handles) { - PORT_Free(search->handles); + PORT_Free(search->handles); } PORT_Free(search); } @@ -1692,22 +1708,22 @@ sftk_FreeSearch(SFTKSearchResults *search) /* update the sessions state based in it's flags and wether or not it's * logged in */ void -sftk_update_state(SFTKSlot *slot,SFTKSession *session) +sftk_update_state(SFTKSlot *slot, SFTKSession *session) { if (slot->isLoggedIn) { - if (slot->ssoLoggedIn) { - session->info.state = CKS_RW_SO_FUNCTIONS; - } else if (session->info.flags & CKF_RW_SESSION) { - session->info.state = CKS_RW_USER_FUNCTIONS; - } else { - session->info.state = CKS_RO_USER_FUNCTIONS; - } + if (slot->ssoLoggedIn) { + session->info.state = CKS_RW_SO_FUNCTIONS; + } else if (session->info.flags & CKF_RW_SESSION) { + session->info.state = CKS_RW_USER_FUNCTIONS; + } else { + session->info.state = CKS_RO_USER_FUNCTIONS; + } } else { - if (session->info.flags & CKF_RW_SESSION) { - session->info.state = CKS_RW_PUBLIC_SESSION; - } else { - session->info.state = CKS_RO_PUBLIC_SESSION; - } + if (session->info.flags & CKF_RW_SESSION) { + session->info.state = CKS_RW_PUBLIC_SESSION; + } else { + session->info.state = CKS_RO_PUBLIC_SESSION; + } } } @@ -1718,13 +1734,13 @@ sftk_update_all_states(SFTKSlot *slot) unsigned int i; SFTKSession *session; - for (i=0; i < slot->sessHashSize; i++) { - PZLock *lock = SFTK_SESSION_LOCK(slot,i); - PZ_Lock(lock); - for (session = slot->head[i]; session; session = session->next) { - sftk_update_state(slot,session); - } - PZ_Unlock(lock); + for (i = 0; i < slot->sessHashSize; i++) { + PZLock *lock = SFTK_SESSION_LOCK(slot, i); + PZ_Lock(lock); + for (session = slot->head[i]; session; session = session->next) { + sftk_update_state(slot, session); + } + PZ_Unlock(lock); } } @@ -1735,14 +1751,14 @@ void sftk_FreeContext(SFTKSessionContext *context) { if (context->cipherInfo) { - (*context->destroy)(context->cipherInfo,PR_TRUE); + (*context->destroy)(context->cipherInfo, PR_TRUE); } if (context->hashInfo) { - (*context->hashdestroy)(context->hashInfo,PR_TRUE); + (*context->hashdestroy)(context->hashInfo, PR_TRUE); } if (context->key) { - sftk_FreeObject(context->key); - context->key = NULL; + sftk_FreeObject(context->key); + context->key = NULL; } PORT_Free(context); } @@ -1753,15 +1769,17 @@ sftk_FreeContext(SFTKSessionContext *context) */ SFTKSession * sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication, - CK_FLAGS flags) + CK_FLAGS flags) { SFTKSession *session; SFTKSlot *slot = sftk_SlotFromID(slotID, PR_FALSE); - if (slot == NULL) return NULL; + if (slot == NULL) + return NULL; - session = (SFTKSession*)PORT_Alloc(sizeof(SFTKSession)); - if (session == NULL) return NULL; + session = (SFTKSession *)PORT_Alloc(sizeof(SFTKSession)); + if (session == NULL) + return NULL; session->next = session->prev = NULL; session->refCount = 1; @@ -1772,8 +1790,8 @@ sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication, session->objectIDCount = 1; session->objectLock = PZ_NewLock(nssILockObject); if (session->objectLock == NULL) { - PORT_Free(session); - return NULL; + PORT_Free(session); + return NULL; } session->objects[0] = NULL; @@ -1783,16 +1801,15 @@ sftk_NewSession(CK_SLOT_ID slotID, CK_NOTIFY notify, CK_VOID_PTR pApplication, session->info.flags = flags; session->info.slotID = slotID; session->info.ulDeviceError = 0; - sftk_update_state(slot,session); + sftk_update_state(slot, session); return session; } - /* free all the data associated with a session. */ static void sftk_DestroySession(SFTKSession *session) { - SFTKObjectList *op,*next; + SFTKObjectList *op, *next; PORT_Assert(session->refCount == 0); /* clean out the attributes */ @@ -1801,26 +1818,25 @@ sftk_DestroySession(SFTKSession *session) for (op = session->objects[0]; op != NULL; op = next) { next = op->next; /* paranoia */ - op->next = op->prev = NULL; - sftk_DeleteObject(session,op->parent); + op->next = op->prev = NULL; + sftk_DeleteObject(session, op->parent); } PZ_DestroyLock(session->objectLock); if (session->enc_context) { - sftk_FreeContext(session->enc_context); + sftk_FreeContext(session->enc_context); } if (session->hash_context) { - sftk_FreeContext(session->hash_context); + sftk_FreeContext(session->hash_context); } if (session->sign_context) { - sftk_FreeContext(session->sign_context); + sftk_FreeContext(session->sign_context); } if (session->search) { - sftk_FreeSearch(session->search); + sftk_FreeSearch(session->search); } PORT_Free(session); } - /* * look up a session structure from a session handle * generate a reference to it. @@ -1828,16 +1844,18 @@ sftk_DestroySession(SFTKSession *session) SFTKSession * sftk_SessionFromHandle(CK_SESSION_HANDLE handle) { - SFTKSlot *slot = sftk_SlotFromSessionHandle(handle); + SFTKSlot *slot = sftk_SlotFromSessionHandle(handle); SFTKSession *session; - PZLock *lock; - - if (!slot) return NULL; - lock = SFTK_SESSION_LOCK(slot,handle); + PZLock *lock; + + if (!slot) + return NULL; + lock = SFTK_SESSION_LOCK(slot, handle); PZ_Lock(lock); - sftkqueue_find(session,handle,slot->head,slot->sessHashSize); - if (session) session->refCount++; + sftkqueue_find(session, handle, slot->head, slot->sessHashSize); + if (session) + session->refCount++; PZ_Unlock(lock); return (session); @@ -1851,37 +1869,39 @@ sftk_FreeSession(SFTKSession *session) { PRBool destroy = PR_FALSE; SFTKSlot *slot = sftk_SlotFromSession(session); - PZLock *lock = SFTK_SESSION_LOCK(slot,session->handle); + PZLock *lock = SFTK_SESSION_LOCK(slot, session->handle); PZ_Lock(lock); - if (session->refCount == 1) destroy = PR_TRUE; + if (session->refCount == 1) + destroy = PR_TRUE; session->refCount--; PZ_Unlock(lock); - if (destroy) sftk_DestroySession(session); + if (destroy) + sftk_DestroySession(session); } void sftk_addHandle(SFTKSearchResults *search, CK_OBJECT_HANDLE handle) { if (search->handles == NULL) { - return; + return; } if (search->size >= search->array_size) { - search->array_size += NSC_SEARCH_BLOCK_SIZE; - search->handles = (CK_OBJECT_HANDLE *) PORT_Realloc(search->handles, - sizeof(CK_OBJECT_HANDLE)* search->array_size); - if (search->handles == NULL) { - return; - } + search->array_size += NSC_SEARCH_BLOCK_SIZE; + search->handles = (CK_OBJECT_HANDLE *)PORT_Realloc(search->handles, + sizeof(CK_OBJECT_HANDLE) * search->array_size); + if (search->handles == NULL) { + return; + } } search->handles[search->size] = handle; search->size++; } -static CK_RV -handleToClass(SFTKSlot *slot, CK_OBJECT_HANDLE handle, - CK_OBJECT_CLASS *objClass) +static CK_RV +handleToClass(SFTKSlot *slot, CK_OBJECT_HANDLE handle, + CK_OBJECT_CLASS *objClass) { SFTKDBHandle *dbHandle = sftk_getDBForTokenObject(slot, handle); CK_ATTRIBUTE objClassTemplate; @@ -1903,10 +1923,10 @@ sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, CK_OBJECT_HANDLE handle) PRBool hasLocks = PR_FALSE; CK_RV crv; - object = sftk_GetObjectFromList(&hasLocks, PR_FALSE, &tokenObjectList, 0, - PR_FALSE); + object = sftk_GetObjectFromList(&hasLocks, PR_FALSE, &tokenObjectList, 0, + PR_FALSE); if (object == NULL) { - return NULL; + return NULL; } object->handle = handle; @@ -1914,26 +1934,23 @@ sftk_NewTokenObject(SFTKSlot *slot, SECItem *dbKey, CK_OBJECT_HANDLE handle) * doesn't exist */ crv = handleToClass(slot, handle, &object->objclass); if (crv != CKR_OK) { - goto loser; + goto loser; } object->slot = slot; object->objectInfo = NULL; object->infoFree = NULL; if (!hasLocks) { - object->refLock = PZ_NewLock(nssILockRefLock); + object->refLock = PZ_NewLock(nssILockRefLock); } if (object->refLock == NULL) { - goto loser; + goto loser; } object->refCount = 1; return object; loser: - if (object) { - (void) sftk_DestroyObject(object); - } + (void)sftk_DestroyObject(object); return NULL; - } SFTKTokenObject * @@ -1947,18 +1964,18 @@ sftk_convertSessionToToken(SFTKObject *obj) sftk_DestroySessionObjectData(so); PZ_DestroyLock(so->attributeLock); if (to == NULL) { - return NULL; + return NULL; } sftk_tokenKeyLock(so->obj.slot); - key = sftk_lookupTokenKeyByHandle(so->obj.slot,so->obj.handle); + key = sftk_lookupTokenKeyByHandle(so->obj.slot, so->obj.handle); if (key == NULL) { - sftk_tokenKeyUnlock(so->obj.slot); - return NULL; + sftk_tokenKeyUnlock(so->obj.slot); + return NULL; } - rv = SECITEM_CopyItem(NULL,&to->dbKey,key); + rv = SECITEM_CopyItem(NULL, &to->dbKey, key); sftk_tokenKeyUnlock(so->obj.slot); if (rv == SECFailure) { - return NULL; + return NULL; } return to; @@ -1975,4 +1992,3 @@ sftk_narrowToTokenObject(SFTKObject *obj) { return sftk_isToken(obj->handle) ? (SFTKTokenObject *)obj : NULL; } - diff --git a/nss/lib/softoken/sdb.c b/nss/lib/softoken/sdb.c index 1684860..0e321dd 100644 --- a/nss/lib/softoken/sdb.c +++ b/nss/lib/softoken/sdb.c @@ -6,11 +6,11 @@ * * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does + * slot 1 is our generic crypto support. It does not require login. + * It supports Public Key ops, and all they bulk ciphers and hashes. + * It can also support Private Key ops for imported Private keys. It does * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It + * slot 2 is our private key support. It requires a login before use. It * can store Private Keys and Certs as token objects. Currently only private * keys and their associated Certificates are saved on the token. * @@ -47,16 +47,16 @@ */ static PRLock *sqlite_lock = NULL; -#define LOCK_SQLITE() PR_Lock(sqlite_lock); -#define UNLOCK_SQLITE() PR_Unlock(sqlite_lock); +#define LOCK_SQLITE() PR_Lock(sqlite_lock); +#define UNLOCK_SQLITE() PR_Unlock(sqlite_lock); #else -#define LOCK_SQLITE() -#define UNLOCK_SQLITE() +#define LOCK_SQLITE() +#define UNLOCK_SQLITE() #endif typedef enum { - SDB_CERT = 1, - SDB_KEY = 2 + SDB_CERT = 1, + SDB_KEY = 2 } sdbDataType; /* @@ -70,19 +70,19 @@ typedef enum { * SDB_MAX_BUSY_RETRIES specifies how many times the sdb_ will retry on * a busy condition. * - * SDB_SQLITE_BUSY_TIMEOUT affects all opertions, both manual + * SDB_SQLITE_BUSY_TIMEOUT affects all opertions, both manual * (prepare/step/reset/finalize) and automatic (sqlite3_exec()). * SDB_BUSY_RETRY_TIME and SDB_MAX_BUSY_RETRIES only affect manual operations - * - * total wait time for automatic operations: + * + * total wait time for automatic operations: * 1 second (SDB_SQLITE_BUSY_TIMEOUT/1000). - * total wait time for manual operations: + * total wait time for manual operations: * (1 second + 5 seconds) * 10 = 60 seconds. * (SDB_SQLITE_BUSY_TIMEOUT/1000 + SDB_BUSY_RETRY_TIME)*SDB_MAX_BUSY_RETRIES */ #define SDB_SQLITE_BUSY_TIMEOUT 1000 /* milliseconds */ -#define SDB_BUSY_RETRY_TIME 5 /* seconds */ -#define SDB_MAX_BUSY_RETRIES 10 +#define SDB_BUSY_RETRY_TIME 5 /* seconds */ +#define SDB_MAX_BUSY_RETRIES 10 /* * Note on use of sqlReadDB: Only one thread at a time may have an actual @@ -98,20 +98,20 @@ typedef enum { * other operations like NSC_GetAttributeValue */ struct SDBPrivateStr { - char *sqlDBName; /* invariant, path to this database */ - sqlite3 *sqlXactDB; /* access protected by dbMon, use protected - * by the transaction. Current transaction db*/ - PRThread *sqlXactThread; /* protected by dbMon, - * current transaction thread */ - sqlite3 *sqlReadDB; /* use protected by dbMon, value invariant */ - PRIntervalTime lastUpdateTime; /* last time the cache was updated */ - PRIntervalTime updateInterval; /* how long the cache can go before it - * must be updated again */ - sdbDataType type; /* invariant, database type */ - char *table; /* invariant, SQL table which contains the db */ - char *cacheTable; /* invariant, SQL table cache of db */ - PRMonitor *dbMon; /* invariant, monitor to protect - * sqlXact* fields, and use of the sqlReadDB */ + char *sqlDBName; /* invariant, path to this database */ + sqlite3 *sqlXactDB; /* access protected by dbMon, use protected + * by the transaction. Current transaction db*/ + PRThread *sqlXactThread; /* protected by dbMon, + * current transaction thread */ + sqlite3 *sqlReadDB; /* use protected by dbMon, value invariant */ + PRIntervalTime lastUpdateTime; /* last time the cache was updated */ + PRIntervalTime updateInterval; /* how long the cache can go before it + * must be updated again */ + sdbDataType type; /* invariant, database type */ + char *table; /* invariant, SQL table which contains the db */ + char *cacheTable; /* invariant, SQL table cache of db */ + PRMonitor *dbMon; /* invariant, monitor to protect + * sqlXact* fields, and use of the sqlReadDB */ }; typedef struct SDBPrivateStr SDBPrivate; @@ -130,7 +130,7 @@ static const CK_ATTRIBUTE_TYPE known_attributes[] = { CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, - CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, + CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUB_PRIME_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_KEY_GEN_MECHANISM, CKA_MODIFIABLE, CKA_EC_PARAMS, @@ -156,8 +156,8 @@ static const CK_ATTRIBUTE_TYPE known_attributes[] = { CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS }; -static int known_attributes_size= sizeof(known_attributes)/ - sizeof(known_attributes[0]); +static int known_attributes_size = sizeof(known_attributes) / + sizeof(known_attributes[0]); /* Magic for an explicit NULL. NOTE: ideally this should be * out of band data. Since it's not completely out of band, pick @@ -172,20 +172,20 @@ const unsigned char SQLITE_EXPLICIT_NULL[] = { 0xa5, 0x0, 0x5a }; /* * determine when we've completed our tasks */ -static int +static int sdb_done(int err, int *count) { /* allow as many rows as the database wants to give */ if (err == SQLITE_ROW) { - *count = 0; - return 0; + *count = 0; + return 0; } if (err != SQLITE_BUSY) { - return 1; + return 1; } /* err == SQLITE_BUSY, Dont' retry forever in this case */ if (++(*count) >= SDB_MAX_BUSY_RETRIES) { - return 1; + return 1; } return 0; } @@ -228,21 +228,25 @@ sdb_getFallbackTempDir(void) "/var/tmp", "/usr/tmp", "/tmp", - NULL /* List terminator */ + NULL /* List terminator */ }; unsigned int i; struct stat buf; const char *zDir = NULL; azDirs[0] = sqlite3_temp_directory; - azDirs[1] = getenv("TMPDIR"); + azDirs[1] = PR_GetEnvSecure("TMPDIR"); for (i = 0; i < PR_ARRAY_SIZE(azDirs); i++) { zDir = azDirs[i]; - if (zDir == NULL) continue; - if (stat(zDir, &buf)) continue; - if (!S_ISDIR(buf.st_mode)) continue; - if (access(zDir, 07)) continue; + if (zDir == NULL) + continue; + if (stat(zDir, &buf)) + continue; + if (!S_ISDIR(buf.st_mode)) + continue; + if (access(zDir, 07)) + continue; break; } @@ -269,33 +273,33 @@ sdb_getTempDir(sqlite3 *sqlDB) /* Obtain temporary filename in sqlite's directory for temporary tables */ sqlrv = sqlite3_file_control(sqlDB, 0, SQLITE_FCNTL_TEMPFILENAME, - (void*)&tempName); + (void *)&tempName); if (sqlrv == SQLITE_NOTFOUND) { - /* SQLITE_FCNTL_TEMPFILENAME not implemented because we are using - * an older SQLite. */ - return sdb_getFallbackTempDir(); + /* SQLITE_FCNTL_TEMPFILENAME not implemented because we are using + * an older SQLite. */ + return sdb_getFallbackTempDir(); } if (sqlrv != SQLITE_OK) { - return NULL; + return NULL; } /* We'll extract the temporary directory from tempName */ foundSeparator = PORT_Strrchr(tempName, PR_GetDirectorySeparator()); if (foundSeparator) { - /* We shorten the temp filename string to contain only - * the directory name (including the trailing separator). - * We know the byte after the foundSeparator position is - * safe to use, in the shortest scenario it contains the - * end-of-string byte. - * By keeping the separator at the found position, it will - * even work if tempDir consists of the separator, only. - * (In this case the toplevel directory will be used for - * access speed testing). */ - ++foundSeparator; - *foundSeparator = 0; - - /* Now we copy the directory name for our caller */ - result = PORT_Strdup(tempName); + /* We shorten the temp filename string to contain only + * the directory name (including the trailing separator). + * We know the byte after the foundSeparator position is + * safe to use, in the shortest scenario it contains the + * end-of-string byte. + * By keeping the separator at the found position, it will + * even work if tempDir consists of the separator, only. + * (In this case the toplevel directory will be used for + * access speed testing). */ + ++foundSeparator; + *foundSeparator = 0; + + /* Now we copy the directory name for our caller */ + result = PORT_Strdup(tempName); } sqlite3_free(tempName); @@ -309,48 +313,46 @@ static CK_RV sdb_mapSQLError(sdbDataType type, int sqlerr) { switch (sqlerr) { - /* good matches */ - case SQLITE_OK: - case SQLITE_DONE: - return CKR_OK; - case SQLITE_NOMEM: - return CKR_HOST_MEMORY; - case SQLITE_READONLY: - return CKR_TOKEN_WRITE_PROTECTED; - /* close matches */ - case SQLITE_AUTH: - case SQLITE_PERM: - /*return CKR_USER_NOT_LOGGED_IN; */ - case SQLITE_CANTOPEN: - case SQLITE_NOTFOUND: - /* NSS distiguishes between failure to open the cert and the key db */ - return type == SDB_CERT ? - CKR_NETSCAPE_CERTDB_FAILED : CKR_NETSCAPE_KEYDB_FAILED; - case SQLITE_IOERR: - return CKR_DEVICE_ERROR; - default: - break; + /* good matches */ + case SQLITE_OK: + case SQLITE_DONE: + return CKR_OK; + case SQLITE_NOMEM: + return CKR_HOST_MEMORY; + case SQLITE_READONLY: + return CKR_TOKEN_WRITE_PROTECTED; + /* close matches */ + case SQLITE_AUTH: + case SQLITE_PERM: + /*return CKR_USER_NOT_LOGGED_IN; */ + case SQLITE_CANTOPEN: + case SQLITE_NOTFOUND: + /* NSS distiguishes between failure to open the cert and the key db */ + return type == SDB_CERT ? CKR_NETSCAPE_CERTDB_FAILED : CKR_NETSCAPE_KEYDB_FAILED; + case SQLITE_IOERR: + return CKR_DEVICE_ERROR; + default: + break; } return CKR_GENERAL_ERROR; } - /* * build up database name from a directory, prefix, name, version and flags. */ -static char *sdb_BuildFileName(const char * directory, - const char *prefix, const char *type, - int version) +static char * +sdb_BuildFileName(const char *directory, + const char *prefix, const char *type, + int version) { char *dbname = NULL; /* build the full dbname */ dbname = sqlite3_mprintf("%s%c%s%s%d.db", directory, - (int)(unsigned char)PR_GetDirectorySeparator(), - prefix, type, version); + (int)(unsigned char)PR_GetDirectorySeparator(), + prefix, type, version); return dbname; } - /* * find out how expensive the access system call is for non-existant files * in the given directory. Return the number of operations done in 33 ms. @@ -368,7 +370,7 @@ sdb_measureAccess(const char *directory) /* no directory, just return one */ if (directory == NULL) { - return 1; + return 1; } /* our calculation assumes time is a 4 bytes == 32 bit integer */ @@ -376,10 +378,9 @@ sdb_measureAccess(const char *directory) directoryLength = strlen(directory); - maxTempLen = directoryLength + strlen(doesntExistName) - + 1 /* potential additional separator char */ - + 11 /* max chars for 32 bit int plus potential sign */ - + 1; /* zero terminator */ + maxTempLen = directoryLength + strlen(doesntExistName) + 1 /* potential additional separator char */ + + 11 /* max chars for 32 bit int plus potential sign */ + + 1; /* zero terminator */ temp = PORT_Alloc(maxTempLen); if (!temp) { @@ -392,7 +393,7 @@ sdb_measureAccess(const char *directory) strcpy(temp, directory); if (directory[directoryLength - 1] != PR_GetDirectorySeparator()) { - temp[directoryLength++] = PR_GetDirectorySeparator(); + temp[directoryLength++] = PR_GetDirectorySeparator(); } tempStartOfFilename = temp + directoryLength; maxFileNameLen = maxTempLen - directoryLength; @@ -400,22 +401,22 @@ sdb_measureAccess(const char *directory) /* measure number of Access operations that can be done in 33 milliseconds * (1/30'th of a second), or 10000 operations, which ever comes first. */ - time = PR_IntervalNow(); - for (i=0; i < 10000u; i++) { - PRIntervalTime next; - - /* We'll use the variable part first in the filename string, just in - * case it's longer than assumed, so if anything gets cut off, it - * will be cut off from the constant part. - * This code assumes the directory name at the beginning of - * temp remains unchanged during our loop. */ + time = PR_IntervalNow(); + for (i = 0; i < 10000u; i++) { + PRIntervalTime next; + + /* We'll use the variable part first in the filename string, just in + * case it's longer than assumed, so if anything gets cut off, it + * will be cut off from the constant part. + * This code assumes the directory name at the beginning of + * temp remains unchanged during our loop. */ PR_snprintf(tempStartOfFilename, maxFileNameLen, - ".%lu%s", (PRUint32)(time+i), doesntExistName); - PR_Access(temp,PR_ACCESS_EXISTS); - next = PR_IntervalNow(); - delta = next - time; - if (delta >= duration) - break; + ".%lu%s", (PRUint32)(time + i), doesntExistName); + PR_Access(temp, PR_ACCESS_EXISTS); + next = PR_IntervalNow(); + delta = next - time; + if (delta >= duration) + break; } PORT_Free(temp); @@ -434,52 +435,52 @@ sdb_measureAccess(const char *directory) */ static const char DROP_CACHE_CMD[] = "DROP TABLE %s"; static const char CREATE_CACHE_CMD[] = - "CREATE TEMPORARY TABLE %s AS SELECT * FROM %s"; -static const char CREATE_ISSUER_INDEX_CMD[] = - "CREATE INDEX issuer ON %s (a81)"; -static const char CREATE_SUBJECT_INDEX_CMD[] = - "CREATE INDEX subject ON %s (a101)"; + "CREATE TEMPORARY TABLE %s AS SELECT * FROM %s"; +static const char CREATE_ISSUER_INDEX_CMD[] = + "CREATE INDEX issuer ON %s (a81)"; +static const char CREATE_SUBJECT_INDEX_CMD[] = + "CREATE INDEX subject ON %s (a101)"; static const char CREATE_LABEL_INDEX_CMD[] = "CREATE INDEX label ON %s (a3)"; static const char CREATE_ID_INDEX_CMD[] = "CREATE INDEX ckaid ON %s (a102)"; static CK_RV -sdb_buildCache(sqlite3 *sqlDB, sdbDataType type, - const char *cacheTable, const char *table) +sdb_buildCache(sqlite3 *sqlDB, sdbDataType type, + const char *cacheTable, const char *table) { char *newStr; int sqlerr = SQLITE_OK; newStr = sqlite3_mprintf(CREATE_CACHE_CMD, cacheTable, table); if (newStr == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); if (sqlerr != SQLITE_OK) { - return sdb_mapSQLError(type, sqlerr); + return sdb_mapSQLError(type, sqlerr); } /* failure to create the indexes is not an issue */ newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, cacheTable); if (newStr == NULL) { - return CKR_OK; + return CKR_OK; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, cacheTable); if (newStr == NULL) { - return CKR_OK; + return CKR_OK; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, cacheTable); if (newStr == NULL) { - return CKR_OK; + return CKR_OK; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, cacheTable); if (newStr == NULL) { - return CKR_OK; + return CKR_OK; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); @@ -500,24 +501,23 @@ sdb_updateCache(SDBPrivate *sdb_p) /* drop the old table */ newStr = sqlite3_mprintf(DROP_CACHE_CMD, sdb_p->cacheTable); if (newStr == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } sqlerr = sqlite3_exec(sdb_p->sqlReadDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); - if ((sqlerr != SQLITE_OK) && (sqlerr != SQLITE_ERROR )) { + if ((sqlerr != SQLITE_OK) && (sqlerr != SQLITE_ERROR)) { /* something went wrong with the drop, don't try to refresh... * NOTE: SQLITE_ERROR is returned if the table doesn't exist. In * that case, we just continue on and try to reload it */ - return sdb_mapSQLError(sdb_p->type, sqlerr); + return sdb_mapSQLError(sdb_p->type, sqlerr); } - /* set up the new table */ - error = sdb_buildCache(sdb_p->sqlReadDB,sdb_p->type, - sdb_p->cacheTable,sdb_p->table ); + error = sdb_buildCache(sdb_p->sqlReadDB, sdb_p->type, + sdb_p->cacheTable, sdb_p->table); if (error == CKR_OK) { - /* we have a new cache! */ - sdb_p->lastUpdateTime = PR_IntervalNow(); + /* we have a new cache! */ + sdb_p->lastUpdateTime = PR_IntervalNow(); } return error; } @@ -535,12 +535,12 @@ sdb_updateCache(SDBPrivate *sdb_p) * in the open and close. Also continually opening and closing the database * defeats the cache code as the cache table is lost on close (thus * requiring us to have to reinitialize the cache every operation). - * + * * An execption to the shared handle is transations. All writes happen - * through a transaction. When we are in a transaction, we must use the - * same database pointer for that entire transation. In this case we save - * the transaction database and use it for all accesses on the transaction - * thread. Other threads use the common database. + * through a transaction. When we are in a transaction, we must use the + * same database pointer for that entire transation. In this case we save + * the transaction database and use it for all accesses on the transaction + * thread. Other threads use the common database. * * There can only be once active transaction on the database at a time. * @@ -555,7 +555,7 @@ sdb_updateCache(SDBPrivate *sdb_p) * and read operations return either the physical table or the cache * depending on whether or not the cache exists. */ -static CK_RV +static CK_RV sdb_openDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB, const char **table) { *sqlDB = NULL; @@ -563,15 +563,15 @@ sdb_openDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB, const char **table) PR_EnterMonitor(sdb_p->dbMon); if (table) { - *table = sdb_p->table; + *table = sdb_p->table; } /* We're in a transaction, use the transaction DB */ if ((sdb_p->sqlXactDB) && (sdb_p->sqlXactThread == PR_GetCurrentThread())) { - *sqlDB =sdb_p->sqlXactDB; - /* only one thread can get here, safe to unlock */ + *sqlDB = sdb_p->sqlXactDB; + /* only one thread can get here, safe to unlock */ PR_ExitMonitor(sdb_p->dbMon); - return CKR_OK; + return CKR_OK; } /* @@ -581,33 +581,32 @@ sdb_openDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB, const char **table) * is on order of human scale, not computer scale. */ if (table && sdb_p->cacheTable) { - PRIntervalTime now = PR_IntervalNow(); - if ((now - sdb_p->lastUpdateTime) > sdb_p->updateInterval) { - sdb_updateCache(sdb_p); + PRIntervalTime now = PR_IntervalNow(); + if ((now - sdb_p->lastUpdateTime) > sdb_p->updateInterval) { + sdb_updateCache(sdb_p); } - *table = sdb_p->cacheTable; + *table = sdb_p->cacheTable; } *sqlDB = sdb_p->sqlReadDB; /* leave holding the lock. only one thread can actually use a given * database connection at once */ - + return CKR_OK; } /* closing the local database currenly means unlocking the monitor */ -static CK_RV -sdb_closeDBLocal(SDBPrivate *sdb_p, sqlite3 *sqlDB) +static CK_RV +sdb_closeDBLocal(SDBPrivate *sdb_p, sqlite3 *sqlDB) { - if (sdb_p->sqlXactDB != sqlDB) { - /* if we weren't in a transaction, we got a lock */ + if (sdb_p->sqlXactDB != sqlDB) { + /* if we weren't in a transaction, we got a lock */ PR_ExitMonitor(sdb_p->dbMon); - } - return CKR_OK; + } + return CKR_OK; } - /* * wrapper to sqlite3_open which also sets the busy_timeout */ @@ -623,14 +622,14 @@ sdb_openDB(const char *name, sqlite3 **sqlDB, int flags) *sqlDB = NULL; sqlerr = sqlite3_open(name, sqlDB); if (sqlerr != SQLITE_OK) { - return sqlerr; + return sqlerr; } sqlerr = sqlite3_busy_timeout(*sqlDB, SDB_SQLITE_BUSY_TIMEOUT); if (sqlerr != SQLITE_OK) { - sqlite3_close(*sqlDB); - *sqlDB = NULL; - return sqlerr; + sqlite3_close(*sqlDB); + *sqlDB = NULL; + return sqlerr; } return SQLITE_OK; } @@ -639,15 +638,16 @@ sdb_openDB(const char *name, sqlite3 **sqlDB, int flags) * the database handle will not see the new table, we need to close this * database and reopen it. Caller must be in a transaction or holding * the dbMon. sqlDB is changed on success. */ -static int -sdb_reopenDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB) { +static int +sdb_reopenDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB) +{ sqlite3 *newDB; int sqlerr; /* open a new database */ sqlerr = sdb_openDB(sdb_p->sqlDBName, &newDB, SDB_RDONLY); if (sqlerr != SQLITE_OK) { - return sqlerr; + return sqlerr; } /* if we are in a transaction, we may not be holding the monitor. @@ -656,9 +656,9 @@ sdb_reopenDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB) { PR_EnterMonitor(sdb_p->dbMon); /* update our view of the database */ if (sdb_p->sqlReadDB == *sqlDB) { - sdb_p->sqlReadDB = newDB; + sdb_p->sqlReadDB = newDB; } else if (sdb_p->sqlXactDB == *sqlDB) { - sdb_p->sqlXactDB = newDB; + sdb_p->sqlXactDB = newDB; } PR_ExitMonitor(sdb_p->dbMon); @@ -674,19 +674,18 @@ struct SDBFindStr { sqlite3_stmt *findstmt; }; - -static const char FIND_OBJECTS_CMD[] = "SELECT ALL * FROM %s WHERE %s;"; +static const char FIND_OBJECTS_CMD[] = "SELECT ALL * FROM %s WHERE %s;"; static const char FIND_OBJECTS_ALL_CMD[] = "SELECT ALL * FROM %s;"; CK_RV -sdb_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *template, CK_ULONG count, - SDBFind **find) +sdb_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *template, CK_ULONG count, + SDBFind **find) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; const char *table; char *newStr, *findStr = NULL; sqlite3_stmt *findstmt = NULL; - char *join=""; + char *join = ""; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; unsigned int i; @@ -695,74 +694,73 @@ sdb_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *template, CK_ULONG count, *find = NULL; error = sdb_openDBLocal(sdb_p, &sqlDB, &table); if (error != CKR_OK) { - goto loser; + goto loser; } findStr = sqlite3_mprintf(""); - for (i=0; findStr && i < count; i++) { - newStr = sqlite3_mprintf("%s%sa%x=$DATA%d", findStr, join, - template[i].type, i); - join=" AND "; - sqlite3_free(findStr); - findStr = newStr; + for (i = 0; findStr && i < count; i++) { + newStr = sqlite3_mprintf("%s%sa%x=$DATA%d", findStr, join, + template[i].type, i); + join = " AND "; + sqlite3_free(findStr); + findStr = newStr; } if (findStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; + error = CKR_HOST_MEMORY; + goto loser; } if (count == 0) { - newStr = sqlite3_mprintf(FIND_OBJECTS_ALL_CMD, table); + newStr = sqlite3_mprintf(FIND_OBJECTS_ALL_CMD, table); } else { - newStr = sqlite3_mprintf(FIND_OBJECTS_CMD, table, findStr); + newStr = sqlite3_mprintf(FIND_OBJECTS_CMD, table, findStr); } sqlite3_free(findStr); if (newStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; + error = CKR_HOST_MEMORY; + goto loser; } sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &findstmt, NULL); sqlite3_free(newStr); - for (i=0; sqlerr == SQLITE_OK && i < count; i++) { - const void *blobData = template[i].pValue; - unsigned int blobSize = template[i].ulValueLen; - if (blobSize == 0) { - blobSize = SQLITE_EXPLICIT_NULL_LEN; - blobData = SQLITE_EXPLICIT_NULL; - } - sqlerr = sqlite3_bind_blob(findstmt, i+1, blobData, blobSize, - SQLITE_TRANSIENT); + for (i = 0; sqlerr == SQLITE_OK && i < count; i++) { + const void *blobData = template[i].pValue; + unsigned int blobSize = template[i].ulValueLen; + if (blobSize == 0) { + blobSize = SQLITE_EXPLICIT_NULL_LEN; + blobData = SQLITE_EXPLICIT_NULL; + } + sqlerr = sqlite3_bind_blob(findstmt, i + 1, blobData, blobSize, + SQLITE_TRANSIENT); } if (sqlerr == SQLITE_OK) { - *find = PORT_New(SDBFind); - if (*find == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } - (*find)->findstmt = findstmt; - (*find)->sqlDB = sqlDB; - UNLOCK_SQLITE() - return CKR_OK; - } + *find = PORT_New(SDBFind); + if (*find == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } + (*find)->findstmt = findstmt; + (*find)->sqlDB = sqlDB; + UNLOCK_SQLITE() + return CKR_OK; + } error = sdb_mapSQLError(sdb_p->type, sqlerr); -loser: +loser: if (findstmt) { - sqlite3_reset(findstmt); - sqlite3_finalize(findstmt); + sqlite3_reset(findstmt); + sqlite3_finalize(findstmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } - CK_RV -sdb_FindObjects(SDB *sdb, SDBFind *sdbFind, CK_OBJECT_HANDLE *object, - CK_ULONG arraySize, CK_ULONG *count) +sdb_FindObjects(SDB *sdb, SDBFind *sdbFind, CK_OBJECT_HANDLE *object, + CK_ULONG arraySize, CK_ULONG *count) { SDBPrivate *sdb_p = sdb->private; sqlite3_stmt *stmt = sdbFind->findstmt; @@ -772,29 +770,29 @@ sdb_FindObjects(SDB *sdb, SDBFind *sdbFind, CK_OBJECT_HANDLE *object, *count = 0; if (arraySize == 0) { - return CKR_OK; + return CKR_OK; } - LOCK_SQLITE() + LOCK_SQLITE() do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - if (sqlerr == SQLITE_ROW) { - /* only care about the id */ - *object++= sqlite3_column_int(stmt, 0); - arraySize--; - (*count)++; - } - } while (!sdb_done(sqlerr,&retry) && (arraySize > 0)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + if (sqlerr == SQLITE_ROW) { + /* only care about the id */ + *object++ = sqlite3_column_int(stmt, 0); + arraySize--; + (*count)++; + } + } while (!sdb_done(sqlerr, &retry) && (arraySize > 0)); /* we only have some of the objects, there is probably more, * set the sqlerr to an OK value so we return CKR_OK */ if (sqlerr == SQLITE_ROW && arraySize == 0) { - sqlerr = SQLITE_DONE; + sqlerr = SQLITE_DONE; } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return sdb_mapSQLError(sdb_p->type, sqlerr); } @@ -807,27 +805,27 @@ sdb_FindObjectsFinal(SDB *sdb, SDBFind *sdbFind) sqlite3 *sqlDB = sdbFind->sqlDB; int sqlerr = SQLITE_OK; - LOCK_SQLITE() + LOCK_SQLITE() if (stmt) { - sqlite3_reset(stmt); - sqlerr = sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlerr = sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } PORT_Free(sdbFind); - UNLOCK_SQLITE() + UNLOCK_SQLITE() return sdb_mapSQLError(sdb_p->type, sqlerr); } static const char GET_ATTRIBUTE_CMD[] = "SELECT ALL %s FROM %s WHERE id=$ID;"; CK_RV -sdb_GetAttributeValueNoLock(SDB *sdb, CK_OBJECT_HANDLE object_id, - CK_ATTRIBUTE *template, CK_ULONG count) +sdb_GetAttributeValueNoLock(SDB *sdb, CK_OBJECT_HANDLE object_id, + CK_ATTRIBUTE *template, CK_ULONG count) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; char *getStr = NULL; char *newStr = NULL; @@ -838,125 +836,128 @@ sdb_GetAttributeValueNoLock(SDB *sdb, CK_OBJECT_HANDLE object_id, int retry = 0; unsigned int i; - /* open a new db if necessary */ error = sdb_openDBLocal(sdb_p, &sqlDB, &table); if (error != CKR_OK) { - goto loser; - } - - for (i=0; i < count; i++) { - getStr = sqlite3_mprintf("a%x", template[i].type); - - if (getStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } - - newStr = sqlite3_mprintf(GET_ATTRIBUTE_CMD, getStr, table); - sqlite3_free(getStr); - getStr = NULL; - if (newStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } - - sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); - sqlite3_free(newStr); - newStr = NULL; - if (sqlerr == SQLITE_ERROR) { - template[i].ulValueLen = -1; - error = CKR_ATTRIBUTE_TYPE_INVALID; - continue; - } else if (sqlerr != SQLITE_OK) { goto loser; } - - sqlerr = sqlite3_bind_int(stmt, 1, object_id); - if (sqlerr != SQLITE_OK) { goto loser; } - - do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - if (sqlerr == SQLITE_ROW) { - unsigned int blobSize; - const char *blobData; - - blobSize = sqlite3_column_bytes(stmt, 0); - blobData = sqlite3_column_blob(stmt, 0); - if (blobData == NULL) { - template[i].ulValueLen = -1; - error = CKR_ATTRIBUTE_TYPE_INVALID; - break; - } - /* If the blob equals our explicit NULL value, then the - * attribute is a NULL. */ - if ((blobSize == SQLITE_EXPLICIT_NULL_LEN) && - (PORT_Memcmp(blobData, SQLITE_EXPLICIT_NULL, - SQLITE_EXPLICIT_NULL_LEN) == 0)) { - blobSize = 0; - } - if (template[i].pValue) { - if (template[i].ulValueLen < blobSize) { - template[i].ulValueLen = -1; - error = CKR_BUFFER_TOO_SMALL; - break; - } - PORT_Memcpy(template[i].pValue, blobData, blobSize); - } - template[i].ulValueLen = blobSize; - found = 1; - } - } while (!sdb_done(sqlerr,&retry)); - sqlite3_reset(stmt); - sqlite3_finalize(stmt); - stmt = NULL; + goto loser; + } + + for (i = 0; i < count; i++) { + getStr = sqlite3_mprintf("a%x", template[i].type); + + if (getStr == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } + + newStr = sqlite3_mprintf(GET_ATTRIBUTE_CMD, getStr, table); + sqlite3_free(getStr); + getStr = NULL; + if (newStr == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } + + sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); + sqlite3_free(newStr); + newStr = NULL; + if (sqlerr == SQLITE_ERROR) { + template[i].ulValueLen = -1; + error = CKR_ATTRIBUTE_TYPE_INVALID; + continue; + } else if (sqlerr != SQLITE_OK) { + goto loser; + } + + sqlerr = sqlite3_bind_int(stmt, 1, object_id); + if (sqlerr != SQLITE_OK) { + goto loser; + } + + do { + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + if (sqlerr == SQLITE_ROW) { + unsigned int blobSize; + const char *blobData; + + blobSize = sqlite3_column_bytes(stmt, 0); + blobData = sqlite3_column_blob(stmt, 0); + if (blobData == NULL) { + template[i].ulValueLen = -1; + error = CKR_ATTRIBUTE_TYPE_INVALID; + break; + } + /* If the blob equals our explicit NULL value, then the + * attribute is a NULL. */ + if ((blobSize == SQLITE_EXPLICIT_NULL_LEN) && + (PORT_Memcmp(blobData, SQLITE_EXPLICIT_NULL, + SQLITE_EXPLICIT_NULL_LEN) == 0)) { + blobSize = 0; + } + if (template[i].pValue) { + if (template[i].ulValueLen < blobSize) { + template[i].ulValueLen = -1; + error = CKR_BUFFER_TOO_SMALL; + break; + } + PORT_Memcpy(template[i].pValue, blobData, blobSize); + } + template[i].ulValueLen = blobSize; + found = 1; + } + } while (!sdb_done(sqlerr, &retry)); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); + stmt = NULL; } loser: /* fix up the error if necessary */ if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); - if (!found && error == CKR_OK) { - error = CKR_OBJECT_HANDLE_INVALID; - } + error = sdb_mapSQLError(sdb_p->type, sqlerr); + if (!found && error == CKR_OK) { + error = CKR_OBJECT_HANDLE_INVALID; + } } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } /* if we had to open a new database, free it now */ if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } return error; } CK_RV -sdb_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, - CK_ATTRIBUTE *template, CK_ULONG count) +sdb_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, + CK_ATTRIBUTE *template, CK_ULONG count) { CK_RV crv; if (count == 0) { - return CKR_OK; + return CKR_OK; } - LOCK_SQLITE() + LOCK_SQLITE() crv = sdb_GetAttributeValueNoLock(sdb, object_id, template, count); - UNLOCK_SQLITE() + UNLOCK_SQLITE() return crv; } - + static const char SET_ATTRIBUTE_CMD[] = "UPDATE %s SET %s WHERE id=$ID;"; CK_RV -sdb_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, - const CK_ATTRIBUTE *template, CK_ULONG count) +sdb_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, + const CK_ATTRIBUTE *template, CK_ULONG count) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; char *setStr = NULL; char *newStr = NULL; @@ -966,82 +967,85 @@ sdb_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id, unsigned int i; if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } if (count == 0) { - return CKR_OK; + return CKR_OK; } - LOCK_SQLITE() + LOCK_SQLITE() setStr = sqlite3_mprintf(""); - for (i=0; setStr && i < count; i++) { - if (i==0) { - sqlite3_free(setStr); - setStr = sqlite3_mprintf("a%x=$VALUE%d", - template[i].type, i); - continue; - } - newStr = sqlite3_mprintf("%s,a%x=$VALUE%d", setStr, - template[i].type, i); - sqlite3_free(setStr); - setStr = newStr; + for (i = 0; setStr && i < count; i++) { + if (i == 0) { + sqlite3_free(setStr); + setStr = sqlite3_mprintf("a%x=$VALUE%d", + template[i].type, i); + continue; + } + newStr = sqlite3_mprintf("%s,a%x=$VALUE%d", setStr, + template[i].type, i); + sqlite3_free(setStr); + setStr = newStr; } newStr = NULL; if (setStr == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } - newStr = sqlite3_mprintf(SET_ATTRIBUTE_CMD, sdb_p->table, setStr); + newStr = sqlite3_mprintf(SET_ATTRIBUTE_CMD, sdb_p->table, setStr); sqlite3_free(setStr); if (newStr == NULL) { - UNLOCK_SQLITE() - return CKR_HOST_MEMORY; + UNLOCK_SQLITE() + return CKR_HOST_MEMORY; } error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); - if (sqlerr != SQLITE_OK) goto loser; - for (i=0; i < count; i++) { - if (template[i].ulValueLen != 0) { - sqlerr = sqlite3_bind_blob(stmt, i+1, template[i].pValue, - template[i].ulValueLen, SQLITE_STATIC); - } else { - sqlerr = sqlite3_bind_blob(stmt, i+2, SQLITE_EXPLICIT_NULL, - SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC); - } - if (sqlerr != SQLITE_OK) goto loser; - } - sqlerr = sqlite3_bind_int(stmt, i+1, object_id); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; + for (i = 0; i < count; i++) { + if (template[i].ulValueLen != 0) { + sqlerr = sqlite3_bind_blob(stmt, i + 1, template[i].pValue, + template[i].ulValueLen, SQLITE_STATIC); + } else { + sqlerr = sqlite3_bind_blob(stmt, i + 1, SQLITE_EXPLICIT_NULL, + SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC); + } + if (sqlerr != SQLITE_OK) + goto loser; + } + sqlerr = sqlite3_bind_int(stmt, i + 1, object_id); + if (sqlerr != SQLITE_OK) + goto loser; do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); loser: if (newStr) { - sqlite3_free(newStr); + sqlite3_free(newStr); } if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); + error = sdb_mapSQLError(sdb_p->type, sqlerr); } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } @@ -1054,9 +1058,9 @@ sdb_objectExists(SDB *sdb, CK_OBJECT_HANDLE candidate) CK_RV crv; CK_ATTRIBUTE template = { CKA_LABEL, NULL, 0 }; - crv = sdb_GetAttributeValueNoLock(sdb,candidate,&template, 1); + crv = sdb_GetAttributeValueNoLock(sdb, candidate, &template, 1); if (crv == CKR_OBJECT_HANDLE_INVALID) { - return PR_FALSE; + return PR_FALSE; } return PR_TRUE; } @@ -1076,24 +1080,24 @@ sdb_getObjectId(SDB *sdb) */ if (next_obj == CK_INVALID_HANDLE) { PRTime time; - time = PR_Now(); + time = PR_Now(); - next_obj = (CK_OBJECT_HANDLE)(time & 0x3fffffffL); + next_obj = (CK_OBJECT_HANDLE)(time & 0x3fffffffL); } candidate = next_obj++; /* detect that we've looped through all the handles... */ for (count = 0; count < 0x40000000; count++, candidate = next_obj++) { - /* mask off excess bits */ - candidate &= 0x3fffffff; - /* if we hit zero, go to the next entry */ - if (candidate == CK_INVALID_HANDLE) { - continue; - } - /* make sure we aren't already using */ - if (!sdb_objectExists(sdb, candidate)) { - /* this one is free */ - return candidate; - } + /* mask off excess bits */ + candidate &= 0x3fffffff; + /* if we hit zero, go to the next entry */ + if (candidate == CK_INVALID_HANDLE) { + continue; + } + /* make sure we aren't already using */ + if (!sdb_objectExists(sdb, candidate)) { + /* this one is free */ + return candidate; + } } /* no handle is free, fail */ @@ -1102,11 +1106,11 @@ sdb_getObjectId(SDB *sdb) static const char CREATE_CMD[] = "INSERT INTO %s (id%s) VALUES($ID%s);"; CK_RV -sdb_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *object_id, - const CK_ATTRIBUTE *template, CK_ULONG count) +sdb_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *object_id, + const CK_ATTRIBUTE *template, CK_ULONG count) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; char *columnStr = NULL; char *valueStr = NULL; @@ -1118,98 +1122,102 @@ sdb_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *object_id, unsigned int i; if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - LOCK_SQLITE() - if ((*object_id != CK_INVALID_HANDLE) && - !sdb_objectExists(sdb, *object_id)) { - this_object = *object_id; + LOCK_SQLITE() + if ((*object_id != CK_INVALID_HANDLE) && + !sdb_objectExists(sdb, *object_id)) { + this_object = *object_id; } else { - this_object = sdb_getObjectId(sdb); + this_object = sdb_getObjectId(sdb); } if (this_object == CK_INVALID_HANDLE) { - UNLOCK_SQLITE(); - return CKR_HOST_MEMORY; + UNLOCK_SQLITE(); + return CKR_HOST_MEMORY; } columnStr = sqlite3_mprintf(""); valueStr = sqlite3_mprintf(""); *object_id = this_object; - for (i=0; columnStr && valueStr && i < count; i++) { - newStr = sqlite3_mprintf("%s,a%x", columnStr, template[i].type); - sqlite3_free(columnStr); - columnStr = newStr; - newStr = sqlite3_mprintf("%s,$VALUE%d", valueStr, i); - sqlite3_free(valueStr); - valueStr = newStr; + for (i = 0; columnStr && valueStr && i < count; i++) { + newStr = sqlite3_mprintf("%s,a%x", columnStr, template[i].type); + sqlite3_free(columnStr); + columnStr = newStr; + newStr = sqlite3_mprintf("%s,$VALUE%d", valueStr, i); + sqlite3_free(valueStr); + valueStr = newStr; } newStr = NULL; if ((columnStr == NULL) || (valueStr == NULL)) { - if (columnStr) { - sqlite3_free(columnStr); - } - if (valueStr) { - sqlite3_free(valueStr); - } - UNLOCK_SQLITE() - return CKR_HOST_MEMORY; - } - newStr = sqlite3_mprintf(CREATE_CMD, sdb_p->table, columnStr, valueStr); + if (columnStr) { + sqlite3_free(columnStr); + } + if (valueStr) { + sqlite3_free(valueStr); + } + UNLOCK_SQLITE() + return CKR_HOST_MEMORY; + } + newStr = sqlite3_mprintf(CREATE_CMD, sdb_p->table, columnStr, valueStr); sqlite3_free(columnStr); sqlite3_free(valueStr); error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; sqlerr = sqlite3_bind_int(stmt, 1, *object_id); - if (sqlerr != SQLITE_OK) goto loser; - for (i=0; i < count; i++) { - if (template[i].ulValueLen) { - sqlerr = sqlite3_bind_blob(stmt, i+2, template[i].pValue, - template[i].ulValueLen, SQLITE_STATIC); - } else { - sqlerr = sqlite3_bind_blob(stmt, i+2, SQLITE_EXPLICIT_NULL, - SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC); - } - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; + for (i = 0; i < count; i++) { + if (template[i].ulValueLen) { + sqlerr = sqlite3_bind_blob(stmt, i + 2, template[i].pValue, + template[i].ulValueLen, SQLITE_STATIC); + } else { + sqlerr = sqlite3_bind_blob(stmt, i + 2, SQLITE_EXPLICIT_NULL, + SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC); + } + if (sqlerr != SQLITE_OK) + goto loser; } do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); loser: if (newStr) { - sqlite3_free(newStr); + sqlite3_free(newStr); } if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); + error = sdb_mapSQLError(sdb_p->type, sqlerr); } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } static const char DESTROY_CMD[] = "DELETE FROM %s WHERE (id=$ID);"; + CK_RV sdb_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; char *newStr = NULL; int sqlerr = SQLITE_OK; @@ -1217,51 +1225,54 @@ sdb_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id) int retry = 0; if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - LOCK_SQLITE() + LOCK_SQLITE() error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } - newStr = sqlite3_mprintf(DESTROY_CMD, sdb_p->table); + newStr = sqlite3_mprintf(DESTROY_CMD, sdb_p->table); if (newStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; + error = CKR_HOST_MEMORY; + goto loser; } - sqlerr =sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); + sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL); sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) goto loser; - sqlerr =sqlite3_bind_int(stmt, 1, object_id); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; + sqlerr = sqlite3_bind_int(stmt, 1, object_id); + if (sqlerr != SQLITE_OK) + goto loser; do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); loser: if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); + error = sdb_mapSQLError(sdb_p->type, sqlerr); } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } - + static const char BEGIN_CMD[] = "BEGIN IMMEDIATE TRANSACTION;"; + /* * start a transaction. * @@ -1273,63 +1284,61 @@ CK_RV sdb_Begin(SDB *sdb) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; int retry = 0; - if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - - LOCK_SQLITE() + LOCK_SQLITE() /* get a new version that we will use for the entire transaction */ sqlerr = sdb_openDB(sdb_p->sqlDBName, &sqlDB, SDB_RDWR); if (sqlerr != SQLITE_OK) { - goto loser; + goto loser; } - sqlerr =sqlite3_prepare_v2(sqlDB, BEGIN_CMD, -1, &stmt, NULL); + sqlerr = sqlite3_prepare_v2(sqlDB, BEGIN_CMD, -1, &stmt, NULL); do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } loser: error = sdb_mapSQLError(sdb_p->type, sqlerr); - /* we are starting a new transaction, + /* we are starting a new transaction, * and if we succeeded, then save this database for the rest of * our transaction */ if (error == CKR_OK) { - /* we hold a 'BEGIN TRANSACTION' and a sdb_p->lock. At this point - * sdb_p->sqlXactDB MUST be null */ - PR_EnterMonitor(sdb_p->dbMon); - PORT_Assert(sdb_p->sqlXactDB == NULL); - sdb_p->sqlXactDB = sqlDB; - sdb_p->sqlXactThread = PR_GetCurrentThread(); + /* we hold a 'BEGIN TRANSACTION' and a sdb_p->lock. At this point + * sdb_p->sqlXactDB MUST be null */ + PR_EnterMonitor(sdb_p->dbMon); + PORT_Assert(sdb_p->sqlXactDB == NULL); + sdb_p->sqlXactDB = sqlDB; + sdb_p->sqlXactThread = PR_GetCurrentThread(); PR_ExitMonitor(sdb_p->dbMon); } else { - /* we failed to start our transaction, - * free any databases we opened. */ - if (sqlDB) { - sqlite3_close(sqlDB); - } + /* we failed to start our transaction, + * free any databases we opened. */ + if (sqlDB) { + sqlite3_close(sqlDB); + } } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } @@ -1339,19 +1348,18 @@ loser: * these 2 are what the database will show. (no change in to former, change in * the latter). */ -static CK_RV +static CK_RV sdb_complete(SDB *sdb, const char *cmd) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; sqlite3_stmt *stmt = NULL; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; int retry = 0; - if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } /* We must have a transation database, or we shouldn't have arrived here */ @@ -1359,40 +1367,40 @@ sdb_complete(SDB *sdb, const char *cmd) PORT_Assert(sdb_p->sqlXactDB); if (sdb_p->sqlXactDB == NULL) { PR_ExitMonitor(sdb_p->dbMon); - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } - PORT_Assert( sdb_p->sqlXactThread == PR_GetCurrentThread()); - if ( sdb_p->sqlXactThread != PR_GetCurrentThread()) { + PORT_Assert(sdb_p->sqlXactThread == PR_GetCurrentThread()); + if (sdb_p->sqlXactThread != PR_GetCurrentThread()) { PR_ExitMonitor(sdb_p->dbMon); - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } sqlDB = sdb_p->sqlXactDB; - sdb_p->sqlXactDB = NULL; /* no one else can get to this DB, - * safe to unlock */ - sdb_p->sqlXactThread = NULL; + sdb_p->sqlXactDB = NULL; /* no one else can get to this DB, + * safe to unlock */ + sdb_p->sqlXactThread = NULL; PR_ExitMonitor(sdb_p->dbMon); - sqlerr =sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL); + sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL); do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); /* Pending BEGIN TRANSACTIONS Can move forward at this point. */ if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } /* we we have a cached DB image, update it as well */ if (sdb_p->cacheTable) { - PR_EnterMonitor(sdb_p->dbMon); - sdb_updateCache(sdb_p); - PR_ExitMonitor(sdb_p->dbMon); + PR_EnterMonitor(sdb_p->dbMon); + sdb_updateCache(sdb_p); + PR_ExitMonitor(sdb_p->dbMon); } error = sdb_mapSQLError(sdb_p->type, sqlerr); @@ -1409,9 +1417,9 @@ CK_RV sdb_Commit(SDB *sdb) { CK_RV crv; - LOCK_SQLITE() - crv = sdb_complete(sdb,COMMIT_CMD); - UNLOCK_SQLITE() + LOCK_SQLITE() + crv = sdb_complete(sdb, COMMIT_CMD); + UNLOCK_SQLITE() return crv; } @@ -1420,9 +1428,9 @@ CK_RV sdb_Abort(SDB *sdb) { CK_RV crv; - LOCK_SQLITE() - crv = sdb_complete(sdb,ROLLBACK_CMD); - UNLOCK_SQLITE() + LOCK_SQLITE() + crv = sdb_complete(sdb, ROLLBACK_CMD); + UNLOCK_SQLITE() return crv; } @@ -1433,17 +1441,17 @@ CK_RV sdb_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = sdb_p->sqlXactDB; + sqlite3 *sqlDB = sdb_p->sqlXactDB; sqlite3_stmt *stmt = NULL; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; int found = 0; int retry = 0; - LOCK_SQLITE() + LOCK_SQLITE() error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } /* handle 'test' versions of the sqlite db */ @@ -1453,77 +1461,79 @@ sdb_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2) * database and reopen it. This is safe because we are holding the lock * still. */ if (sqlerr == SQLITE_SCHEMA) { - sqlerr = sdb_reopenDBLocal(sdb_p, &sqlDB); - if (sqlerr != SQLITE_OK) { - goto loser; - } - sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL); + sqlerr = sdb_reopenDBLocal(sdb_p, &sqlDB); + if (sqlerr != SQLITE_OK) { + goto loser; + } + sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL); } - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC); do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - if (sqlerr == SQLITE_ROW) { - const char *blobData; - unsigned int len = item1->len; - item1->len = sqlite3_column_bytes(stmt, 1); - if (item1->len > len) { - error = CKR_BUFFER_TOO_SMALL; - continue; - } - blobData = sqlite3_column_blob(stmt, 1); - PORT_Memcpy(item1->data,blobData, item1->len); - if (item2) { - len = item2->len; - item2->len = sqlite3_column_bytes(stmt, 2); - if (item2->len > len) { - error = CKR_BUFFER_TOO_SMALL; - continue; - } - blobData = sqlite3_column_blob(stmt, 2); - PORT_Memcpy(item2->data,blobData, item2->len); - } - found = 1; - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + if (sqlerr == SQLITE_ROW) { + const char *blobData; + unsigned int len = item1->len; + item1->len = sqlite3_column_bytes(stmt, 1); + if (item1->len > len) { + error = CKR_BUFFER_TOO_SMALL; + continue; + } + blobData = sqlite3_column_blob(stmt, 1); + PORT_Memcpy(item1->data, blobData, item1->len); + if (item2) { + len = item2->len; + item2->len = sqlite3_column_bytes(stmt, 2); + if (item2->len > len) { + error = CKR_BUFFER_TOO_SMALL; + continue; + } + blobData = sqlite3_column_blob(stmt, 2); + PORT_Memcpy(item2->data, blobData, item2->len); + } + found = 1; + } + } while (!sdb_done(sqlerr, &retry)); loser: /* fix up the error if necessary */ if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); - if (!found && error == CKR_OK) { - error = CKR_OBJECT_HANDLE_INVALID; - } + error = sdb_mapSQLError(sdb_p->type, sqlerr); + if (!found && error == CKR_OK) { + error = CKR_OBJECT_HANDLE_INVALID; + } } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } static const char PW_CREATE_TABLE_CMD[] = - "CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2);"; + "CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2);"; static const char PW_CREATE_CMD[] = - "INSERT INTO metaData (id,item1,item2) VALUES($ID,$ITEM1,$ITEM2);"; -static const char MD_CREATE_CMD[] = - "INSERT INTO metaData (id,item1) VALUES($ID,$ITEM1);"; + "INSERT INTO metaData (id,item1,item2) VALUES($ID,$ITEM1,$ITEM2);"; +static const char MD_CREATE_CMD[] = + "INSERT INTO metaData (id,item1) VALUES($ID,$ITEM1);"; + CK_RV -sdb_PutMetaData(SDB *sdb, const char *id, const SECItem *item1, - const SECItem *item2) +sdb_PutMetaData(SDB *sdb, const char *id, const SECItem *item1, + const SECItem *item2) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = sdb_p->sqlXactDB; + sqlite3 *sqlDB = sdb_p->sqlXactDB; sqlite3_stmt *stmt = NULL; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; @@ -1531,56 +1541,61 @@ sdb_PutMetaData(SDB *sdb, const char *id, const SECItem *item1, const char *cmd = PW_CREATE_CMD; if ((sdb->sdb_flags & SDB_RDONLY) != 0) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } - LOCK_SQLITE() + LOCK_SQLITE() error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } if (!tableExists(sqlDB, "metaData")) { - sqlerr = sqlite3_exec(sqlDB, PW_CREATE_TABLE_CMD, NULL, 0, NULL); - if (sqlerr != SQLITE_OK) goto loser; + sqlerr = sqlite3_exec(sqlDB, PW_CREATE_TABLE_CMD, NULL, 0, NULL); + if (sqlerr != SQLITE_OK) + goto loser; } if (item2 == NULL) { - cmd = MD_CREATE_CMD; + cmd = MD_CREATE_CMD; } sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; sqlerr = sqlite3_bind_blob(stmt, 2, item1->data, item1->len, SQLITE_STATIC); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; if (item2) { - sqlerr = sqlite3_bind_blob(stmt, 3, item2->data, - item2->len, SQLITE_STATIC); - if (sqlerr != SQLITE_OK) goto loser; + sqlerr = sqlite3_bind_blob(stmt, 3, item2->data, + item2->len, SQLITE_STATIC); + if (sqlerr != SQLITE_OK) + goto loser; } do { - sqlerr = sqlite3_step(stmt); - if (sqlerr == SQLITE_BUSY) { - PR_Sleep(SDB_BUSY_RETRY_TIME); - } - } while (!sdb_done(sqlerr,&retry)); + sqlerr = sqlite3_step(stmt); + if (sqlerr == SQLITE_BUSY) { + PR_Sleep(SDB_BUSY_RETRY_TIME); + } + } while (!sdb_done(sqlerr, &retry)); loser: /* fix up the error if necessary */ if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); + error = sdb_mapSQLError(sdb_p->type, sqlerr); } if (stmt) { - sqlite3_reset(stmt); - sqlite3_finalize(stmt); + sqlite3_reset(stmt); + sqlite3_finalize(stmt); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } @@ -1590,54 +1605,54 @@ CK_RV sdb_Reset(SDB *sdb) { SDBPrivate *sdb_p = sdb->private; - sqlite3 *sqlDB = NULL; + sqlite3 *sqlDB = NULL; char *newStr; int sqlerr = SQLITE_OK; CK_RV error = CKR_OK; /* only Key databases can be reset */ if (sdb_p->type != SDB_KEY) { - return CKR_OBJECT_HANDLE_INVALID; + return CKR_OBJECT_HANDLE_INVALID; } - LOCK_SQLITE() + LOCK_SQLITE() error = sdb_openDBLocal(sdb_p, &sqlDB, NULL); if (error != CKR_OK) { - goto loser; + goto loser; } /* delete the key table */ - newStr = sqlite3_mprintf(RESET_CMD, sdb_p->table); + newStr = sqlite3_mprintf(RESET_CMD, sdb_p->table); if (newStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; + error = CKR_HOST_MEMORY; + goto loser; } sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) goto loser; + if (sqlerr != SQLITE_OK) + goto loser; /* delete the password entry table */ - sqlerr = sqlite3_exec(sqlDB, "DROP TABLE IF EXISTS metaData;", + sqlerr = sqlite3_exec(sqlDB, "DROP TABLE IF EXISTS metaData;", NULL, 0, NULL); loser: /* fix up the error if necessary */ if (error == CKR_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); + error = sdb_mapSQLError(sdb_p->type, sqlerr); } if (sqlDB) { - sdb_closeDBLocal(sdb_p, sqlDB) ; + sdb_closeDBLocal(sdb_p, sqlDB); } - UNLOCK_SQLITE() + UNLOCK_SQLITE() return error; } - -CK_RV -sdb_Close(SDB *sdb) +CK_RV +sdb_Close(SDB *sdb) { SDBPrivate *sdb_p = sdb->private; int sqlerr = SQLITE_OK; @@ -1646,30 +1661,31 @@ sdb_Close(SDB *sdb) sqlerr = sqlite3_close(sdb_p->sqlReadDB); PORT_Free(sdb_p->sqlDBName); if (sdb_p->cacheTable) { - sqlite3_free(sdb_p->cacheTable); + sqlite3_free(sdb_p->cacheTable); } if (sdb_p->dbMon) { - PR_DestroyMonitor(sdb_p->dbMon); + PR_DestroyMonitor(sdb_p->dbMon); } free(sdb_p); free(sdb); return sdb_mapSQLError(type, sqlerr); } - /* * functions to support open */ static const char CHECK_TABLE_CMD[] = "SELECT ALL * FROM %s LIMIT 0;"; + /* return 1 if sqlDB contains table 'tableName */ -static int tableExists(sqlite3 *sqlDB, const char *tableName) +static int +tableExists(sqlite3 *sqlDB, const char *tableName) { - char * cmd = sqlite3_mprintf(CHECK_TABLE_CMD, tableName); + char *cmd = sqlite3_mprintf(CHECK_TABLE_CMD, tableName); int sqlerr = SQLITE_OK; if (cmd == NULL) { - return 0; + return 0; } sqlerr = sqlite3_exec(sqlDB, cmd, NULL, 0, 0); @@ -1678,7 +1694,8 @@ static int tableExists(sqlite3 *sqlDB, const char *tableName) return (sqlerr == SQLITE_OK) ? 1 : 0; } -void sdb_SetForkState(PRBool forked) +void +sdb_SetForkState(PRBool forked) { /* XXXright now this is a no-op. The global fork state in the softokn3 * shared library is already taken care of at the PKCS#11 level. @@ -1690,11 +1707,11 @@ void sdb_SetForkState(PRBool forked) * initialize a single database */ static const char INIT_CMD[] = - "CREATE TABLE %s (id PRIMARY KEY UNIQUE ON CONFLICT ABORT%s)"; + "CREATE TABLE %s (id PRIMARY KEY UNIQUE ON CONFLICT ABORT%s)"; -CK_RV +CK_RV sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, - int *newInit, int flags, PRUint32 accessOps, SDB **pSdb) + int *newInit, int inFlags, PRUint32 accessOps, SDB **pSdb) { int i; char *initStr = NULL; @@ -1710,117 +1727,123 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, char *env; PRBool enableCache = PR_FALSE; PRBool create; + int flags = inFlags & 0x7; *pSdb = NULL; *inUpdate = 0; - /* sqlite3 doesn't have a flag to specify that we want to + /* sqlite3 doesn't have a flag to specify that we want to * open the database read only. If the db doesn't exist, * sqlite3 will always create it. */ LOCK_SQLITE(); create = (PR_Access(dbname, PR_ACCESS_EXISTS) != PR_SUCCESS); if ((flags == SDB_RDONLY) && create) { - error = sdb_mapSQLError(type, SQLITE_CANTOPEN); - goto loser; + error = sdb_mapSQLError(type, SQLITE_CANTOPEN); + goto loser; } sqlerr = sdb_openDB(dbname, &sqlDB, flags); if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; + error = sdb_mapSQLError(type, sqlerr); + goto loser; } - /* sql created the file, but it doesn't set appropriate modes for - * a database */ - if (create) { - /* NO NSPR call for this? :( */ - chmod (dbname, 0600); + + /* + * SQL created the file, but it doesn't set appropriate modes for + * a database. + * + * NO NSPR call for chmod? :( + */ + if (create && chmod(dbname, 0600) != 0) { + error = sdb_mapSQLError(type, SQLITE_CANTOPEN); + goto loser; } if (flags != SDB_RDONLY) { - sqlerr = sqlite3_exec(sqlDB, BEGIN_CMD, NULL, 0, NULL); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } - inTransaction = 1; - } - if (!tableExists(sqlDB,table)) { - *newInit = 1; - if (flags != SDB_CREATE) { - error = sdb_mapSQLError(type, SQLITE_CANTOPEN); - goto loser; - } - initStr = sqlite3_mprintf(""); - for (i=0; initStr && i < known_attributes_size; i++) { - newStr = sqlite3_mprintf("%s, a%x",initStr, known_attributes[i]); - sqlite3_free(initStr); - initStr = newStr; - } - if (initStr == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } - - newStr = sqlite3_mprintf(INIT_CMD, table, initStr); - sqlite3_free(initStr); - if (newStr == NULL) { + sqlerr = sqlite3_exec(sqlDB, BEGIN_CMD, NULL, 0, NULL); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } + inTransaction = 1; + } + if (!tableExists(sqlDB, table)) { + *newInit = 1; + if (flags != SDB_CREATE) { + error = sdb_mapSQLError(type, SQLITE_CANTOPEN); + goto loser; + } + initStr = sqlite3_mprintf(""); + for (i = 0; initStr && i < known_attributes_size; i++) { + newStr = sqlite3_mprintf("%s, a%x", initStr, known_attributes[i]); + sqlite3_free(initStr); + initStr = newStr; + } + if (initStr == NULL) { error = CKR_HOST_MEMORY; - goto loser; - } - sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); - sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } - - newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, table); - if (newStr == NULL) { + goto loser; + } + + newStr = sqlite3_mprintf(INIT_CMD, table, initStr); + sqlite3_free(initStr); + if (newStr == NULL) { error = CKR_HOST_MEMORY; - goto loser; - } - sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); - sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } - - newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, table); - if (newStr == NULL) { + goto loser; + } + sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); + sqlite3_free(newStr); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } + + newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, table); + if (newStr == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } + sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); + sqlite3_free(newStr); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } + + newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, table); + if (newStr == NULL) { error = CKR_HOST_MEMORY; - goto loser; - } - sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); - sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } - - newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, table); - if (newStr == NULL) { + goto loser; + } + sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); + sqlite3_free(newStr); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } + + newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, table); + if (newStr == NULL) { error = CKR_HOST_MEMORY; - goto loser; - } - sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); - sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } - - newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, table); - if (newStr == NULL) { + goto loser; + } + sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); + sqlite3_free(newStr); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } + + newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, table); + if (newStr == NULL) { error = CKR_HOST_MEMORY; - goto loser; - } - sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); - sqlite3_free(newStr); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(type, sqlerr); - goto loser; - } + goto loser; + } + sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL); + sqlite3_free(newStr); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(type, sqlerr); + goto loser; + } } /* * detect the case where we have created the database, but have @@ -1833,22 +1856,22 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, * on noticing that the cert database didn't exist (see newInit set above). */ if (type == SDB_KEY && !tableExists(sqlDB, "metaData")) { - *newInit = 1; + *newInit = 1; } - + /* access to network filesystems are significantly slower than local ones * for database operations. In those cases we need to create a cached copy * of the database in a temporary location on the local disk. SQLITE * already provides a way to create a temporary table and initialize it, * so we use it for the cache (see sdb_buildCache for how it's done).*/ - /* + /* * we decide whether or not to use the cache based on the following input. * - * NSS_SDB_USE_CACHE environment variable is non-existant or set to + * NSS_SDB_USE_CACHE environment variable is non-existant or set to * anything other than "no" or "yes" ("auto", for instance). * This is the normal case. NSS will measure the performance of access - * to the temp database versus the access to the users passed in + * to the temp database versus the access to the users passed in * database location. If the temp database location is "significantly" * faster we will use the cache. * @@ -1859,56 +1882,56 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, * always be used. * * It is expected that most applications would use the "auto" selection, - * the environment variable is primarily to simplify testing, and to + * the environment variable is primarily to simplify testing, and to * correct potential corner cases where */ - env = PR_GetEnv("NSS_SDB_USE_CACHE"); - - if (env && PORT_Strcasecmp(env,"no") == 0) { - enableCache = PR_FALSE; - } else if (env && PORT_Strcasecmp(env,"yes") == 0) { - enableCache = PR_TRUE; - } else { - char *tempDir = NULL; - PRUint32 tempOps = 0; - /* - * Use PR_Access to determine how expensive it - * is to check for the existance of a local file compared to the same - * check in the temp directory. If the temp directory is faster, cache - * the database there. */ - tempDir = sdb_getTempDir(sqlDB); - if (tempDir) { - tempOps = sdb_measureAccess(tempDir); - PORT_Free(tempDir); - - /* There is a cost to continually copying the database. - * Account for that cost with the arbitrary factor of 10 */ - enableCache = (PRBool)(tempOps > accessOps * 10); - } + env = PR_GetEnvSecure("NSS_SDB_USE_CACHE"); + + if (env && PORT_Strcasecmp(env, "no") == 0) { + enableCache = PR_FALSE; + } else if (env && PORT_Strcasecmp(env, "yes") == 0) { + enableCache = PR_TRUE; + } else { + char *tempDir = NULL; + PRUint32 tempOps = 0; + /* + * Use PR_Access to determine how expensive it + * is to check for the existance of a local file compared to the same + * check in the temp directory. If the temp directory is faster, cache + * the database there. */ + tempDir = sdb_getTempDir(sqlDB); + if (tempDir) { + tempOps = sdb_measureAccess(tempDir); + PORT_Free(tempDir); + + /* There is a cost to continually copying the database. + * Account for that cost with the arbitrary factor of 10 */ + enableCache = (PRBool)(tempOps > accessOps * 10); + } } if (enableCache) { - /* try to set the temp store to memory.*/ - sqlite3_exec(sqlDB, "PRAGMA temp_store=MEMORY", NULL, 0, NULL); - /* Failure to set the temp store to memory is not fatal, + /* try to set the temp store to memory.*/ + sqlite3_exec(sqlDB, "PRAGMA temp_store=MEMORY", NULL, 0, NULL); + /* Failure to set the temp store to memory is not fatal, * ignore the error */ - cacheTable = sqlite3_mprintf("%sCache",table); - if (cacheTable == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } - /* build the cache table */ - error = sdb_buildCache(sqlDB, type, cacheTable, table); - if (error != CKR_OK) { - goto loser; - } - /* initialize the last cache build time */ - now = PR_IntervalNow(); + cacheTable = sqlite3_mprintf("%sCache", table); + if (cacheTable == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } + /* build the cache table */ + error = sdb_buildCache(sqlDB, type, cacheTable, table); + if (error != CKR_OK) { + goto loser; + } + /* initialize the last cache build time */ + now = PR_IntervalNow(); } - sdb = (SDB *) malloc(sizeof(SDB)); - sdb_p = (SDBPrivate *) malloc(sizeof(SDBPrivate)); + sdb = (SDB *)malloc(sizeof(SDB)); + sdb_p = (SDBPrivate *)malloc(sizeof(SDBPrivate)); /* invariant fields */ sdb_p->sqlDBName = PORT_Strdup(dbname); @@ -1918,14 +1941,14 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, sdb_p->lastUpdateTime = now; /* set the cache delay time. This is how long we will wait before we * decide the existing cache is stale. Currently set to 10 sec */ - sdb_p->updateInterval = PR_SecondsToInterval(10); + sdb_p->updateInterval = PR_SecondsToInterval(10); sdb_p->dbMon = PR_NewMonitor(); /* these fields are protected by the lock */ sdb_p->sqlXactDB = NULL; sdb_p->sqlXactThread = NULL; sdb->private = sdb_p; sdb->version = 0; - sdb->sdb_flags = flags | SDB_HAS_META; + sdb->sdb_flags = inFlags | SDB_HAS_META; sdb->app_private = NULL; sdb->sdb_FindObjectsInit = sdb_FindObjectsInit; sdb->sdb_FindObjects = sdb_FindObjects; @@ -1944,12 +1967,12 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, sdb->sdb_SetForkState = sdb_SetForkState; if (inTransaction) { - sqlerr = sqlite3_exec(sqlDB, COMMIT_CMD, NULL, 0, NULL); - if (sqlerr != SQLITE_OK) { - error = sdb_mapSQLError(sdb_p->type, sqlerr); - goto loser; - } - inTransaction = 0; + sqlerr = sqlite3_exec(sqlDB, COMMIT_CMD, NULL, 0, NULL); + if (sqlerr != SQLITE_OK) { + error = sdb_mapSQLError(sdb_p->type, sqlerr); + goto loser; + } + inTransaction = 0; } sdb_p->sqlReadDB = sqlDB; @@ -1961,50 +1984,48 @@ sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate, loser: /* lots of stuff to do */ if (inTransaction) { - sqlite3_exec(sqlDB, ROLLBACK_CMD, NULL, 0, NULL); + sqlite3_exec(sqlDB, ROLLBACK_CMD, NULL, 0, NULL); } if (sdb) { - free(sdb); + free(sdb); } if (sdb_p) { - free(sdb_p); + free(sdb_p); } if (sqlDB) { - sqlite3_close(sqlDB); + sqlite3_close(sqlDB); } UNLOCK_SQLITE(); return error; - } - /* sdbopen */ CK_RV s_open(const char *directory, const char *certPrefix, const char *keyPrefix, - int cert_version, int key_version, int flags, - SDB **certdb, SDB **keydb, int *newInit) + int cert_version, int key_version, int flags, + SDB **certdb, SDB **keydb, int *newInit) { char *cert = sdb_BuildFileName(directory, certPrefix, - "cert", cert_version); + "cert", cert_version); char *key = sdb_BuildFileName(directory, keyPrefix, - "key", key_version); + "key", key_version); CK_RV error = CKR_OK; int inUpdate; PRUint32 accessOps; - if (certdb) - *certdb = NULL; - if (keydb) - *keydb = NULL; + if (certdb) + *certdb = NULL; + if (keydb) + *keydb = NULL; *newInit = 0; #ifdef SQLITE_UNSAFE_THREADS if (sqlite_lock == NULL) { - sqlite_lock = PR_NewLock(); - if (sqlite_lock == NULL) { - error = CKR_HOST_MEMORY; - goto loser; - } + sqlite_lock = PR_NewLock(); + if (sqlite_lock == NULL) { + error = CKR_HOST_MEMORY; + goto loser; + } } #endif @@ -2013,12 +2034,12 @@ s_open(const char *directory, const char *certPrefix, const char *keyPrefix, accessOps = 1; { char *env; - env = PR_GetEnv("NSS_SDB_USE_CACHE"); + env = PR_GetEnvSecure("NSS_SDB_USE_CACHE"); /* If the environment variable is set to yes or no, sdb_init() will * ignore the value of accessOps, and we can skip the measuring.*/ if (!env || ((PORT_Strcasecmp(env, "no") != 0) && - (PORT_Strcasecmp(env, "yes") != 0))){ - accessOps = sdb_measureAccess(directory); + (PORT_Strcasecmp(env, "yes") != 0))) { + accessOps = sdb_measureAccess(directory); } } @@ -2026,16 +2047,16 @@ s_open(const char *directory, const char *certPrefix, const char *keyPrefix, * open the cert data base */ if (certdb) { - /* initialize Certificate database */ - error = sdb_init(cert, "nssPublic", SDB_CERT, &inUpdate, - newInit, flags, accessOps, certdb); - if (error != CKR_OK) { - goto loser; - } + /* initialize Certificate database */ + error = sdb_init(cert, "nssPublic", SDB_CERT, &inUpdate, + newInit, flags, accessOps, certdb); + if (error != CKR_OK) { + goto loser; + } } /* - * open the key data base: + * open the key data base: * NOTE:if we want to implement a single database, we open * the same database file as the certificate here. * @@ -2043,32 +2064,31 @@ s_open(const char *directory, const char *certPrefix, const char *keyPrefix, * conflict. */ if (keydb) { - /* initialize the Key database */ - error = sdb_init(key, "nssPrivate", SDB_KEY, &inUpdate, - newInit, flags, accessOps, keydb); - if (error != CKR_OK) { - goto loser; - } + /* initialize the Key database */ + error = sdb_init(key, "nssPrivate", SDB_KEY, &inUpdate, + newInit, flags, accessOps, keydb); + if (error != CKR_OK) { + goto loser; + } } - loser: if (cert) { - sqlite3_free(cert); + sqlite3_free(cert); } if (key) { - sqlite3_free(key); + sqlite3_free(key); } if (error != CKR_OK) { - /* currently redundant, but could be necessary if more code is added - * just before loser */ - if (keydb && *keydb) { - sdb_Close(*keydb); - } - if (certdb && *certdb) { - sdb_Close(*certdb); - } + /* currently redundant, but could be necessary if more code is added + * just before loser */ + if (keydb && *keydb) { + sdb_Close(*keydb); + } + if (certdb && *certdb) { + sdb_Close(*certdb); + } } return error; @@ -2079,8 +2099,8 @@ s_shutdown() { #ifdef SQLITE_UNSAFE_THREADS if (sqlite_lock) { - PR_DestroyLock(sqlite_lock); - sqlite_lock = NULL; + PR_DestroyLock(sqlite_lock); + sqlite_lock = NULL; } #endif return CKR_OK; diff --git a/nss/lib/softoken/sdb.h b/nss/lib/softoken/sdb.h index 2a855fb..04b873e 100644 --- a/nss/lib/softoken/sdb.h +++ b/nss/lib/softoken/sdb.h @@ -6,11 +6,11 @@ * * For more information about PKCS 11 See PKCS 11 Token Inteface Standard. * This implementation has two slots: - * slot 1 is our generic crypto support. It does not require login. - * It supports Public Key ops, and all they bulk ciphers and hashes. - * It can also support Private Key ops for imported Private keys. It does + * slot 1 is our generic crypto support. It does not require login. + * It supports Public Key ops, and all they bulk ciphers and hashes. + * It can also support Private Key ops for imported Private keys. It does * not have any token storage. - * slot 2 is our private key support. It requires a login before use. It + * slot 2 is our private key support. It requires a login before use. It * can store Private Keys and Certs as token objects. Currently only private * keys and their associated Certificates are saved on the token. * @@ -35,44 +35,59 @@ typedef struct SDBStr SDB; struct SDBStr { void *private; - int version; - int reserved; - int sdb_flags; + int version; + int reserved; + int sdb_flags; void *app_private; - CK_RV (*sdb_FindObjectsInit)(SDB *sdb, const CK_ATTRIBUTE *template, - CK_ULONG count, SDBFind **find); - CK_RV (*sdb_FindObjects)(SDB *sdb, SDBFind *find, CK_OBJECT_HANDLE *ids, - CK_ULONG arraySize, CK_ULONG *count); - CK_RV (*sdb_FindObjectsFinal)(SDB *sdb, SDBFind *find); - CK_RV (*sdb_GetAttributeValue)(SDB *sdb, CK_OBJECT_HANDLE object, - CK_ATTRIBUTE *template, CK_ULONG count); - CK_RV (*sdb_SetAttributeValue)(SDB *sdb, CK_OBJECT_HANDLE object, - const CK_ATTRIBUTE *template, CK_ULONG count); - CK_RV (*sdb_CreateObject)(SDB *sdb, CK_OBJECT_HANDLE *object, - const CK_ATTRIBUTE *template, CK_ULONG count); - CK_RV (*sdb_DestroyObject)(SDB *sdb, CK_OBJECT_HANDLE object); - CK_RV (*sdb_GetMetaData)(SDB *sdb, const char *id, - SECItem *item1, SECItem *item2); - CK_RV (*sdb_PutMetaData)(SDB *sdb, const char *id, - const SECItem *item1, const SECItem *item2); - CK_RV (*sdb_Begin)(SDB *sdb); - CK_RV (*sdb_Commit)(SDB *sdb); - CK_RV (*sdb_Abort)(SDB *sdb); - CK_RV (*sdb_Reset)(SDB *sdb); - CK_RV (*sdb_Close)(SDB *sdb); + CK_RV(*sdb_FindObjectsInit) + (SDB *sdb, const CK_ATTRIBUTE *template, + CK_ULONG count, SDBFind **find); + CK_RV(*sdb_FindObjects) + (SDB *sdb, SDBFind *find, CK_OBJECT_HANDLE *ids, + CK_ULONG arraySize, CK_ULONG *count); + CK_RV(*sdb_FindObjectsFinal) + (SDB *sdb, SDBFind *find); + CK_RV(*sdb_GetAttributeValue) + (SDB *sdb, CK_OBJECT_HANDLE object, + CK_ATTRIBUTE *template, CK_ULONG count); + CK_RV(*sdb_SetAttributeValue) + (SDB *sdb, CK_OBJECT_HANDLE object, + const CK_ATTRIBUTE *template, CK_ULONG count); + CK_RV(*sdb_CreateObject) + (SDB *sdb, CK_OBJECT_HANDLE *object, + const CK_ATTRIBUTE *template, CK_ULONG count); + CK_RV(*sdb_DestroyObject) + (SDB *sdb, CK_OBJECT_HANDLE object); + CK_RV(*sdb_GetMetaData) + (SDB *sdb, const char *id, + SECItem *item1, SECItem *item2); + CK_RV(*sdb_PutMetaData) + (SDB *sdb, const char *id, + const SECItem *item1, const SECItem *item2); + CK_RV(*sdb_Begin) + (SDB *sdb); + CK_RV(*sdb_Commit) + (SDB *sdb); + CK_RV(*sdb_Abort) + (SDB *sdb); + CK_RV(*sdb_Reset) + (SDB *sdb); + CK_RV(*sdb_Close) + (SDB *sdb); void (*sdb_SetForkState)(PRBool forked); }; -CK_RV s_open(const char *directory, const char *certPrefix, - const char *keyPrefix, - int cert_version, int key_version, - int flags, SDB **certdb, SDB **keydb, int *newInit); +CK_RV s_open(const char *directory, const char *certPrefix, + const char *keyPrefix, + int cert_version, int key_version, + int flags, SDB **certdb, SDB **keydb, int *newInit); CK_RV s_shutdown(); /* flags */ -#define SDB_RDONLY 1 -#define SDB_RDWR 2 -#define SDB_CREATE 4 -#define SDB_HAS_META 8 +#define SDB_RDONLY 1 +#define SDB_RDWR 2 +#define SDB_CREATE 4 +#define SDB_HAS_META 8 +#define SDB_FIPS 0x10 #endif diff --git a/nss/lib/softoken/sftkdb.c b/nss/lib/softoken/sftkdb.c index 61f1e9e..52e5161 100644 --- a/nss/lib/softoken/sftkdb.c +++ b/nss/lib/softoken/sftkdb.c @@ -1,28 +1,28 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * The following code handles the storage of PKCS 11 modules used by the * NSS. For the rest of NSS, only one kind of database handle exists: * * SFTKDBHandle * - * There is one SFTKDBHandle for the each key database and one for each cert + * There is one SFTKDBHandle for the each key database and one for each cert * database. These databases are opened as associated pairs, one pair per * slot. SFTKDBHandles are reference counted objects. * * Each SFTKDBHandle points to a low level database handle (SDB). This handle - * represents the underlying physical database. These objects are not + * represents the underlying physical database. These objects are not * reference counted, an are 'owned' by their respective SFTKDBHandles. * - * + * */ #include "sftkdb.h" #include "sftkdbti.h" #include "pkcs11t.h" #include "pkcs11i.h" #include "sdb.h" -#include "prprf.h" +#include "prprf.h" #include "pratom.h" #include "lgglue.h" #include "utilpars.h" @@ -41,84 +41,83 @@ #define BBP 8 static PRBool -sftkdb_isULONGAttribute(CK_ATTRIBUTE_TYPE type) +sftkdb_isULONGAttribute(CK_ATTRIBUTE_TYPE type) { - switch(type) { - case CKA_CERTIFICATE_CATEGORY: - case CKA_CERTIFICATE_TYPE: - case CKA_CLASS: - case CKA_JAVA_MIDP_SECURITY_DOMAIN: - case CKA_KEY_GEN_MECHANISM: - case CKA_KEY_TYPE: - case CKA_MECHANISM_TYPE: - case CKA_MODULUS_BITS: - case CKA_PRIME_BITS: - case CKA_SUBPRIME_BITS: - case CKA_VALUE_BITS: - case CKA_VALUE_LEN: - - case CKA_TRUST_DIGITAL_SIGNATURE: - case CKA_TRUST_NON_REPUDIATION: - case CKA_TRUST_KEY_ENCIPHERMENT: - case CKA_TRUST_DATA_ENCIPHERMENT: - case CKA_TRUST_KEY_AGREEMENT: - case CKA_TRUST_KEY_CERT_SIGN: - case CKA_TRUST_CRL_SIGN: - - case CKA_TRUST_SERVER_AUTH: - case CKA_TRUST_CLIENT_AUTH: - case CKA_TRUST_CODE_SIGNING: - case CKA_TRUST_EMAIL_PROTECTION: - case CKA_TRUST_IPSEC_END_SYSTEM: - case CKA_TRUST_IPSEC_TUNNEL: - case CKA_TRUST_IPSEC_USER: - case CKA_TRUST_TIME_STAMPING: - case CKA_TRUST_STEP_UP_APPROVED: - return PR_TRUE; - default: - break; + switch (type) { + case CKA_CERTIFICATE_CATEGORY: + case CKA_CERTIFICATE_TYPE: + case CKA_CLASS: + case CKA_JAVA_MIDP_SECURITY_DOMAIN: + case CKA_KEY_GEN_MECHANISM: + case CKA_KEY_TYPE: + case CKA_MECHANISM_TYPE: + case CKA_MODULUS_BITS: + case CKA_PRIME_BITS: + case CKA_SUBPRIME_BITS: + case CKA_VALUE_BITS: + case CKA_VALUE_LEN: + + case CKA_TRUST_DIGITAL_SIGNATURE: + case CKA_TRUST_NON_REPUDIATION: + case CKA_TRUST_KEY_ENCIPHERMENT: + case CKA_TRUST_DATA_ENCIPHERMENT: + case CKA_TRUST_KEY_AGREEMENT: + case CKA_TRUST_KEY_CERT_SIGN: + case CKA_TRUST_CRL_SIGN: + + case CKA_TRUST_SERVER_AUTH: + case CKA_TRUST_CLIENT_AUTH: + case CKA_TRUST_CODE_SIGNING: + case CKA_TRUST_EMAIL_PROTECTION: + case CKA_TRUST_IPSEC_END_SYSTEM: + case CKA_TRUST_IPSEC_TUNNEL: + case CKA_TRUST_IPSEC_USER: + case CKA_TRUST_TIME_STAMPING: + case CKA_TRUST_STEP_UP_APPROVED: + return PR_TRUE; + default: + break; } return PR_FALSE; - } /* are the attributes private? */ static PRBool -sftkdb_isPrivateAttribute(CK_ATTRIBUTE_TYPE type) +sftkdb_isPrivateAttribute(CK_ATTRIBUTE_TYPE type) { - switch(type) { - case CKA_VALUE: - case CKA_PRIVATE_EXPONENT: - case CKA_PRIME_1: - case CKA_PRIME_2: - case CKA_EXPONENT_1: - case CKA_EXPONENT_2: - case CKA_COEFFICIENT: - return PR_TRUE; - default: - break; + switch (type) { + case CKA_VALUE: + case CKA_PRIVATE_EXPONENT: + case CKA_PRIME_1: + case CKA_PRIME_2: + case CKA_EXPONENT_1: + case CKA_EXPONENT_2: + case CKA_COEFFICIENT: + return PR_TRUE; + default: + break; } return PR_FALSE; } /* These attributes must be authenticated with an hmac. */ static PRBool -sftkdb_isAuthenticatedAttribute(CK_ATTRIBUTE_TYPE type) +sftkdb_isAuthenticatedAttribute(CK_ATTRIBUTE_TYPE type) { - switch(type) { - case CKA_MODULUS: - case CKA_PUBLIC_EXPONENT: - case CKA_CERT_SHA1_HASH: - case CKA_CERT_MD5_HASH: - case CKA_TRUST_SERVER_AUTH: - case CKA_TRUST_CLIENT_AUTH: - case CKA_TRUST_EMAIL_PROTECTION: - case CKA_TRUST_CODE_SIGNING: - case CKA_TRUST_STEP_UP_APPROVED: - case CKA_NSS_OVERRIDE_EXTENSIONS: - return PR_TRUE; - default: - break; + switch (type) { + case CKA_MODULUS: + case CKA_PUBLIC_EXPONENT: + case CKA_CERT_SHA1_HASH: + case CKA_CERT_MD5_HASH: + case CKA_TRUST_SERVER_AUTH: + case CKA_TRUST_CLIENT_AUTH: + case CKA_TRUST_EMAIL_PROTECTION: + case CKA_TRUST_CODE_SIGNING: + case CKA_TRUST_STEP_UP_APPROVED: + case CKA_NSS_OVERRIDE_EXTENSIONS: + return PR_TRUE; + default: + break; } return PR_FALSE; } @@ -129,11 +128,11 @@ sftkdb_isAuthenticatedAttribute(CK_ATTRIBUTE_TYPE type) */ void sftk_ULong2SDBULong(unsigned char *data, CK_ULONG value) -{ +{ int i; - for (i=0; i < SDB_ULONG_SIZE; i++) { - data[i] = (value >> (SDB_ULONG_SIZE-1-i)*BBP) & 0xff; + for (i = 0; i < SDB_ULONG_SIZE; i++) { + data[i] = (value >> (SDB_ULONG_SIZE - 1 - i) * BBP) & 0xff; } } @@ -147,8 +146,8 @@ sftk_SDBULong2ULong(unsigned char *data) int i; CK_ULONG value = 0; - for (i=0; i < SDB_ULONG_SIZE; i++) { - value |= (((CK_ULONG)data[i]) << (SDB_ULONG_SIZE-1-i)*BBP); + for (i = 0; i < SDB_ULONG_SIZE; i++) { + value |= (((CK_ULONG)data[i]) << (SDB_ULONG_SIZE - 1 - i) * BBP); } return value; } @@ -159,8 +158,8 @@ sftk_SDBULong2ULong(unsigned char *data) * CK_ULONG attributes, the orignal template is passed in as is. */ static CK_ATTRIBUTE * -sftkdb_fixupTemplateIn(const CK_ATTRIBUTE *template, int count, - unsigned char **dataOut) +sftkdb_fixupTemplateIn(const CK_ATTRIBUTE *template, int count, + unsigned char **dataOut) { int i; int ulongCount = 0; @@ -170,56 +169,55 @@ sftkdb_fixupTemplateIn(const CK_ATTRIBUTE *template, int count, *dataOut = NULL; /* first count the number of CK_ULONG attributes */ - for (i=0; i < count; i++) { - /* Don't 'fixup' NULL values */ - if (!template[i].pValue) { - continue; - } - if (template[i].ulValueLen == sizeof (CK_ULONG)) { - if ( sftkdb_isULONGAttribute(template[i].type)) { - ulongCount++; - } - } + for (i = 0; i < count; i++) { + /* Don't 'fixup' NULL values */ + if (!template[i].pValue) { + continue; + } + if (template[i].ulValueLen == sizeof(CK_ULONG)) { + if (sftkdb_isULONGAttribute(template[i].type)) { + ulongCount++; + } + } } /* no attributes to fixup, just call on through */ if (ulongCount == 0) { - return (CK_ATTRIBUTE *)template; + return (CK_ATTRIBUTE *)template; } /* allocate space for new ULONGS */ - data = (unsigned char *)PORT_Alloc(SDB_ULONG_SIZE*ulongCount); + data = (unsigned char *)PORT_Alloc(SDB_ULONG_SIZE * ulongCount); if (!data) { - return NULL; + return NULL; } /* allocate new template */ - ntemplate = PORT_NewArray(CK_ATTRIBUTE,count); + ntemplate = PORT_NewArray(CK_ATTRIBUTE, count); if (!ntemplate) { - PORT_Free(data); - return NULL; + PORT_Free(data); + return NULL; } *dataOut = data; /* copy the old template, fixup the actual ulongs */ - for (i=0; i < count; i++) { - ntemplate[i] = template[i]; - /* Don't 'fixup' NULL values */ - if (!template[i].pValue) { - continue; - } - if (template[i].ulValueLen == sizeof (CK_ULONG)) { - if ( sftkdb_isULONGAttribute(template[i].type) ) { - CK_ULONG value = *(CK_ULONG *) template[i].pValue; - sftk_ULong2SDBULong(data, value); - ntemplate[i].pValue = data; - ntemplate[i].ulValueLen = SDB_ULONG_SIZE; - data += SDB_ULONG_SIZE; - } - } + for (i = 0; i < count; i++) { + ntemplate[i] = template[i]; + /* Don't 'fixup' NULL values */ + if (!template[i].pValue) { + continue; + } + if (template[i].ulValueLen == sizeof(CK_ULONG)) { + if (sftkdb_isULONGAttribute(template[i].type)) { + CK_ULONG value = *(CK_ULONG *)template[i].pValue; + sftk_ULong2SDBULong(data, value); + ntemplate[i].pValue = data; + ntemplate[i].ulValueLen = SDB_ULONG_SIZE; + data += SDB_ULONG_SIZE; + } + } } return ntemplate; } - static const char SFTKDB_META_SIG_TEMPLATE[] = "sig_%s_%08x_%08x"; /* @@ -228,7 +226,7 @@ static const char SFTKDB_META_SIG_TEMPLATE[] = "sig_%s_%08x_%08x"; const char * sftkdb_TypeString(SFTKDBHandle *handle) { - return (handle->type == SFTK_KEYDB_TYPE) ? "key" : "cert"; + return (handle->type == SFTK_KEYDB_TYPE) ? "key" : "cert"; } /* @@ -244,9 +242,9 @@ sftkdb_TypeString(SFTKDBHandle *handle) * function will fail with CKR_BUFFER_TOO_SMALL. */ static CK_RV -sftkdb_getAttributeSignature(SFTKDBHandle *handle, SFTKDBHandle *keyHandle, - CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type, - SECItem *signText) +sftkdb_getAttributeSignature(SFTKDBHandle *handle, SFTKDBHandle *keyHandle, + CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type, + SECItem *signText) { SDB *db; char id[30]; @@ -255,8 +253,8 @@ sftkdb_getAttributeSignature(SFTKDBHandle *handle, SFTKDBHandle *keyHandle, db = SFTK_GET_SDB(keyHandle); sprintf(id, SFTKDB_META_SIG_TEMPLATE, - sftkdb_TypeString(handle), - (unsigned int)objectID, (unsigned int)type); + sftkdb_TypeString(handle), + (unsigned int)objectID, (unsigned int)type); crv = (*db->sdb_GetMetaData)(db, id, signText, NULL); return crv; @@ -273,16 +271,16 @@ sftkdb_getAttributeSignature(SFTKDBHandle *handle, SFTKDBHandle *keyHandle, * This function stores that pkcs5 signature. */ CK_RV -sftkdb_PutAttributeSignature(SFTKDBHandle *handle, SDB *keyTarget, - CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type, - SECItem *signText) +sftkdb_PutAttributeSignature(SFTKDBHandle *handle, SDB *keyTarget, + CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE type, + SECItem *signText) { char id[30]; CK_RV crv; sprintf(id, SFTKDB_META_SIG_TEMPLATE, - sftkdb_TypeString(handle), - (unsigned int)objectID, (unsigned int)type); + sftkdb_TypeString(handle), + (unsigned int)objectID, (unsigned int)type); crv = (*keyTarget->sdb_PutMetaData)(keyTarget, id, signText, NULL); return crv; @@ -294,7 +292,7 @@ sftkdb_PutAttributeSignature(SFTKDBHandle *handle, SDB *keyTarget, */ static CK_RV sftkdb_fixupTemplateOut(CK_ATTRIBUTE *template, CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE *ntemplate, int count, SFTKDBHandle *handle) + CK_ATTRIBUTE *ntemplate, int count, SFTKDBHandle *handle) { int i; CK_RV crv = CKR_OK; @@ -307,130 +305,130 @@ sftkdb_fixupTemplateOut(CK_ATTRIBUTE *template, CK_OBJECT_HANDLE objectID, /* find the key handle */ keyHandle = handle; if (handle->type != SFTK_KEYDB_TYPE) { - checkEnc = PR_FALSE; - keyHandle = handle->peerDB; - } - - if ((keyHandle == NULL) || - ((SFTK_GET_SDB(keyHandle)->sdb_flags & SDB_HAS_META) == 0) || - (keyHandle->passwordKey.data == NULL)) { - checkSig = PR_FALSE; - } - - for (i=0; i < count; i++) { - CK_ULONG length = template[i].ulValueLen; - template[i].ulValueLen = ntemplate[i].ulValueLen; - /* fixup ulongs */ - if (ntemplate[i].ulValueLen == SDB_ULONG_SIZE) { - if (sftkdb_isULONGAttribute(template[i].type)) { - if (template[i].pValue) { - CK_ULONG value; - - value = sftk_SDBULong2ULong(ntemplate[i].pValue); - if (length < sizeof(CK_ULONG)) { - template[i].ulValueLen = -1; - crv = CKR_BUFFER_TOO_SMALL; - continue; - } - PORT_Memcpy(template[i].pValue,&value,sizeof(CK_ULONG)); - } - template[i].ulValueLen = sizeof(CK_ULONG); - } - } - - /* if no data was retrieved, no need to process encrypted or signed - * attributes */ - if ((template[i].pValue == NULL) || (template[i].ulValueLen == -1)) { - continue; - } - - /* fixup private attributes */ - if (checkEnc && sftkdb_isPrivateAttribute(ntemplate[i].type)) { - /* we have a private attribute */ - /* This code depends on the fact that the cipherText is bigger - * than the plain text */ - SECItem cipherText; - SECItem *plainText; - SECStatus rv; - - cipherText.data = ntemplate[i].pValue; - cipherText.len = ntemplate[i].ulValueLen; - PZ_Lock(handle->passwordLock); - if (handle->passwordKey.data == NULL) { - PZ_Unlock(handle->passwordLock); - template[i].ulValueLen = -1; - crv = CKR_USER_NOT_LOGGED_IN; - continue; - } - rv = sftkdb_DecryptAttribute(&handle->passwordKey, - &cipherText, &plainText); - PZ_Unlock(handle->passwordLock); - if (rv != SECSuccess) { - PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); - template[i].ulValueLen = -1; - crv = CKR_GENERAL_ERROR; - continue; - } - PORT_Assert(template[i].ulValueLen >= plainText->len); - if (template[i].ulValueLen < plainText->len) { - SECITEM_FreeItem(plainText,PR_TRUE); - PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); - template[i].ulValueLen = -1; - crv = CKR_GENERAL_ERROR; - continue; - } - - /* copy the plain text back into the template */ - PORT_Memcpy(template[i].pValue, plainText->data, plainText->len); - template[i].ulValueLen = plainText->len; - SECITEM_FreeItem(plainText,PR_TRUE); - } - /* make sure signed attributes are valid */ - if (checkSig && sftkdb_isAuthenticatedAttribute(ntemplate[i].type)) { - SECStatus rv; - SECItem signText; - SECItem plainText; - unsigned char signData[SDB_MAX_META_DATA_LEN]; - - signText.data = signData; - signText.len = sizeof(signData); - - rv = sftkdb_getAttributeSignature(handle, keyHandle, - objectID, ntemplate[i].type, &signText); - if (rv != SECSuccess) { - PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); - template[i].ulValueLen = -1; - crv = CKR_DATA_INVALID; /* better error code? */ - continue; - } - - plainText.data = ntemplate[i].pValue; - plainText.len = ntemplate[i].ulValueLen; - - /* - * we do a second check holding the lock just in case the user - * loggout while we were trying to get the signature. - */ - PZ_Lock(keyHandle->passwordLock); - if (keyHandle->passwordKey.data == NULL) { - /* if we are no longer logged in, no use checking the other - * Signatures either. */ - checkSig = PR_FALSE; - PZ_Unlock(keyHandle->passwordLock); - continue; - } - - rv = sftkdb_VerifyAttribute(&keyHandle->passwordKey, - objectID, ntemplate[i].type, - &plainText, &signText); - PZ_Unlock(keyHandle->passwordLock); - if (rv != SECSuccess) { - PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); - template[i].ulValueLen = -1; - crv = CKR_SIGNATURE_INVALID; /* better error code? */ - } - /* This Attribute is fine */ - } + checkEnc = PR_FALSE; + keyHandle = handle->peerDB; + } + + if ((keyHandle == NULL) || + ((SFTK_GET_SDB(keyHandle)->sdb_flags & SDB_HAS_META) == 0) || + (keyHandle->passwordKey.data == NULL)) { + checkSig = PR_FALSE; + } + + for (i = 0; i < count; i++) { + CK_ULONG length = template[i].ulValueLen; + template[i].ulValueLen = ntemplate[i].ulValueLen; + /* fixup ulongs */ + if (ntemplate[i].ulValueLen == SDB_ULONG_SIZE) { + if (sftkdb_isULONGAttribute(template[i].type)) { + if (template[i].pValue) { + CK_ULONG value; + + value = sftk_SDBULong2ULong(ntemplate[i].pValue); + if (length < sizeof(CK_ULONG)) { + template[i].ulValueLen = -1; + crv = CKR_BUFFER_TOO_SMALL; + continue; + } + PORT_Memcpy(template[i].pValue, &value, sizeof(CK_ULONG)); + } + template[i].ulValueLen = sizeof(CK_ULONG); + } + } + + /* if no data was retrieved, no need to process encrypted or signed + * attributes */ + if ((template[i].pValue == NULL) || (template[i].ulValueLen == -1)) { + continue; + } + + /* fixup private attributes */ + if (checkEnc && sftkdb_isPrivateAttribute(ntemplate[i].type)) { + /* we have a private attribute */ + /* This code depends on the fact that the cipherText is bigger + * than the plain text */ + SECItem cipherText; + SECItem *plainText; + SECStatus rv; + + cipherText.data = ntemplate[i].pValue; + cipherText.len = ntemplate[i].ulValueLen; + PZ_Lock(handle->passwordLock); + if (handle->passwordKey.data == NULL) { + PZ_Unlock(handle->passwordLock); + template[i].ulValueLen = -1; + crv = CKR_USER_NOT_LOGGED_IN; + continue; + } + rv = sftkdb_DecryptAttribute(&handle->passwordKey, + &cipherText, &plainText); + PZ_Unlock(handle->passwordLock); + if (rv != SECSuccess) { + PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); + template[i].ulValueLen = -1; + crv = CKR_GENERAL_ERROR; + continue; + } + PORT_Assert(template[i].ulValueLen >= plainText->len); + if (template[i].ulValueLen < plainText->len) { + SECITEM_FreeItem(plainText, PR_TRUE); + PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); + template[i].ulValueLen = -1; + crv = CKR_GENERAL_ERROR; + continue; + } + + /* copy the plain text back into the template */ + PORT_Memcpy(template[i].pValue, plainText->data, plainText->len); + template[i].ulValueLen = plainText->len; + SECITEM_FreeItem(plainText, PR_TRUE); + } + /* make sure signed attributes are valid */ + if (checkSig && sftkdb_isAuthenticatedAttribute(ntemplate[i].type)) { + SECStatus rv; + SECItem signText; + SECItem plainText; + unsigned char signData[SDB_MAX_META_DATA_LEN]; + + signText.data = signData; + signText.len = sizeof(signData); + + rv = sftkdb_getAttributeSignature(handle, keyHandle, + objectID, ntemplate[i].type, &signText); + if (rv != SECSuccess) { + PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); + template[i].ulValueLen = -1; + crv = CKR_DATA_INVALID; /* better error code? */ + continue; + } + + plainText.data = ntemplate[i].pValue; + plainText.len = ntemplate[i].ulValueLen; + + /* + * we do a second check holding the lock just in case the user + * loggout while we were trying to get the signature. + */ + PZ_Lock(keyHandle->passwordLock); + if (keyHandle->passwordKey.data == NULL) { + /* if we are no longer logged in, no use checking the other + * Signatures either. */ + checkSig = PR_FALSE; + PZ_Unlock(keyHandle->passwordLock); + continue; + } + + rv = sftkdb_VerifyAttribute(&keyHandle->passwordKey, + objectID, ntemplate[i].type, + &plainText, &signText); + PZ_Unlock(keyHandle->passwordLock); + if (rv != SECSuccess) { + PORT_Memset(template[i].pValue, 0, template[i].ulValueLen); + template[i].ulValueLen = -1; + crv = CKR_SIGNATURE_INVALID; /* better error code? */ + } + /* This Attribute is fine */ + } } return crv; } @@ -446,15 +444,15 @@ sftkdb_fixupTemplateOut(CK_ATTRIBUTE *template, CK_OBJECT_HANDLE objectID, * Certs themselves are considered properly authenticated by virtue of their * signature, or their matching hash with the trust object. * - * These signature is only checked for objects coming from shared databases. - * Older dbm style databases have such no signature checks. HMACs are also - * only checked when the token is logged in, as it requires a pbe generated + * These signature is only checked for objects coming from shared databases. + * Older dbm style databases have such no signature checks. HMACs are also + * only checked when the token is logged in, as it requires a pbe generated * from the password. * * Tokens which have no key database (and therefore no master password) do not * have any stored signature values. Signature values are stored in the key * database, since the signature data is tightly coupled to the key database - * password. + * password. * * This function takes a template of attributes that were either created or * modified. These attributes are checked to see if the need to be signed. @@ -468,10 +466,10 @@ sftkdb_fixupTemplateOut(CK_ATTRIBUTE *template, CK_OBJECT_HANDLE objectID, * event of a failure of this function. */ static CK_RV -sftk_signTemplate(PLArenaPool *arena, SFTKDBHandle *handle, - PRBool mayBeUpdateDB, - CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template, - CK_ULONG count) +sftk_signTemplate(PLArenaPool *arena, SFTKDBHandle *handle, + PRBool mayBeUpdateDB, + CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template, + CK_ULONG count) { unsigned int i; CK_RV crv; @@ -483,112 +481,111 @@ sftk_signTemplate(PLArenaPool *arena, SFTKDBHandle *handle, PORT_Assert(handle); if (handle->type != SFTK_KEYDB_TYPE) { - keyHandle = handle->peerDB; - usingPeerDB = PR_TRUE; + keyHandle = handle->peerDB; + usingPeerDB = PR_TRUE; } /* no key DB defined? then no need to sign anything */ if (keyHandle == NULL) { - crv = CKR_OK; - goto loser; + crv = CKR_OK; + goto loser; } - /* When we are in a middle of an update, we have an update database set, + /* When we are in a middle of an update, we have an update database set, * but we want to write to the real database. The bool mayBeUpdateDB is * set to TRUE if it's possible that we want to write an update database * rather than a primary */ - keyTarget = (mayBeUpdateDB && keyHandle->update) ? - keyHandle->update : keyHandle->db; + keyTarget = (mayBeUpdateDB && keyHandle->update) ? keyHandle->update : keyHandle->db; /* skip the the database does not support meta data */ if ((keyTarget->sdb_flags & SDB_HAS_META) == 0) { - crv = CKR_OK; - goto loser; + crv = CKR_OK; + goto loser; } /* If we had to switch databases, we need to initialize a transaction. */ if (usingPeerDB) { - crv = (*keyTarget->sdb_Begin)(keyTarget); - if (crv != CKR_OK) { - goto loser; - } - inPeerDBTransaction = PR_TRUE; - } - - for (i=0; i < count; i ++) { - if (sftkdb_isAuthenticatedAttribute(template[i].type)) { - SECStatus rv; - SECItem *signText; - SECItem plainText; - - plainText.data = template[i].pValue; - plainText.len = template[i].ulValueLen; - PZ_Lock(keyHandle->passwordLock); - if (keyHandle->passwordKey.data == NULL) { - PZ_Unlock(keyHandle->passwordLock); - crv = CKR_USER_NOT_LOGGED_IN; - goto loser; - } - rv = sftkdb_SignAttribute(arena, &keyHandle->passwordKey, - objectID, template[i].type, - &plainText, &signText); - PZ_Unlock(keyHandle->passwordLock); - if (rv != SECSuccess) { - crv = CKR_GENERAL_ERROR; /* better error code here? */ - goto loser; - } - rv = sftkdb_PutAttributeSignature(handle, keyTarget, - objectID, template[i].type, signText); - if (rv != SECSuccess) { - crv = CKR_GENERAL_ERROR; /* better error code here? */ - goto loser; - } - } + crv = (*keyTarget->sdb_Begin)(keyTarget); + if (crv != CKR_OK) { + goto loser; + } + inPeerDBTransaction = PR_TRUE; + } + + for (i = 0; i < count; i++) { + if (sftkdb_isAuthenticatedAttribute(template[i].type)) { + SECStatus rv; + SECItem *signText; + SECItem plainText; + + plainText.data = template[i].pValue; + plainText.len = template[i].ulValueLen; + PZ_Lock(keyHandle->passwordLock); + if (keyHandle->passwordKey.data == NULL) { + PZ_Unlock(keyHandle->passwordLock); + crv = CKR_USER_NOT_LOGGED_IN; + goto loser; + } + rv = sftkdb_SignAttribute(arena, &keyHandle->passwordKey, + objectID, template[i].type, + &plainText, &signText); + PZ_Unlock(keyHandle->passwordLock); + if (rv != SECSuccess) { + crv = CKR_GENERAL_ERROR; /* better error code here? */ + goto loser; + } + rv = sftkdb_PutAttributeSignature(handle, keyTarget, + objectID, template[i].type, signText); + if (rv != SECSuccess) { + crv = CKR_GENERAL_ERROR; /* better error code here? */ + goto loser; + } + } } crv = CKR_OK; /* If necessary, commit the transaction */ if (inPeerDBTransaction) { - crv = (*keyTarget->sdb_Commit)(keyTarget); - if (crv != CKR_OK) { - goto loser; - } - inPeerDBTransaction = PR_FALSE; + crv = (*keyTarget->sdb_Commit)(keyTarget); + if (crv != CKR_OK) { + goto loser; + } + inPeerDBTransaction = PR_FALSE; } loser: if (inPeerDBTransaction) { - /* The transaction must have failed. Abort. */ - (*keyTarget->sdb_Abort)(keyTarget); - PORT_Assert(crv != CKR_OK); - if (crv == CKR_OK) crv = CKR_GENERAL_ERROR; + /* The transaction must have failed. Abort. */ + (*keyTarget->sdb_Abort)(keyTarget); + PORT_Assert(crv != CKR_OK); + if (crv == CKR_OK) + crv = CKR_GENERAL_ERROR; } return crv; } static CK_RV sftkdb_CreateObject(PLArenaPool *arena, SFTKDBHandle *handle, - SDB *db, CK_OBJECT_HANDLE *objectID, - CK_ATTRIBUTE *template, CK_ULONG count) + SDB *db, CK_OBJECT_HANDLE *objectID, + CK_ATTRIBUTE *template, CK_ULONG count) { CK_RV crv; crv = (*db->sdb_CreateObject)(db, objectID, template, count); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = sftk_signTemplate(arena, handle, (db == handle->update), - *objectID, template, count); + *objectID, template, count); loser: return crv; } - -CK_ATTRIBUTE * -sftk_ExtractTemplate(PLArenaPool *arena, SFTKObject *object, - SFTKDBHandle *handle,CK_ULONG *pcount, - CK_RV *crv) +CK_ATTRIBUTE * +sftk_ExtractTemplate(PLArenaPool *arena, SFTKObject *object, + SFTKDBHandle *handle, CK_ULONG *pcount, + CK_RV *crv) { unsigned int count; CK_ATTRIBUTE *template; @@ -599,94 +596,93 @@ sftk_ExtractTemplate(PLArenaPool *arena, SFTKObject *object, *crv = CKR_OK; if (sessObject == NULL) { - *crv = CKR_GENERAL_ERROR; /* internal programming error */ - return NULL; + *crv = CKR_GENERAL_ERROR; /* internal programming error */ + return NULL; } PORT_Assert(handle); /* find the key handle */ if (handle->type != SFTK_KEYDB_TYPE) { - doEnc = PR_FALSE; + doEnc = PR_FALSE; } PZ_Lock(sessObject->attributeLock); count = 0; - for (i=0; i < sessObject->hashSize; i++) { - SFTKAttribute *attr; - for (attr=sessObject->head[i]; attr; attr=attr->next) { - count++; - } + for (i = 0; i < sessObject->hashSize; i++) { + SFTKAttribute *attr; + for (attr = sessObject->head[i]; attr; attr = attr->next) { + count++; + } } template = PORT_ArenaNewArray(arena, CK_ATTRIBUTE, count); if (template == NULL) { PZ_Unlock(sessObject->attributeLock); - *crv = CKR_HOST_MEMORY; - return NULL; + *crv = CKR_HOST_MEMORY; + return NULL; } templateIndex = 0; - for (i=0; i < sessObject->hashSize; i++) { - SFTKAttribute *attr; - for (attr=sessObject->head[i]; attr; attr=attr->next) { - CK_ATTRIBUTE *tp = &template[templateIndex++]; - /* copy the attribute */ - *tp = attr->attrib; - - /* fixup ULONG s */ - if ((tp->ulValueLen == sizeof (CK_ULONG)) && - (sftkdb_isULONGAttribute(tp->type)) ) { - CK_ULONG value = *(CK_ULONG *) tp->pValue; - unsigned char *data; - - tp->pValue = PORT_ArenaAlloc(arena, SDB_ULONG_SIZE); - data = (unsigned char *)tp->pValue; - if (data == NULL) { - *crv = CKR_HOST_MEMORY; - break; - } - sftk_ULong2SDBULong(data, value); - tp->ulValueLen = SDB_ULONG_SIZE; - } - - /* encrypt private attributes */ - if (doEnc && sftkdb_isPrivateAttribute(tp->type)) { - /* we have a private attribute */ - SECItem *cipherText; - SECItem plainText; - SECStatus rv; - - plainText.data = tp->pValue; - plainText.len = tp->ulValueLen; - PZ_Lock(handle->passwordLock); - if (handle->passwordKey.data == NULL) { - PZ_Unlock(handle->passwordLock); - *crv = CKR_USER_NOT_LOGGED_IN; - break; - } - rv = sftkdb_EncryptAttribute(arena, &handle->passwordKey, - &plainText, &cipherText); - PZ_Unlock(handle->passwordLock); - if (rv == SECSuccess) { - tp->pValue = cipherText->data; - tp->ulValueLen = cipherText->len; - } else { - *crv = CKR_GENERAL_ERROR; /* better error code here? */ - break; - } - PORT_Memset(plainText.data, 0, plainText.len); - } - } + for (i = 0; i < sessObject->hashSize; i++) { + SFTKAttribute *attr; + for (attr = sessObject->head[i]; attr; attr = attr->next) { + CK_ATTRIBUTE *tp = &template[templateIndex++]; + /* copy the attribute */ + *tp = attr->attrib; + + /* fixup ULONG s */ + if ((tp->ulValueLen == sizeof(CK_ULONG)) && + (sftkdb_isULONGAttribute(tp->type))) { + CK_ULONG value = *(CK_ULONG *)tp->pValue; + unsigned char *data; + + tp->pValue = PORT_ArenaAlloc(arena, SDB_ULONG_SIZE); + data = (unsigned char *)tp->pValue; + if (data == NULL) { + *crv = CKR_HOST_MEMORY; + break; + } + sftk_ULong2SDBULong(data, value); + tp->ulValueLen = SDB_ULONG_SIZE; + } + + /* encrypt private attributes */ + if (doEnc && sftkdb_isPrivateAttribute(tp->type)) { + /* we have a private attribute */ + SECItem *cipherText; + SECItem plainText; + SECStatus rv; + + plainText.data = tp->pValue; + plainText.len = tp->ulValueLen; + PZ_Lock(handle->passwordLock); + if (handle->passwordKey.data == NULL) { + PZ_Unlock(handle->passwordLock); + *crv = CKR_USER_NOT_LOGGED_IN; + break; + } + rv = sftkdb_EncryptAttribute(arena, &handle->passwordKey, + &plainText, &cipherText); + PZ_Unlock(handle->passwordLock); + if (rv == SECSuccess) { + tp->pValue = cipherText->data; + tp->ulValueLen = cipherText->len; + } else { + *crv = CKR_GENERAL_ERROR; /* better error code here? */ + break; + } + PORT_Memset(plainText.data, 0, plainText.len); + } + } } PORT_Assert(templateIndex <= count); PZ_Unlock(sessObject->attributeLock); if (*crv != CKR_OK) { - return NULL; + return NULL; } if (pcount) { - *pcount = count; + *pcount = count; } return template; - } /* @@ -696,41 +692,40 @@ sftk_ExtractTemplate(PLArenaPool *arena, SFTKObject *object, * modify the actual value in the template. */ static CK_ATTRIBUTE * -sftkdb_getAttributeFromTemplate(CK_ATTRIBUTE_TYPE attribute, - CK_ATTRIBUTE *ptemplate, CK_ULONG len) +sftkdb_getAttributeFromTemplate(CK_ATTRIBUTE_TYPE attribute, + CK_ATTRIBUTE *ptemplate, CK_ULONG len) { CK_ULONG i; - for (i=0; i < len; i++) { - if (attribute == ptemplate[i].type) { - return &ptemplate[i]; - } + for (i = 0; i < len; i++) { + if (attribute == ptemplate[i].type) { + return &ptemplate[i]; + } } return NULL; } static const CK_ATTRIBUTE * -sftkdb_getAttributeFromConstTemplate(CK_ATTRIBUTE_TYPE attribute, - const CK_ATTRIBUTE *ptemplate, CK_ULONG len) +sftkdb_getAttributeFromConstTemplate(CK_ATTRIBUTE_TYPE attribute, + const CK_ATTRIBUTE *ptemplate, CK_ULONG len) { CK_ULONG i; - for (i=0; i < len; i++) { - if (attribute == ptemplate[i].type) { - return &ptemplate[i]; - } + for (i = 0; i < len; i++) { + if (attribute == ptemplate[i].type) { + return &ptemplate[i]; + } } return NULL; } - /* * fetch a template which identifies 'unique' entries based on object type */ static CK_RV sftkdb_getFindTemplate(CK_OBJECT_CLASS objectType, unsigned char *objTypeData, - CK_ATTRIBUTE *findTemplate, CK_ULONG *findCount, - CK_ATTRIBUTE *ptemplate, int len) + CK_ATTRIBUTE *findTemplate, CK_ULONG *findCount, + CK_ATTRIBUTE *ptemplate, int len) { CK_ATTRIBUTE *attr; CK_ULONG count = 1; @@ -741,69 +736,69 @@ sftkdb_getFindTemplate(CK_OBJECT_CLASS objectType, unsigned char *objTypeData, findTemplate[0].ulValueLen = SDB_ULONG_SIZE; switch (objectType) { - case CKO_CERTIFICATE: - case CKO_NSS_TRUST: - attr = sftkdb_getAttributeFromTemplate(CKA_ISSUER, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[1] = *attr; - attr = sftkdb_getAttributeFromTemplate(CKA_SERIAL_NUMBER, - ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[2] = *attr; - count = 3; - break; - - case CKO_PRIVATE_KEY: - case CKO_PUBLIC_KEY: - case CKO_SECRET_KEY: - attr = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - if (attr->ulValueLen == 0) { - /* key is too generic to determine that it's unique, usually - * happens in the key gen case */ - return CKR_OBJECT_HANDLE_INVALID; - } - - findTemplate[1] = *attr; - count = 2; - break; - - case CKO_NSS_CRL: - attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[1] = *attr; - count = 2; - break; - - case CKO_NSS_SMIME: - attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[1] = *attr; - attr = sftkdb_getAttributeFromTemplate(CKA_NSS_EMAIL, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[2] = *attr; - count = 3; - break; - default: - attr = sftkdb_getAttributeFromTemplate(CKA_VALUE, ptemplate, len); - if (attr == NULL) { - return CKR_TEMPLATE_INCOMPLETE; - } - findTemplate[1] = *attr; - count = 2; - break; + case CKO_CERTIFICATE: + case CKO_NSS_TRUST: + attr = sftkdb_getAttributeFromTemplate(CKA_ISSUER, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[1] = *attr; + attr = sftkdb_getAttributeFromTemplate(CKA_SERIAL_NUMBER, + ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[2] = *attr; + count = 3; + break; + + case CKO_PRIVATE_KEY: + case CKO_PUBLIC_KEY: + case CKO_SECRET_KEY: + attr = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + if (attr->ulValueLen == 0) { + /* key is too generic to determine that it's unique, usually + * happens in the key gen case */ + return CKR_OBJECT_HANDLE_INVALID; + } + + findTemplate[1] = *attr; + count = 2; + break; + + case CKO_NSS_CRL: + attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[1] = *attr; + count = 2; + break; + + case CKO_NSS_SMIME: + attr = sftkdb_getAttributeFromTemplate(CKA_SUBJECT, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[1] = *attr; + attr = sftkdb_getAttributeFromTemplate(CKA_NSS_EMAIL, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[2] = *attr; + count = 3; + break; + default: + attr = sftkdb_getAttributeFromTemplate(CKA_VALUE, ptemplate, len); + if (attr == NULL) { + return CKR_TEMPLATE_INCOMPLETE; + } + findTemplate[1] = *attr; + count = 2; + break; } *findCount = count; @@ -815,8 +810,8 @@ sftkdb_getFindTemplate(CK_OBJECT_CLASS objectType, unsigned char *objTypeData, * it does. */ static CK_RV -sftkdb_lookupObject(SDB *db, CK_OBJECT_CLASS objectType, - CK_OBJECT_HANDLE *id, CK_ATTRIBUTE *ptemplate, CK_ULONG len) +sftkdb_lookupObject(SDB *db, CK_OBJECT_CLASS objectType, + CK_OBJECT_HANDLE *id, CK_ATTRIBUTE *ptemplate, CK_ULONG len) { CK_ATTRIBUTE findTemplate[3]; CK_ULONG count = 1; @@ -827,49 +822,48 @@ sftkdb_lookupObject(SDB *db, CK_OBJECT_CLASS objectType, *id = CK_INVALID_HANDLE; if (objectType == CKO_NSS_CRL) { - return CKR_OK; + return CKR_OK; } crv = sftkdb_getFindTemplate(objectType, objTypeData, - findTemplate, &count, ptemplate, len); + findTemplate, &count, ptemplate, len); if (crv == CKR_OBJECT_HANDLE_INVALID) { - /* key is too generic to determine that it's unique, usually - * happens in the key gen case, tell the caller to go ahead - * and just create it */ - return CKR_OK; + /* key is too generic to determine that it's unique, usually + * happens in the key gen case, tell the caller to go ahead + * and just create it */ + return CKR_OK; } if (crv != CKR_OK) { - return crv; + return crv; } /* use the raw find, so we get the correct database */ crv = (*db->sdb_FindObjectsInit)(db, findTemplate, count, &find); if (crv != CKR_OK) { - return crv; + return crv; } (*db->sdb_FindObjects)(db, find, id, 1, &objCount); (*db->sdb_FindObjectsFinal)(db, find); if (objCount == 0) { - *id = CK_INVALID_HANDLE; + *id = CK_INVALID_HANDLE; } return CKR_OK; } - /* * check to see if this template conflicts with others in our current database. */ static CK_RV -sftkdb_checkConflicts(SDB *db, CK_OBJECT_CLASS objectType, - const CK_ATTRIBUTE *ptemplate, CK_ULONG len, - CK_OBJECT_HANDLE sourceID) +sftkdb_checkConflicts(SDB *db, CK_OBJECT_CLASS objectType, + const CK_ATTRIBUTE *ptemplate, CK_ULONG len, + CK_OBJECT_HANDLE sourceID) { CK_ATTRIBUTE findTemplate[2]; unsigned char objTypeData[SDB_ULONG_SIZE]; - /* we may need to allocate some temporaries. Keep track of what was + /* we may need to allocate some temporaries. Keep track of what was * allocated so we can free it in the end */ - unsigned char *temp1 = NULL; + unsigned char *temp1 = NULL; unsigned char *temp2 = NULL; CK_ULONG objCount = 0; SDBFind *find = NULL; @@ -878,52 +872,52 @@ sftkdb_checkConflicts(SDB *db, CK_OBJECT_CLASS objectType, CK_RV crv; CK_ATTRIBUTE subject; - /* Currently the only conflict is with nicknames pointing to the same + /* Currently the only conflict is with nicknames pointing to the same * subject when creating or modifying a certificate. */ /* If the object is not a cert, no problem. */ if (objectType != CKO_CERTIFICATE) { - return CKR_OK; + return CKR_OK; } /* if not setting a nickname then there's still no problem */ attr = sftkdb_getAttributeFromConstTemplate(CKA_LABEL, ptemplate, len); if ((attr == NULL) || (attr->ulValueLen == 0)) { - return CKR_OK; + return CKR_OK; } /* fetch the subject of the source. For creation and merge, this should * be found in the template */ attr2 = sftkdb_getAttributeFromConstTemplate(CKA_SUBJECT, ptemplate, len); if (sourceID == CK_INVALID_HANDLE) { - if ((attr2 == NULL) || ((CK_LONG)attr2->ulValueLen < 0)) { - crv = CKR_TEMPLATE_INCOMPLETE; - goto done; - } + if ((attr2 == NULL) || ((CK_LONG)attr2->ulValueLen < 0)) { + crv = CKR_TEMPLATE_INCOMPLETE; + goto done; + } } else if ((attr2 == NULL) || ((CK_LONG)attr2->ulValueLen <= 0)) { - /* sourceID is set if we are trying to modify an existing entry instead - * of creating a new one. In this case the subject may not be (probably - * isn't) in the template, we have to read it from the database */ - subject.type = CKA_SUBJECT; - subject.pValue = NULL; - subject.ulValueLen = 0; - crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1); - if (crv != CKR_OK) { - goto done; - } - if ((CK_LONG)subject.ulValueLen < 0) { - crv = CKR_DEVICE_ERROR; /* closest pkcs11 error to corrupted DB */ - goto done; - } - temp1 = subject.pValue = PORT_Alloc(++subject.ulValueLen); - if (temp1 == NULL) { - crv = CKR_HOST_MEMORY; - goto done; - } - crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1); - if (crv != CKR_OK) { - goto done; - } - attr2 = &subject; - } - + /* sourceID is set if we are trying to modify an existing entry instead + * of creating a new one. In this case the subject may not be (probably + * isn't) in the template, we have to read it from the database */ + subject.type = CKA_SUBJECT; + subject.pValue = NULL; + subject.ulValueLen = 0; + crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1); + if (crv != CKR_OK) { + goto done; + } + if ((CK_LONG)subject.ulValueLen < 0) { + crv = CKR_DEVICE_ERROR; /* closest pkcs11 error to corrupted DB */ + goto done; + } + temp1 = subject.pValue = PORT_Alloc(++subject.ulValueLen); + if (temp1 == NULL) { + crv = CKR_HOST_MEMORY; + goto done; + } + crv = (*db->sdb_GetAttributeValue)(db, sourceID, &subject, 1); + if (crv != CKR_OK) { + goto done; + } + attr2 = &subject; + } + /* check for another cert in the database with the same nickname */ sftk_ULong2SDBULong(objTypeData, objectType); findTemplate[0].type = CKA_CLASS; @@ -933,65 +927,64 @@ sftkdb_checkConflicts(SDB *db, CK_OBJECT_CLASS objectType, crv = (*db->sdb_FindObjectsInit)(db, findTemplate, 2, &find); if (crv != CKR_OK) { - goto done; + goto done; } (*db->sdb_FindObjects)(db, find, &id, 1, &objCount); (*db->sdb_FindObjectsFinal)(db, find); - /* object count == 0 means no conflicting certs found, + /* object count == 0 means no conflicting certs found, * go on with the operation */ if (objCount == 0) { - crv = CKR_OK; - goto done; + crv = CKR_OK; + goto done; } /* There is a least one cert that shares the nickname, make sure it also * matches the subject. */ findTemplate[0] = *attr2; - /* we know how big the source subject was. Use that length to create the - * space for the target. If it's not enough space, then it means the - * source subject is too big, and therefore not a match. GetAttributeValue - * will return CKR_BUFFER_TOO_SMALL. Otherwise it should be exactly enough + /* we know how big the source subject was. Use that length to create the + * space for the target. If it's not enough space, then it means the + * source subject is too big, and therefore not a match. GetAttributeValue + * will return CKR_BUFFER_TOO_SMALL. Otherwise it should be exactly enough * space (or enough space to be able to compare the result. */ temp2 = findTemplate[0].pValue = PORT_Alloc(++findTemplate[0].ulValueLen); if (temp2 == NULL) { - crv = CKR_HOST_MEMORY; - goto done; + crv = CKR_HOST_MEMORY; + goto done; } crv = (*db->sdb_GetAttributeValue)(db, id, findTemplate, 1); if (crv != CKR_OK) { - if (crv == CKR_BUFFER_TOO_SMALL) { - /* if our buffer is too small, then the Subjects clearly do - * not match */ - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; - } - /* otherwise we couldn't get the value, just fail */ - goto done; - } - - /* Ok, we have both subjects, make sure they are the same. + if (crv == CKR_BUFFER_TOO_SMALL) { + /* if our buffer is too small, then the Subjects clearly do + * not match */ + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; + } + /* otherwise we couldn't get the value, just fail */ + goto done; + } + + /* Ok, we have both subjects, make sure they are the same. * Compare the subjects */ - if ((findTemplate[0].ulValueLen != attr2->ulValueLen) || - (attr2->ulValueLen > 0 && - PORT_Memcmp(findTemplate[0].pValue, attr2->pValue, attr2->ulValueLen) - != 0)) { - crv = CKR_ATTRIBUTE_VALUE_INVALID; - goto loser; + if ((findTemplate[0].ulValueLen != attr2->ulValueLen) || + (attr2->ulValueLen > 0 && + PORT_Memcmp(findTemplate[0].pValue, attr2->pValue, attr2->ulValueLen) != 0)) { + crv = CKR_ATTRIBUTE_VALUE_INVALID; + goto loser; } crv = CKR_OK; - + done: - /* If we've failed for some other reason than a conflict, make sure we - * return an error code other than CKR_ATTRIBUTE_VALUE_INVALID. - * (NOTE: neither sdb_FindObjectsInit nor sdb_GetAttributeValue should + /* If we've failed for some other reason than a conflict, make sure we + * return an error code other than CKR_ATTRIBUTE_VALUE_INVALID. + * (NOTE: neither sdb_FindObjectsInit nor sdb_GetAttributeValue should * return CKR_ATTRIBUTE_VALUE_INVALID, so the following is paranoia). */ if (crv == CKR_ATTRIBUTE_VALUE_INVALID) { - crv = CKR_GENERAL_ERROR; /* clearly a programming error */ + crv = CKR_GENERAL_ERROR; /* clearly a programming error */ } - /* exit point if we found a conflict */ +/* exit point if we found a conflict */ loser: PORT_Free(temp1); PORT_Free(temp2); @@ -999,20 +992,20 @@ loser: } /* - * try to update the template to fix any errors. This is only done + * try to update the template to fix any errors. This is only done * during update. * - * NOTE: we must update the template or return an error, or the update caller + * NOTE: we must update the template or return an error, or the update caller * will loop forever! * - * Two copies of the source code for this algorithm exist in NSS. + * Two copies of the source code for this algorithm exist in NSS. * Changes must be made in both copies. * The other copy is in pk11_IncrementNickname() in pk11wrap/pk11merge.c. * */ static CK_RV sftkdb_resolveConflicts(PLArenaPool *arena, CK_OBJECT_CLASS objectType, - CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) + CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) { CK_ATTRIBUTE *attr; char *nickname, *newNickname; @@ -1020,11 +1013,11 @@ sftkdb_resolveConflicts(PLArenaPool *arena, CK_OBJECT_CLASS objectType, /* sanity checks. We should never get here with these errors */ if (objectType != CKO_CERTIFICATE) { - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } attr = sftkdb_getAttributeFromTemplate(CKA_LABEL, ptemplate, *plen); if ((attr == NULL) || (attr->ulValueLen == 0)) { - return CKR_GENERAL_ERROR; /* shouldn't happen */ + return CKR_GENERAL_ERROR; /* shouldn't happen */ } /* update the nickname */ @@ -1033,49 +1026,50 @@ sftkdb_resolveConflicts(PLArenaPool *arena, CK_OBJECT_CLASS objectType, nickname = (char *)attr->pValue; /* does nickname end with " #n*" ? */ - for (end = attr->ulValueLen - 1; - end >= 2 && (digit = nickname[end]) <= '9' && digit >= '0'; - end--) /* just scan */ ; + for (end = attr->ulValueLen - 1; + end >= 2 && (digit = nickname[end]) <= '9' && digit >= '0'; + end--) /* just scan */ + ; if (attr->ulValueLen >= 3 && end < (attr->ulValueLen - 1) /* at least one digit */ && - nickname[end] == '#' && - nickname[end - 1] == ' ') { - /* Already has a suitable suffix string */ + nickname[end] == '#' && + nickname[end - 1] == ' ') { + /* Already has a suitable suffix string */ } else { - /* ... append " #2" to the name */ - static const char num2[] = " #2"; - newNickname = PORT_ArenaAlloc(arena, attr->ulValueLen + sizeof(num2)); - if (!newNickname) { - return CKR_HOST_MEMORY; - } - PORT_Memcpy(newNickname, nickname, attr->ulValueLen); - PORT_Memcpy(&newNickname[attr->ulValueLen], num2, sizeof(num2)); - attr->pValue = newNickname; /* modifies ptemplate */ - attr->ulValueLen += 3; /* 3 is strlen(num2) */ - return CKR_OK; + /* ... append " #2" to the name */ + static const char num2[] = " #2"; + newNickname = PORT_ArenaAlloc(arena, attr->ulValueLen + sizeof(num2)); + if (!newNickname) { + return CKR_HOST_MEMORY; + } + PORT_Memcpy(newNickname, nickname, attr->ulValueLen); + PORT_Memcpy(&newNickname[attr->ulValueLen], num2, sizeof(num2)); + attr->pValue = newNickname; /* modifies ptemplate */ + attr->ulValueLen += 3; /* 3 is strlen(num2) */ + return CKR_OK; } for (end = attr->ulValueLen; end-- > 0;) { - digit = nickname[end]; + digit = nickname[end]; if (digit > '9' || digit < '0') { - break; + break; } - if (digit < '9') { - nickname[end]++; - return CKR_OK; - } - nickname[end] = '0'; + if (digit < '9') { + nickname[end]++; + return CKR_OK; + } + nickname[end] = '0'; } /* we overflowed, insert a new '1' for a carry in front of the number */ newNickname = PORT_ArenaAlloc(arena, attr->ulValueLen + 1); if (!newNickname) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* PORT_Memcpy should handle len of '0' */ PORT_Memcpy(newNickname, nickname, ++end); newNickname[end] = '1'; - PORT_Memset(&newNickname[end+1],'0',attr->ulValueLen - end); + PORT_Memset(&newNickname[end + 1], '0', attr->ulValueLen - end); attr->pValue = newNickname; attr->ulValueLen++; return CKR_OK; @@ -1086,16 +1080,16 @@ sftkdb_resolveConflicts(PLArenaPool *arena, CK_OBJECT_CLASS objectType, */ static CK_RV sftkdb_setAttributeValue(PLArenaPool *arena, SFTKDBHandle *handle, - SDB *db, CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template, - CK_ULONG count) + SDB *db, CK_OBJECT_HANDLE objectID, const CK_ATTRIBUTE *template, + CK_ULONG count) { CK_RV crv; crv = (*db->sdb_SetAttributeValue)(db, objectID, template, count); if (crv != CKR_OK) { - return crv; + return crv; } - crv = sftk_signTemplate(arena, handle, db == handle->update, - objectID, template, count); + crv = sftk_signTemplate(arena, handle, db == handle->update, + objectID, template, count); return crv; } @@ -1103,8 +1097,8 @@ sftkdb_setAttributeValue(PLArenaPool *arena, SFTKDBHandle *handle, * write a softoken object out to the database. */ CK_RV -sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, - CK_OBJECT_HANDLE *objectID) +sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, + CK_OBJECT_HANDLE *objectID) { CK_ATTRIBUTE *template; PLArenaPool *arena; @@ -1117,34 +1111,34 @@ sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, *objectID = CK_INVALID_HANDLE; if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } db = SFTK_GET_SDB(handle); /* * we have opened a new database, but we have not yet updated it. We are - * still running pointing to the old database (so the application can + * still running pointing to the old database (so the application can * still read). We don't want to write to the old database at this point, * however, since it leads to user confusion. So at this point we simply * require a user login. Let NSS know this so it can prompt the user. */ if (db == handle->update) { - return CKR_USER_NOT_LOGGED_IN; + return CKR_USER_NOT_LOGGED_IN; } arena = PORT_NewArena(256); - if (arena == NULL) { - return CKR_HOST_MEMORY; + if (arena == NULL) { + return CKR_HOST_MEMORY; } template = sftk_ExtractTemplate(arena, object, handle, &count, &crv); if (!template) { - goto loser; + goto loser; } crv = (*db->sdb_Begin)(db); if (crv != CKR_OK) { - goto loser; + goto loser; } inTransaction = PR_TRUE; @@ -1152,9 +1146,9 @@ sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, * We want to make the base database as free from object specific knowledge * as possible. To maintain compatibility, keep some of the desirable * object specific semantics of the old database. - * + * * These were 2 fold: - * 1) there were certain conflicts (like trying to set the same nickname + * 1) there were certain conflicts (like trying to set the same nickname * on two different subjects) that would return an error. * 2) Importing the 'same' object would silently update that object. * @@ -1165,24 +1159,24 @@ sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, /* make sure we don't have attributes that conflict with the existing DB */ crv = sftkdb_checkConflicts(db, object->objclass, template, count, - CK_INVALID_HANDLE); + CK_INVALID_HANDLE); if (crv != CKR_OK) { - goto loser; + goto loser; } /* Find any copies that match this particular object */ crv = sftkdb_lookupObject(db, object->objclass, &id, template, count); if (crv != CKR_OK) { - goto loser; + goto loser; } if (id == CK_INVALID_HANDLE) { crv = sftkdb_CreateObject(arena, handle, db, objectID, template, count); } else { - /* object already exists, modify it's attributes */ - *objectID = id; + /* object already exists, modify it's attributes */ + *objectID = id; crv = sftkdb_setAttributeValue(arena, handle, db, id, template, count); } if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_Commit)(db); @@ -1190,27 +1184,27 @@ sftkdb_write(SFTKDBHandle *handle, SFTKObject *object, loser: if (inTransaction) { - (*db->sdb_Abort)(db); - /* It is trivial to show the following code cannot - * happen unless something is horribly wrong with our compilier or - * hardware */ - PORT_Assert(crv != CKR_OK); - if (crv == CKR_OK) crv = CKR_GENERAL_ERROR; + (*db->sdb_Abort)(db); + /* It is trivial to show the following code cannot + * happen unless something is horribly wrong with our compilier or + * hardware */ + PORT_Assert(crv != CKR_OK); + if (crv == CKR_OK) + crv = CKR_GENERAL_ERROR; } if (arena) { - PORT_FreeArena(arena,PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } if (crv == CKR_OK) { - *objectID |= (handle->type | SFTK_TOKEN_TYPE); - } + *objectID |= (handle->type | SFTK_TOKEN_TYPE); + } return crv; } - -CK_RV +CK_RV sftkdb_FindObjectsInit(SFTKDBHandle *handle, const CK_ATTRIBUTE *template, - CK_ULONG count, SDBFind **find) + CK_ULONG count, SDBFind **find) { unsigned char *data = NULL; CK_ATTRIBUTE *ntemplate = NULL; @@ -1218,55 +1212,56 @@ sftkdb_FindObjectsInit(SFTKDBHandle *handle, const CK_ATTRIBUTE *template, SDB *db; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } db = SFTK_GET_SDB(handle); - if (count != 0) { - ntemplate = sftkdb_fixupTemplateIn(template, count, &data); - if (ntemplate == NULL) { - return CKR_HOST_MEMORY; - } + if (count != 0) { + ntemplate = sftkdb_fixupTemplateIn(template, count, &data); + if (ntemplate == NULL) { + return CKR_HOST_MEMORY; + } } - - crv = (*db->sdb_FindObjectsInit)(db, ntemplate, - count, find); + + crv = (*db->sdb_FindObjectsInit)(db, ntemplate, + count, find); if (data) { - PORT_Free(ntemplate); - PORT_Free(data); + PORT_Free(ntemplate); + PORT_Free(data); } return crv; } -CK_RV -sftkdb_FindObjects(SFTKDBHandle *handle, SDBFind *find, - CK_OBJECT_HANDLE *ids, int arraySize, CK_ULONG *count) +CK_RV +sftkdb_FindObjects(SFTKDBHandle *handle, SDBFind *find, + CK_OBJECT_HANDLE *ids, int arraySize, CK_ULONG *count) { CK_RV crv; SDB *db; if (handle == NULL) { - *count = 0; - return CKR_OK; + *count = 0; + return CKR_OK; } db = SFTK_GET_SDB(handle); - crv = (*db->sdb_FindObjects)(db, find, ids, - arraySize, count); + crv = (*db->sdb_FindObjects)(db, find, ids, + arraySize, count); if (crv == CKR_OK) { - unsigned int i; - for (i=0; i < *count; i++) { - ids[i] |= (handle->type | SFTK_TOKEN_TYPE); - } + unsigned int i; + for (i = 0; i < *count; i++) { + ids[i] |= (handle->type | SFTK_TOKEN_TYPE); + } } return crv; } -CK_RV sftkdb_FindObjectsFinal(SFTKDBHandle *handle, SDBFind *find) +CK_RV +sftkdb_FindObjectsFinal(SFTKDBHandle *handle, SDBFind *find) { SDB *db; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } db = SFTK_GET_SDB(handle); return (*db->sdb_FindObjectsFinal)(db, find); @@ -1274,72 +1269,72 @@ CK_RV sftkdb_FindObjectsFinal(SFTKDBHandle *handle, SDBFind *find) CK_RV sftkdb_GetAttributeValue(SFTKDBHandle *handle, CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE *template, CK_ULONG count) + CK_ATTRIBUTE *template, CK_ULONG count) { - CK_RV crv,crv2; + CK_RV crv, crv2; CK_ATTRIBUTE *ntemplate; unsigned char *data = NULL; SDB *db; if (handle == NULL) { - return CKR_GENERAL_ERROR; + return CKR_GENERAL_ERROR; } /* short circuit common attributes */ - if (count == 1 && - (template[0].type == CKA_TOKEN || - template[0].type == CKA_PRIVATE || - template[0].type == CKA_SENSITIVE)) { - CK_BBOOL boolVal = CK_TRUE; - - if (template[0].pValue == NULL) { - template[0].ulValueLen = sizeof(CK_BBOOL); - return CKR_OK; - } - if (template[0].ulValueLen < sizeof(CK_BBOOL)) { - template[0].ulValueLen = -1; - return CKR_BUFFER_TOO_SMALL; - } - - if ((template[0].type == CKA_PRIVATE) && - (handle->type != SFTK_KEYDB_TYPE)) { - boolVal = CK_FALSE; - } - if ((template[0].type == CKA_SENSITIVE) && - (handle->type != SFTK_KEYDB_TYPE)) { - boolVal = CK_FALSE; - } - *(CK_BBOOL *)template[0].pValue = boolVal; - template[0].ulValueLen = sizeof(CK_BBOOL); - return CKR_OK; + if (count == 1 && + (template[0].type == CKA_TOKEN || + template[0].type == CKA_PRIVATE || + template[0].type == CKA_SENSITIVE)) { + CK_BBOOL boolVal = CK_TRUE; + + if (template[0].pValue == NULL) { + template[0].ulValueLen = sizeof(CK_BBOOL); + return CKR_OK; + } + if (template[0].ulValueLen < sizeof(CK_BBOOL)) { + template[0].ulValueLen = -1; + return CKR_BUFFER_TOO_SMALL; + } + + if ((template[0].type == CKA_PRIVATE) && + (handle->type != SFTK_KEYDB_TYPE)) { + boolVal = CK_FALSE; + } + if ((template[0].type == CKA_SENSITIVE) && + (handle->type != SFTK_KEYDB_TYPE)) { + boolVal = CK_FALSE; + } + *(CK_BBOOL *)template[0].pValue = boolVal; + template[0].ulValueLen = sizeof(CK_BBOOL); + return CKR_OK; } db = SFTK_GET_SDB(handle); /* nothing to do */ if (count == 0) { - return CKR_OK; + return CKR_OK; } ntemplate = sftkdb_fixupTemplateIn(template, count, &data); if (ntemplate == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } objectID &= SFTK_OBJ_ID_MASK; - crv = (*db->sdb_GetAttributeValue)(db, objectID, - ntemplate, count); - crv2 = sftkdb_fixupTemplateOut(template, objectID, ntemplate, - count, handle); - if (crv == CKR_OK) crv = crv2; + crv = (*db->sdb_GetAttributeValue)(db, objectID, + ntemplate, count); + crv2 = sftkdb_fixupTemplateOut(template, objectID, ntemplate, + count, handle); + if (crv == CKR_OK) + crv = crv2; if (data) { - PORT_Free(ntemplate); - PORT_Free(data); + PORT_Free(ntemplate); + PORT_Free(data); } return crv; - } CK_RV sftkdb_SetAttributeValue(SFTKDBHandle *handle, SFTKObject *object, - const CK_ATTRIBUTE *template, CK_ULONG count) + const CK_ATTRIBUTE *template, CK_ULONG count) { CK_ATTRIBUTE *ntemplate; unsigned char *data = NULL; @@ -1350,63 +1345,63 @@ sftkdb_SetAttributeValue(SFTKDBHandle *handle, SFTKObject *object, PRBool inTransaction = PR_FALSE; if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } db = SFTK_GET_SDB(handle); /* nothing to do */ if (count == 0) { - return CKR_OK; + return CKR_OK; } /* * we have opened a new database, but we have not yet updated it. We are - * still running pointing to the old database (so the application can + * still running pointing to the old database (so the application can * still read). We don't want to write to the old database at this point, * however, since it leads to user confusion. So at this point we simply * require a user login. Let NSS know this so it can prompt the user. */ if (db == handle->update) { - return CKR_USER_NOT_LOGGED_IN; + return CKR_USER_NOT_LOGGED_IN; } ntemplate = sftkdb_fixupTemplateIn(template, count, &data); if (ntemplate == NULL) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* make sure we don't have attributes that conflict with the existing DB */ crv = sftkdb_checkConflicts(db, object->objclass, template, count, objectID); if (crv != CKR_OK) { - goto loser; + goto loser; } arena = PORT_NewArena(256); - if (arena == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; + if (arena == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; } crv = (*db->sdb_Begin)(db); if (crv != CKR_OK) { - goto loser; + goto loser; } inTransaction = PR_TRUE; - crv = sftkdb_setAttributeValue(arena, handle, db, - objectID, template, count); + crv = sftkdb_setAttributeValue(arena, handle, db, + objectID, template, count); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_Commit)(db); loser: if (crv != CKR_OK && inTransaction) { - (*db->sdb_Abort)(db); + (*db->sdb_Abort)(db); } if (data) { - PORT_Free(ntemplate); - PORT_Free(data); + PORT_Free(ntemplate); + PORT_Free(data); } if (arena) { - PORT_FreeArena(arena, PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return crv; } @@ -1418,22 +1413,22 @@ sftkdb_DestroyObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE objectID) SDB *db; if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } db = SFTK_GET_SDB(handle); objectID &= SFTK_OBJ_ID_MASK; crv = (*db->sdb_Begin)(db); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_DestroyObject)(db, objectID); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_Commit)(db); loser: if (crv != CKR_OK) { - (*db->sdb_Abort)(db); + (*db->sdb_Abort)(db); } return crv; } @@ -1445,38 +1440,38 @@ sftkdb_CloseDB(SFTKDBHandle *handle) PRBool parentForkedAfterC_Initialize = PR_FALSE; #endif if (handle == NULL) { - return CKR_OK; + return CKR_OK; } if (handle->update) { if (handle->db->sdb_SetForkState) { (*handle->db->sdb_SetForkState)(parentForkedAfterC_Initialize); } - (*handle->update->sdb_Close)(handle->update); + (*handle->update->sdb_Close)(handle->update); } if (handle->db) { if (handle->db->sdb_SetForkState) { (*handle->db->sdb_SetForkState)(parentForkedAfterC_Initialize); } - (*handle->db->sdb_Close)(handle->db); + (*handle->db->sdb_Close)(handle->db); } if (handle->passwordKey.data) { - PORT_ZFree(handle->passwordKey.data, handle->passwordKey.len); + PORT_ZFree(handle->passwordKey.data, handle->passwordKey.len); } if (handle->passwordLock) { - SKIP_AFTER_FORK(PZ_DestroyLock(handle->passwordLock)); + SKIP_AFTER_FORK(PZ_DestroyLock(handle->passwordLock)); } if (handle->updatePasswordKey) { - SECITEM_FreeItem(handle->updatePasswordKey, PR_TRUE); + SECITEM_FreeItem(handle->updatePasswordKey, PR_TRUE); } if (handle->updateID) { - PORT_Free(handle->updateID); + PORT_Free(handle->updateID); } PORT_Free(handle); return CKR_OK; } /* - * reset a database to it's uninitialized state. + * reset a database to it's uninitialized state. */ static CK_RV sftkdb_ResetDB(SFTKDBHandle *handle) @@ -1484,26 +1479,25 @@ sftkdb_ResetDB(SFTKDBHandle *handle) CK_RV crv = CKR_OK; SDB *db; if (handle == NULL) { - return CKR_TOKEN_WRITE_PROTECTED; + return CKR_TOKEN_WRITE_PROTECTED; } db = SFTK_GET_SDB(handle); crv = (*db->sdb_Begin)(db); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_Reset)(db); if (crv != CKR_OK) { - goto loser; + goto loser; } crv = (*db->sdb_Commit)(db); loser: if (crv != CKR_OK) { - (*db->sdb_Abort)(db); + (*db->sdb_Abort)(db); } return crv; } - CK_RV sftkdb_Begin(SFTKDBHandle *handle) { @@ -1511,11 +1505,11 @@ sftkdb_Begin(SFTKDBHandle *handle) SDB *db; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } db = SFTK_GET_SDB(handle); if (db) { - crv = (*db->sdb_Begin)(db); + crv = (*db->sdb_Begin)(db); } return crv; } @@ -1527,11 +1521,11 @@ sftkdb_Commit(SFTKDBHandle *handle) SDB *db; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } db = SFTK_GET_SDB(handle); if (db) { - (*db->sdb_Commit)(db); + (*db->sdb_Commit)(db); } return crv; } @@ -1543,16 +1537,15 @@ sftkdb_Abort(SFTKDBHandle *handle) SDB *db; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } db = SFTK_GET_SDB(handle); if (db) { - crv = (db->sdb_Abort)(db); + crv = (db->sdb_Abort)(db); } return crv; } - /* * functions to update the database from an old database */ @@ -1571,7 +1564,7 @@ static const CK_ATTRIBUTE_TYPE known_attributes[] = { CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE, CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT, CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT, - CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, + CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS, CKA_SUB_PRIME_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_EXTRACTABLE, CKA_LOCAL, CKA_NEVER_EXTRACTABLE, CKA_ALWAYS_SENSITIVE, CKA_KEY_GEN_MECHANISM, CKA_MODIFIABLE, CKA_EC_PARAMS, @@ -1597,45 +1590,45 @@ static const CK_ATTRIBUTE_TYPE known_attributes[] = { CKA_NETSCAPE_DB, CKA_NETSCAPE_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS }; -static unsigned int known_attributes_size= sizeof(known_attributes)/ - sizeof(known_attributes[0]); +static unsigned int known_attributes_size = sizeof(known_attributes) / + sizeof(known_attributes[0]); static CK_RV sftkdb_GetObjectTemplate(SDB *source, CK_OBJECT_HANDLE id, - CK_ATTRIBUTE *ptemplate, CK_ULONG *max) + CK_ATTRIBUTE *ptemplate, CK_ULONG *max) { - unsigned int i,j; + unsigned int i, j; CK_RV crv; if (*max < known_attributes_size) { - *max = known_attributes_size; - return CKR_BUFFER_TOO_SMALL; + *max = known_attributes_size; + return CKR_BUFFER_TOO_SMALL; } - for (i=0; i < known_attributes_size; i++) { - ptemplate[i].type = known_attributes[i]; - ptemplate[i].pValue = NULL; - ptemplate[i].ulValueLen = 0; + for (i = 0; i < known_attributes_size; i++) { + ptemplate[i].type = known_attributes[i]; + ptemplate[i].pValue = NULL; + ptemplate[i].ulValueLen = 0; } - crv = (*source->sdb_GetAttributeValue)(source, id, - ptemplate, known_attributes_size); + crv = (*source->sdb_GetAttributeValue)(source, id, + ptemplate, known_attributes_size); if ((crv != CKR_OK) && (crv != CKR_ATTRIBUTE_TYPE_INVALID)) { - return crv; - } - - for (i=0, j=0; i < known_attributes_size; i++, j++) { - while (i < known_attributes_size && (ptemplate[i].ulValueLen == -1)) { - i++; - } - if (i >= known_attributes_size) { - break; - } - /* cheap optimization */ - if (i == j) { - continue; - } - ptemplate[j] = ptemplate[i]; + return crv; + } + + for (i = 0, j = 0; i < known_attributes_size; i++, j++) { + while (i < known_attributes_size && (ptemplate[i].ulValueLen == -1)) { + i++; + } + if (i >= known_attributes_size) { + break; + } + /* cheap optimization */ + if (i == j) { + continue; + } + ptemplate[j] = ptemplate[i]; } *max = j; return CKR_OK; @@ -1645,11 +1638,11 @@ static const char SFTKDB_META_UPDATE_TEMPLATE[] = "upd_%s_%s"; /* * check to see if we have already updated this database. - * a NULL updateID means we are trying to do an in place + * a NULL updateID means we are trying to do an in place * single database update. In that case we have already * determined that an update was necessary. */ -static PRBool +static PRBool sftkdb_hasUpdate(const char *typeString, SDB *db, const char *updateID) { char *id; @@ -1658,11 +1651,11 @@ sftkdb_hasUpdate(const char *typeString, SDB *db, const char *updateID) unsigned char dummyData[SDB_MAX_META_DATA_LEN]; if (!updateID) { - return PR_FALSE; + return PR_FALSE; } id = PR_smprintf(SFTKDB_META_UPDATE_TEMPLATE, typeString, updateID); if (id == NULL) { - return PR_FALSE; + return PR_FALSE; } dummy.data = dummyData; dummy.len = sizeof(dummyData); @@ -1686,7 +1679,7 @@ sftkdb_putUpdate(const char *typeString, SDB *db, const char *updateID) /* if no id was given, nothing to do */ if (updateID == NULL) { - return CKR_OK; + return CKR_OK; } dummy.data = (unsigned char *)updateID; @@ -1694,7 +1687,7 @@ sftkdb_putUpdate(const char *typeString, SDB *db, const char *updateID) id = PR_smprintf(SFTKDB_META_UPDATE_TEMPLATE, typeString, updateID); if (id == NULL) { - return PR_FALSE; + return PR_FALSE; } crv = (*db->sdb_PutMetaData)(db, id, &dummy, NULL); @@ -1707,14 +1700,14 @@ sftkdb_putUpdate(const char *typeString, SDB *db, const char *updateID) * NOTE: this is a raw templated stored in database order! */ static CK_ULONG -sftkdb_getULongFromTemplate(CK_ATTRIBUTE_TYPE type, - CK_ATTRIBUTE *ptemplate, CK_ULONG len) +sftkdb_getULongFromTemplate(CK_ATTRIBUTE_TYPE type, + CK_ATTRIBUTE *ptemplate, CK_ULONG len) { CK_ATTRIBUTE *attr = sftkdb_getAttributeFromTemplate(type, - ptemplate, len); + ptemplate, len); if (attr && attr->pValue && attr->ulValueLen == SDB_ULONG_SIZE) { - return sftk_SDBULong2ULong(attr->pValue); + return sftk_SDBULong2ULong(attr->pValue); } return (CK_ULONG)-1; } @@ -1723,12 +1716,12 @@ sftkdb_getULongFromTemplate(CK_ATTRIBUTE_TYPE type, * we need to find a unique CKA_ID. * The basic idea is to just increment the lowest byte. * This code also handles the following corner cases: - * 1) the single byte overflows. On overflow we increment the next byte up + * 1) the single byte overflows. On overflow we increment the next byte up * and so forth until we have overflowed the entire CKA_ID. * 2) If we overflow the entire CKA_ID we expand it by one byte. * 3) the CKA_ID is non-existant, we create a new one with one byte. - * This means no matter what CKA_ID is passed, the result of this function - * is always a new CKA_ID, and this function will never return the same + * This means no matter what CKA_ID is passed, the result of this function + * is always a new CKA_ID, and this function will never return the same * CKA_ID the it has returned in the passed. */ static CK_RV @@ -1738,34 +1731,34 @@ sftkdb_incrementCKAID(PLArenaPool *arena, CK_ATTRIBUTE *ptemplate) CK_ULONG len = ptemplate->ulValueLen; if (buf == NULL || len == (CK_ULONG)-1) { - /* we have no valid CKAID, we'll create a basic one byte CKA_ID below */ - len = 0; + /* we have no valid CKAID, we'll create a basic one byte CKA_ID below */ + len = 0; } else { - CK_ULONG i; - - /* walk from the back to front, incrementing - * the CKA_ID until we no longer have a carry, - * or have hit the front of the id. */ - for (i=len; i != 0; i--) { - buf[i-1]++; - if (buf[i-1] != 0) { - /* no more carries, the increment is complete */ - return CKR_OK; - } - } - /* we've now overflowed, fall through and expand the CKA_ID by - * one byte */ - } - buf = PORT_ArenaAlloc(arena, len+1); + CK_ULONG i; + + /* walk from the back to front, incrementing + * the CKA_ID until we no longer have a carry, + * or have hit the front of the id. */ + for (i = len; i != 0; i--) { + buf[i - 1]++; + if (buf[i - 1] != 0) { + /* no more carries, the increment is complete */ + return CKR_OK; + } + } + /* we've now overflowed, fall through and expand the CKA_ID by + * one byte */ + } + buf = PORT_ArenaAlloc(arena, len + 1); if (!buf) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } if (len > 0) { - PORT_Memcpy(buf, ptemplate->pValue, len); + PORT_Memcpy(buf, ptemplate->pValue, len); } buf[len] = 0; ptemplate->pValue = buf; - ptemplate->ulValueLen = len+1; + ptemplate->ulValueLen = len + 1; return CKR_OK; } @@ -1773,30 +1766,30 @@ sftkdb_incrementCKAID(PLArenaPool *arena, CK_ATTRIBUTE *ptemplate) * drop an attribute from a template. */ void -sftkdb_dropAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE *ptemplate, - CK_ULONG *plen) +sftkdb_dropAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE *ptemplate, + CK_ULONG *plen) { - CK_ULONG count = *plen; - CK_ULONG i; - - for (i=0; i < count; i++) { - if (attr->type == ptemplate[i].type) { - break; - } - } - - if (i == count) { - /* attribute not found */ - return; - } - - /* copy the remaining attributes up */ - for ( i++; i < count; i++) { - ptemplate[i-1] = ptemplate[i]; - } - - /* decrement the template size */ - *plen = count -1; + CK_ULONG count = *plen; + CK_ULONG i; + + for (i = 0; i < count; i++) { + if (attr->type == ptemplate[i].type) { + break; + } + } + + if (i == count) { + /* attribute not found */ + return; + } + + /* copy the remaining attributes up */ + for (i++; i < count; i++) { + ptemplate[i - 1] = ptemplate[i]; + } + + /* decrement the template size */ + *plen = count - 1; } /* @@ -1804,10 +1797,10 @@ sftkdb_dropAttribute(CK_ATTRIBUTE *attr, CK_ATTRIBUTE *ptemplate, * of true/false. (make's it easier to remember what means what. */ typedef enum { - SFTKDB_DO_NOTHING = 0, - SFTKDB_ADD_OBJECT, - SFTKDB_MODIFY_OBJECT, - SFTKDB_DROP_ATTRIBUTE + SFTKDB_DO_NOTHING = 0, + SFTKDB_ADD_OBJECT, + SFTKDB_MODIFY_OBJECT, + SFTKDB_DROP_ATTRIBUTE } sftkdbUpdateStatus; /* @@ -1821,18 +1814,18 @@ typedef enum { * return SFTKDB_DROP_ATTRIBUTE * * In the end the caller will remove any attributes in the source - * template when SFTKDB_DROP_ATTRIBUTE is specified, then use do a - * set attributes with that template on the target if we received + * template when SFTKDB_DROP_ATTRIBUTE is specified, then use do a + * set attributes with that template on the target if we received * any SFTKDB_MODIFY_OBJECT returns. */ sftkdbUpdateStatus sftkdb_reconcileTrustEntry(PLArenaPool *arena, CK_ATTRIBUTE *target, - CK_ATTRIBUTE *source) + CK_ATTRIBUTE *source) { CK_ULONG targetTrust = sftkdb_getULongFromTemplate(target->type, - target, 1); + target, 1); CK_ULONG sourceTrust = sftkdb_getULongFromTemplate(target->type, - source, 1); + source, 1); /* * try to pick the best solution between the source and the @@ -1843,24 +1836,24 @@ sftkdb_reconcileTrustEntry(PLArenaPool *arena, CK_ATTRIBUTE *target, /* they are the same, everything is already kosher */ if (targetTrust == sourceTrust) { - return SFTKDB_DO_NOTHING; + return SFTKDB_DO_NOTHING; } /* handle the case where the source Trust attribute may be a bit * flakey */ if (sourceTrust == (CK_ULONG)-1) { - /* - * The source Trust is invalid. We know that the target Trust - * must be valid here, otherwise the above - * targetTrust == sourceTrust check would have succeeded. - */ - return SFTKDB_DROP_ATTRIBUTE; + /* + * The source Trust is invalid. We know that the target Trust + * must be valid here, otherwise the above + * targetTrust == sourceTrust check would have succeeded. + */ + return SFTKDB_DROP_ATTRIBUTE; } /* target is invalid, use the source's idea of the trust value */ if (targetTrust == (CK_ULONG)-1) { - /* overwriting the target in this case is OK */ - return SFTKDB_MODIFY_OBJECT; + /* overwriting the target in this case is OK */ + return SFTKDB_MODIFY_OBJECT; } /* at this point we know that both attributes exist and have the @@ -1868,31 +1861,29 @@ sftkdb_reconcileTrustEntry(PLArenaPool *arena, CK_ATTRIBUTE *target, * ulValueLen for either attribute. */ if (sourceTrust == CKT_NSS_TRUST_UNKNOWN) { - return SFTKDB_DROP_ATTRIBUTE; + return SFTKDB_DROP_ATTRIBUTE; } /* target has no idea, use the source's idea of the trust value */ if (targetTrust == CKT_NSS_TRUST_UNKNOWN) { - /* overwriting the target in this case is OK */ - return SFTKDB_MODIFY_OBJECT; + /* overwriting the target in this case is OK */ + return SFTKDB_MODIFY_OBJECT; } - /* so both the target and the source have some idea of what this - * trust attribute should be, and neither agree exactly. - * At this point, we prefer 'hard' attributes over 'soft' ones. + /* so both the target and the source have some idea of what this + * trust attribute should be, and neither agree exactly. + * At this point, we prefer 'hard' attributes over 'soft' ones. * 'hard' ones are CKT_NSS_TRUSTED, CKT_NSS_TRUSTED_DELEGATOR, and * CKT_NSS_NOT_TRUTED. Soft ones are ones which don't change the - * actual trust of the cert (CKT_MUST_VERIFY_TRUST, + * actual trust of the cert (CKT_MUST_VERIFY_TRUST, * CKT_NSS_VALID_DELEGATOR). */ - if ((sourceTrust == CKT_NSS_MUST_VERIFY_TRUST) - || (sourceTrust == CKT_NSS_VALID_DELEGATOR)) { - return SFTKDB_DROP_ATTRIBUTE; + if ((sourceTrust == CKT_NSS_MUST_VERIFY_TRUST) || (sourceTrust == CKT_NSS_VALID_DELEGATOR)) { + return SFTKDB_DROP_ATTRIBUTE; } - if ((targetTrust == CKT_NSS_MUST_VERIFY_TRUST) - || (targetTrust == CKT_NSS_VALID_DELEGATOR)) { - /* again, overwriting the target in this case is OK */ - return SFTKDB_MODIFY_OBJECT; + if ((targetTrust == CKT_NSS_MUST_VERIFY_TRUST) || (targetTrust == CKT_NSS_VALID_DELEGATOR)) { + /* again, overwriting the target in this case is OK */ + return SFTKDB_MODIFY_OBJECT; } /* both have hard attributes, we have a conflict, let the target win. */ @@ -1900,13 +1891,13 @@ sftkdb_reconcileTrustEntry(PLArenaPool *arena, CK_ATTRIBUTE *target, } const CK_ATTRIBUTE_TYPE sftkdb_trustList[] = - { CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, - CKA_TRUST_CODE_SIGNING, CKA_TRUST_EMAIL_PROTECTION, - CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, - CKA_TRUST_TIME_STAMPING }; + { CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, + CKA_TRUST_CODE_SIGNING, CKA_TRUST_EMAIL_PROTECTION, + CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, + CKA_TRUST_TIME_STAMPING }; #define SFTK_TRUST_TEMPLATE_COUNT \ - (sizeof(sftkdb_trustList)/sizeof(sftkdb_trustList[0])) + (sizeof(sftkdb_trustList) / sizeof(sftkdb_trustList[0])) /* * Run through the list of known trust types, and reconcile each trust * entry one by one. Keep track of we really need to write out the source @@ -1914,249 +1905,242 @@ const CK_ATTRIBUTE_TYPE sftkdb_trustList[] = */ static sftkdbUpdateStatus sftkdb_reconcileTrust(PLArenaPool *arena, SDB *db, CK_OBJECT_HANDLE id, - CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) + CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) { CK_ATTRIBUTE trustTemplate[SFTK_TRUST_TEMPLATE_COUNT]; - unsigned char trustData[SFTK_TRUST_TEMPLATE_COUNT*SDB_ULONG_SIZE]; + unsigned char trustData[SFTK_TRUST_TEMPLATE_COUNT * SDB_ULONG_SIZE]; sftkdbUpdateStatus update = SFTKDB_DO_NOTHING; CK_ULONG i; CK_RV crv; - - for (i=0; i < SFTK_TRUST_TEMPLATE_COUNT; i++) { - trustTemplate[i].type = sftkdb_trustList[i]; - trustTemplate[i].pValue = &trustData[i*SDB_ULONG_SIZE]; - trustTemplate[i].ulValueLen = SDB_ULONG_SIZE; + for (i = 0; i < SFTK_TRUST_TEMPLATE_COUNT; i++) { + trustTemplate[i].type = sftkdb_trustList[i]; + trustTemplate[i].pValue = &trustData[i * SDB_ULONG_SIZE]; + trustTemplate[i].ulValueLen = SDB_ULONG_SIZE; } - crv = (*db->sdb_GetAttributeValue)(db, id, - trustTemplate, SFTK_TRUST_TEMPLATE_COUNT); + crv = (*db->sdb_GetAttributeValue)(db, id, + trustTemplate, SFTK_TRUST_TEMPLATE_COUNT); if ((crv != CKR_OK) && (crv != CKR_ATTRIBUTE_TYPE_INVALID)) { - /* target trust has some problems, update it */ - update = SFTKDB_MODIFY_OBJECT; - goto done; - } - - for (i=0; i < SFTK_TRUST_TEMPLATE_COUNT; i++) { - CK_ATTRIBUTE *attr = sftkdb_getAttributeFromTemplate( - trustTemplate[i].type, ptemplate, *plen); - sftkdbUpdateStatus status; - - - /* if target trust value doesn't exist, nothing to merge */ - if (trustTemplate[i].ulValueLen == (CK_ULONG)-1) { - /* if the source exists, then we want the source entry, - * go ahead and update */ - if (attr && attr->ulValueLen != (CK_ULONG)-1) { - update = SFTKDB_MODIFY_OBJECT; - } - continue; - } - - /* - * the source doesn't have the attribute, go to the next attribute - */ - if (attr == NULL) { - continue; - - } - status = sftkdb_reconcileTrustEntry(arena, &trustTemplate[i], attr); - if (status == SFTKDB_MODIFY_OBJECT) { - update = SFTKDB_MODIFY_OBJECT; - } else if (status == SFTKDB_DROP_ATTRIBUTE) { - /* drop the source copy of the attribute, we are going with - * the target's version */ - sftkdb_dropAttribute(attr, ptemplate, plen); - } + /* target trust has some problems, update it */ + update = SFTKDB_MODIFY_OBJECT; + goto done; + } + + for (i = 0; i < SFTK_TRUST_TEMPLATE_COUNT; i++) { + CK_ATTRIBUTE *attr = sftkdb_getAttributeFromTemplate( + trustTemplate[i].type, ptemplate, *plen); + sftkdbUpdateStatus status; + + /* if target trust value doesn't exist, nothing to merge */ + if (trustTemplate[i].ulValueLen == (CK_ULONG)-1) { + /* if the source exists, then we want the source entry, + * go ahead and update */ + if (attr && attr->ulValueLen != (CK_ULONG)-1) { + update = SFTKDB_MODIFY_OBJECT; + } + continue; + } + + /* + * the source doesn't have the attribute, go to the next attribute + */ + if (attr == NULL) { + continue; + } + status = sftkdb_reconcileTrustEntry(arena, &trustTemplate[i], attr); + if (status == SFTKDB_MODIFY_OBJECT) { + update = SFTKDB_MODIFY_OBJECT; + } else if (status == SFTKDB_DROP_ATTRIBUTE) { + /* drop the source copy of the attribute, we are going with + * the target's version */ + sftkdb_dropAttribute(attr, ptemplate, plen); + } } /* finally manage stepup */ if (update == SFTKDB_MODIFY_OBJECT) { - CK_BBOOL stepUpBool = CK_FALSE; - /* if we are going to write from the source, make sure we don't - * overwrite the stepup bit if it's on*/ - trustTemplate[0].type = CKA_TRUST_STEP_UP_APPROVED; - trustTemplate[0].pValue = &stepUpBool; - trustTemplate[0].ulValueLen = sizeof(stepUpBool); - crv = (*db->sdb_GetAttributeValue)(db, id, trustTemplate, 1); - if ((crv == CKR_OK) && (stepUpBool == CK_TRUE)) { - sftkdb_dropAttribute(trustTemplate, ptemplate, plen); - } + CK_BBOOL stepUpBool = CK_FALSE; + /* if we are going to write from the source, make sure we don't + * overwrite the stepup bit if it's on*/ + trustTemplate[0].type = CKA_TRUST_STEP_UP_APPROVED; + trustTemplate[0].pValue = &stepUpBool; + trustTemplate[0].ulValueLen = sizeof(stepUpBool); + crv = (*db->sdb_GetAttributeValue)(db, id, trustTemplate, 1); + if ((crv == CKR_OK) && (stepUpBool == CK_TRUE)) { + sftkdb_dropAttribute(trustTemplate, ptemplate, plen); + } } else { - /* we currently aren't going to update. If the source stepup bit is - * on however, do an update so the target gets it as well */ - CK_ATTRIBUTE *attr; - - attr = sftkdb_getAttributeFromTemplate(CKA_TRUST_STEP_UP_APPROVED, - ptemplate, *plen); - if (attr && (attr->ulValueLen == sizeof(CK_BBOOL)) && - (*(CK_BBOOL *)(attr->pValue) == CK_TRUE)) { - update = SFTKDB_MODIFY_OBJECT; - } - } - + /* we currently aren't going to update. If the source stepup bit is + * on however, do an update so the target gets it as well */ + CK_ATTRIBUTE *attr; + + attr = sftkdb_getAttributeFromTemplate(CKA_TRUST_STEP_UP_APPROVED, + ptemplate, *plen); + if (attr && (attr->ulValueLen == sizeof(CK_BBOOL)) && + (*(CK_BBOOL *)(attr->pValue) == CK_TRUE)) { + update = SFTKDB_MODIFY_OBJECT; + } + } + done: return update; } static sftkdbUpdateStatus sftkdb_handleIDAndName(PLArenaPool *arena, SDB *db, CK_OBJECT_HANDLE id, - CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) + CK_ATTRIBUTE *ptemplate, CK_ULONG *plen) { sftkdbUpdateStatus update = SFTKDB_DO_NOTHING; CK_ATTRIBUTE *attr1, *attr2; CK_ATTRIBUTE ttemplate[2] = { - {CKA_ID, NULL, 0}, - {CKA_LABEL, NULL, 0} + { CKA_ID, NULL, 0 }, + { CKA_LABEL, NULL, 0 } }; attr1 = sftkdb_getAttributeFromTemplate(CKA_LABEL, ptemplate, *plen); attr2 = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, *plen); /* if the source has neither an id nor label, don't bother updating */ - if ( (!attr1 || attr1->ulValueLen == 0) && - (! attr2 || attr2->ulValueLen == 0) ) { - return SFTKDB_DO_NOTHING; + if ((!attr1 || attr1->ulValueLen == 0) && + (!attr2 || attr2->ulValueLen == 0)) { + return SFTKDB_DO_NOTHING; } /* the source has either an id or a label, see what the target has */ (void)(*db->sdb_GetAttributeValue)(db, id, ttemplate, 2); /* if the target has neither, update from the source */ - if ( ((ttemplate[0].ulValueLen == 0) || - (ttemplate[0].ulValueLen == (CK_ULONG)-1)) && - ((ttemplate[1].ulValueLen == 0) || - (ttemplate[1].ulValueLen == (CK_ULONG)-1)) ) { - return SFTKDB_MODIFY_OBJECT; + if (((ttemplate[0].ulValueLen == 0) || + (ttemplate[0].ulValueLen == (CK_ULONG)-1)) && + ((ttemplate[1].ulValueLen == 0) || + (ttemplate[1].ulValueLen == (CK_ULONG)-1))) { + return SFTKDB_MODIFY_OBJECT; } /* check the CKA_ID */ - if ((ttemplate[0].ulValueLen != 0) && - (ttemplate[0].ulValueLen != (CK_ULONG)-1)) { - /* we have a CKA_ID in the target, don't overwrite - * the target with an empty CKA_ID from the source*/ - if (attr1 && attr1->ulValueLen == 0) { - sftkdb_dropAttribute(attr1, ptemplate, plen); - } + if ((ttemplate[0].ulValueLen != 0) && + (ttemplate[0].ulValueLen != (CK_ULONG)-1)) { + /* we have a CKA_ID in the target, don't overwrite + * the target with an empty CKA_ID from the source*/ + if (attr1 && attr1->ulValueLen == 0) { + sftkdb_dropAttribute(attr1, ptemplate, plen); + } } else if (attr1 && attr1->ulValueLen != 0) { - /* source has a CKA_ID, but the target doesn't, update the target */ - update = SFTKDB_MODIFY_OBJECT; + /* source has a CKA_ID, but the target doesn't, update the target */ + update = SFTKDB_MODIFY_OBJECT; } - /* check the nickname */ - if ((ttemplate[1].ulValueLen != 0) && - (ttemplate[1].ulValueLen != (CK_ULONG)-1)) { - - /* we have a nickname in the target, and we don't have to update - * the CKA_ID. We are done. NOTE: if we add addition attributes - * in this check, this shortcut can only go on the last of them. */ - if (update == SFTKDB_DO_NOTHING) { - return update; - } - /* we have a nickname in the target, don't overwrite - * the target with an empty nickname from the source */ - if (attr2 && attr2->ulValueLen == 0) { - sftkdb_dropAttribute(attr2, ptemplate, plen); - } + if ((ttemplate[1].ulValueLen != 0) && + (ttemplate[1].ulValueLen != (CK_ULONG)-1)) { + + /* we have a nickname in the target, and we don't have to update + * the CKA_ID. We are done. NOTE: if we add addition attributes + * in this check, this shortcut can only go on the last of them. */ + if (update == SFTKDB_DO_NOTHING) { + return update; + } + /* we have a nickname in the target, don't overwrite + * the target with an empty nickname from the source */ + if (attr2 && attr2->ulValueLen == 0) { + sftkdb_dropAttribute(attr2, ptemplate, plen); + } } else if (attr2 && attr2->ulValueLen != 0) { - /* source has a nickname, but the target doesn't, update the target */ - update = SFTKDB_MODIFY_OBJECT; + /* source has a nickname, but the target doesn't, update the target */ + update = SFTKDB_MODIFY_OBJECT; } return update; } - - /* * This function updates the template before we write the object out. * * If we are going to skip updating this object, return PR_FALSE. * If it should be updated we return PR_TRUE. - * To help readability, these have been defined + * To help readability, these have been defined * as SFTK_DONT_UPDATE and SFTK_UPDATE respectively. */ static PRBool sftkdb_updateObjectTemplate(PLArenaPool *arena, SDB *db, - CK_OBJECT_CLASS objectType, - CK_ATTRIBUTE *ptemplate, CK_ULONG *plen, - CK_OBJECT_HANDLE *targetID) + CK_OBJECT_CLASS objectType, + CK_ATTRIBUTE *ptemplate, CK_ULONG *plen, + CK_OBJECT_HANDLE *targetID) { PRBool done; /* should we repeat the loop? */ CK_OBJECT_HANDLE id; CK_RV crv = CKR_OK; do { - crv = sftkdb_checkConflicts(db, objectType, ptemplate, - *plen, CK_INVALID_HANDLE); - if (crv != CKR_ATTRIBUTE_VALUE_INVALID) { - break; - } - crv = sftkdb_resolveConflicts(arena, objectType, ptemplate, plen); + crv = sftkdb_checkConflicts(db, objectType, ptemplate, + *plen, CK_INVALID_HANDLE); + if (crv != CKR_ATTRIBUTE_VALUE_INVALID) { + break; + } + crv = sftkdb_resolveConflicts(arena, objectType, ptemplate, plen); } while (crv == CKR_OK); if (crv != CKR_OK) { - return SFTKDB_DO_NOTHING; + return SFTKDB_DO_NOTHING; } do { - done = PR_TRUE; - crv = sftkdb_lookupObject(db, objectType, &id, ptemplate, *plen); - if (crv != CKR_OK) { - return SFTKDB_DO_NOTHING; - } - - /* This object already exists, merge it, don't update */ - if (id != CK_INVALID_HANDLE) { - CK_ATTRIBUTE *attr = NULL; - /* special post processing for attributes */ - switch (objectType) { - case CKO_CERTIFICATE: - case CKO_PUBLIC_KEY: - case CKO_PRIVATE_KEY: - /* update target's CKA_ID and labels if they don't already - * exist */ - *targetID = id; - return sftkdb_handleIDAndName(arena, db, id, ptemplate, plen); - case CKO_NSS_TRUST: - /* if we have conflicting trust object types, - * we need to reconcile them */ - *targetID = id; - return sftkdb_reconcileTrust(arena, db, id, ptemplate, plen); - case CKO_SECRET_KEY: - /* secret keys in the old database are all sdr keys, - * unfortunately they all appear to have the same CKA_ID, - * even though they are truly different keys, so we always - * want to update these keys, but we need to - * give them a new CKA_ID */ - /* NOTE: this changes ptemplate */ - attr = sftkdb_getAttributeFromTemplate(CKA_ID,ptemplate,*plen); - crv = attr ? sftkdb_incrementCKAID(arena, attr) - : CKR_HOST_MEMORY; - /* in the extremely rare event that we needed memory and - * couldn't get it, just drop the key */ - if (crv != CKR_OK) { - return SFTKDB_DO_NOTHING; - } - done = PR_FALSE; /* repeat this find loop */ - break; - default: - /* for all other objects, if we found the equivalent object, - * don't update it */ - return SFTKDB_DO_NOTHING; - } - } + done = PR_TRUE; + crv = sftkdb_lookupObject(db, objectType, &id, ptemplate, *plen); + if (crv != CKR_OK) { + return SFTKDB_DO_NOTHING; + } + + /* This object already exists, merge it, don't update */ + if (id != CK_INVALID_HANDLE) { + CK_ATTRIBUTE *attr = NULL; + /* special post processing for attributes */ + switch (objectType) { + case CKO_CERTIFICATE: + case CKO_PUBLIC_KEY: + case CKO_PRIVATE_KEY: + /* update target's CKA_ID and labels if they don't already + * exist */ + *targetID = id; + return sftkdb_handleIDAndName(arena, db, id, ptemplate, plen); + case CKO_NSS_TRUST: + /* if we have conflicting trust object types, + * we need to reconcile them */ + *targetID = id; + return sftkdb_reconcileTrust(arena, db, id, ptemplate, plen); + case CKO_SECRET_KEY: + /* secret keys in the old database are all sdr keys, + * unfortunately they all appear to have the same CKA_ID, + * even though they are truly different keys, so we always + * want to update these keys, but we need to + * give them a new CKA_ID */ + /* NOTE: this changes ptemplate */ + attr = sftkdb_getAttributeFromTemplate(CKA_ID, ptemplate, *plen); + crv = attr ? sftkdb_incrementCKAID(arena, attr) + : CKR_HOST_MEMORY; + /* in the extremely rare event that we needed memory and + * couldn't get it, just drop the key */ + if (crv != CKR_OK) { + return SFTKDB_DO_NOTHING; + } + done = PR_FALSE; /* repeat this find loop */ + break; + default: + /* for all other objects, if we found the equivalent object, + * don't update it */ + return SFTKDB_DO_NOTHING; + } + } } while (!done); /* this object doesn't exist, update it */ return SFTKDB_ADD_OBJECT; } - #define MAX_ATTRIBUTES 500 static CK_RV -sftkdb_mergeObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE id, - SECItem *key) +sftkdb_mergeObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE id, + SECItem *key) { CK_ATTRIBUTE template[MAX_ATTRIBUTES]; CK_ATTRIBUTE *ptemplate; @@ -2169,76 +2153,75 @@ sftkdb_mergeObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE id, PLArenaPool *arena = NULL; arena = PORT_NewArena(256); - if (arena == NULL) { - return CKR_HOST_MEMORY; + if (arena == NULL) { + return CKR_HOST_MEMORY; } ptemplate = &template[0]; id &= SFTK_OBJ_ID_MASK; crv = sftkdb_GetObjectTemplate(source, id, ptemplate, &max_attributes); if (crv == CKR_BUFFER_TOO_SMALL) { - ptemplate = PORT_ArenaNewArray(arena, CK_ATTRIBUTE, max_attributes); - if (ptemplate == NULL) { - crv = CKR_HOST_MEMORY; - } else { - crv = sftkdb_GetObjectTemplate(source, id, - ptemplate, &max_attributes); - } + ptemplate = PORT_ArenaNewArray(arena, CK_ATTRIBUTE, max_attributes); + if (ptemplate == NULL) { + crv = CKR_HOST_MEMORY; + } else { + crv = sftkdb_GetObjectTemplate(source, id, + ptemplate, &max_attributes); + } } if (crv != CKR_OK) { - goto loser; + goto loser; } - for (i=0; i < max_attributes; i++) { - ptemplate[i].pValue = PORT_ArenaAlloc(arena,ptemplate[i].ulValueLen); - if (ptemplate[i].pValue == NULL) { - crv = CKR_HOST_MEMORY; - goto loser; - } + for (i = 0; i < max_attributes; i++) { + ptemplate[i].pValue = PORT_ArenaAlloc(arena, ptemplate[i].ulValueLen); + if (ptemplate[i].pValue == NULL) { + crv = CKR_HOST_MEMORY; + goto loser; + } } - crv = (*source->sdb_GetAttributeValue)(source, id, - ptemplate, max_attributes); + crv = (*source->sdb_GetAttributeValue)(source, id, + ptemplate, max_attributes); if (crv != CKR_OK) { - goto loser; + goto loser; } objectType = sftkdb_getULongFromTemplate(CKA_CLASS, ptemplate, - max_attributes); + max_attributes); /* - * Update Object updates the object template if necessary then returns - * whether or not we need to actually write the object out to our target + * Update Object updates the object template if necessary then returns + * whether or not we need to actually write the object out to our target * database. */ if (!handle->updateID) { - crv = sftkdb_CreateObject(arena, handle, target, &id, - ptemplate, max_attributes); + crv = sftkdb_CreateObject(arena, handle, target, &id, + ptemplate, max_attributes); } else { - sftkdbUpdateStatus update_status; - update_status = sftkdb_updateObjectTemplate(arena, target, - objectType, ptemplate, &max_attributes, &id); - switch (update_status) { - case SFTKDB_ADD_OBJECT: - crv = sftkdb_CreateObject(arena, handle, target, &id, - ptemplate, max_attributes); - break; - case SFTKDB_MODIFY_OBJECT: - crv = sftkdb_setAttributeValue(arena, handle, target, - id, ptemplate, max_attributes); - break; - case SFTKDB_DO_NOTHING: - case SFTKDB_DROP_ATTRIBUTE: - break; - } - } + sftkdbUpdateStatus update_status; + update_status = sftkdb_updateObjectTemplate(arena, target, + objectType, ptemplate, &max_attributes, &id); + switch (update_status) { + case SFTKDB_ADD_OBJECT: + crv = sftkdb_CreateObject(arena, handle, target, &id, + ptemplate, max_attributes); + break; + case SFTKDB_MODIFY_OBJECT: + crv = sftkdb_setAttributeValue(arena, handle, target, + id, ptemplate, max_attributes); + break; + case SFTKDB_DO_NOTHING: + case SFTKDB_DROP_ATTRIBUTE: + break; + } + } loser: if (arena) { - PORT_FreeArena(arena,PR_TRUE); + PORT_FreeArena(arena, PR_TRUE); } return crv; } - #define MAX_IDS 10 /* @@ -2256,10 +2239,10 @@ sftkdb_Update(SFTKDBHandle *handle, SECItem *key) unsigned int i; if (handle == NULL) { - return CKR_OK; + return CKR_OK; } if (handle->update == NULL) { - return CKR_OK; + return CKR_OK; } /* @@ -2268,38 +2251,39 @@ sftkdb_Update(SFTKDBHandle *handle, SECItem *key) */ crv = (*handle->db->sdb_Begin)(handle->db); if (crv != CKR_OK) { - goto loser; + goto loser; } inTransaction = PR_TRUE; - + /* some one else has already updated this db */ - if (sftkdb_hasUpdate(sftkdb_TypeString(handle), - handle->db, handle->updateID)) { - crv = CKR_OK; - goto done; + if (sftkdb_hasUpdate(sftkdb_TypeString(handle), + handle->db, handle->updateID)) { + crv = CKR_OK; + goto done; } updatePasswordKey = sftkdb_GetUpdatePasswordKey(handle); if (updatePasswordKey) { - /* pass the source DB key to the legacy code, - * so it can decrypt things */ - handle->oldKey = updatePasswordKey; + /* pass the source DB key to the legacy code, + * so it can decrypt things */ + handle->oldKey = updatePasswordKey; } - + /* find all the objects */ crv = sftkdb_FindObjectsInit(handle, NULL, 0, &find); if (crv != CKR_OK) { - goto loser; + goto loser; } while ((crv == CKR_OK) && (idCount == MAX_IDS)) { - crv = sftkdb_FindObjects(handle, find, ids, MAX_IDS, &idCount); - for (i=0; (crv == CKR_OK) && (i < idCount); i++) { - crv = sftkdb_mergeObject(handle, ids[i], key); - } + crv = sftkdb_FindObjects(handle, find, ids, MAX_IDS, &idCount); + for (i = 0; (crv == CKR_OK) && (i < idCount); i++) { + crv = sftkdb_mergeObject(handle, ids[i], key); + } } crv2 = sftkdb_FindObjectsFinal(handle, find); - if (crv == CKR_OK) crv = crv2; + if (crv == CKR_OK) + crv = crv2; loser: /* no longer need the old key value */ @@ -2307,62 +2291,61 @@ loser: /* update the password - even if we didn't update objects */ if (handle->type == SFTK_KEYDB_TYPE) { - SECItem item1, item2; - unsigned char data1[SDB_MAX_META_DATA_LEN]; - unsigned char data2[SDB_MAX_META_DATA_LEN]; - - item1.data = data1; - item1.len = sizeof(data1); - item2.data = data2; - item2.len = sizeof(data2); - - /* if the target db already has a password, skip this. */ - crv = (*handle->db->sdb_GetMetaData)(handle->db, "password", - &item1, &item2); - if (crv == CKR_OK) { - goto done; - } - - - /* nope, update it from the source */ - crv = (*handle->update->sdb_GetMetaData)(handle->update, "password", - &item1, &item2); - if (crv != CKR_OK) { - goto done; - } - crv = (*handle->db->sdb_PutMetaData)(handle->db, "password", &item1, - &item2); - if (crv != CKR_OK) { - goto done; - } + SECItem item1, item2; + unsigned char data1[SDB_MAX_META_DATA_LEN]; + unsigned char data2[SDB_MAX_META_DATA_LEN]; + + item1.data = data1; + item1.len = sizeof(data1); + item2.data = data2; + item2.len = sizeof(data2); + + /* if the target db already has a password, skip this. */ + crv = (*handle->db->sdb_GetMetaData)(handle->db, "password", + &item1, &item2); + if (crv == CKR_OK) { + goto done; + } + + /* nope, update it from the source */ + crv = (*handle->update->sdb_GetMetaData)(handle->update, "password", + &item1, &item2); + if (crv != CKR_OK) { + goto done; + } + crv = (*handle->db->sdb_PutMetaData)(handle->db, "password", &item1, + &item2); + if (crv != CKR_OK) { + goto done; + } } done: /* finally mark this up to date db up to date */ /* some one else has already updated this db */ if (crv == CKR_OK) { - crv = sftkdb_putUpdate(sftkdb_TypeString(handle), - handle->db, handle->updateID); + crv = sftkdb_putUpdate(sftkdb_TypeString(handle), + handle->db, handle->updateID); } if (inTransaction) { - if (crv == CKR_OK) { - crv = (*handle->db->sdb_Commit)(handle->db); - } else { - (*handle->db->sdb_Abort)(handle->db); - } + if (crv == CKR_OK) { + crv = (*handle->db->sdb_Commit)(handle->db); + } else { + (*handle->db->sdb_Abort)(handle->db); + } } if (handle->update) { - (*handle->update->sdb_Close)(handle->update); - handle->update = NULL; + (*handle->update->sdb_Close)(handle->update); + handle->update = NULL; } if (handle->updateID) { - PORT_Free(handle->updateID); - handle->updateID = NULL; + PORT_Free(handle->updateID); + handle->updateID = NULL; } sftkdb_FreeUpdatePasswordKey(handle); if (updatePasswordKey) { - SECITEM_ZfreeItem(updatePasswordKey, PR_TRUE); + SECITEM_ZfreeItem(updatePasswordKey, PR_TRUE); } handle->updateDBIsInit = PR_FALSE; return crv; @@ -2370,7 +2353,7 @@ done: /****************************************************************** * DB handle managing functions. - * + * * These functions are called by softoken to initialize, acquire, * and release database handles. */ @@ -2387,18 +2370,18 @@ sftk_freeDB(SFTKDBHandle *handle) { PRInt32 ref; - if (!handle) return; + if (!handle) + return; ref = PR_ATOMIC_DECREMENT(&handle->ref); if (ref == 0) { - sftkdb_CloseDB(handle); + sftkdb_CloseDB(handle); } return; } - /* - * acquire a database handle for a certificate db - * (database for public objects) + * acquire a database handle for a certificate db + * (database for public objects) */ SFTKDBHandle * sftk_getCertDB(SFTKSlot *slot) @@ -2415,7 +2398,7 @@ sftk_getCertDB(SFTKSlot *slot) } /* - * acquire a database handle for a key database + * acquire a database handle for a key database * (database for private objects) */ SFTKDBHandle * @@ -2456,24 +2439,24 @@ sftk_getDBForTokenObject(SFTKSlot *slot, CK_OBJECT_HANDLE objectID) static SFTKDBHandle * sftk_NewDBHandle(SDB *sdb, int type) { - SFTKDBHandle *handle = PORT_New(SFTKDBHandle); - handle->ref = 1; - handle->db = sdb; - handle->update = NULL; - handle->peerDB = NULL; - handle->newKey = NULL; - handle->oldKey = NULL; - handle->updatePasswordKey = NULL; - handle->updateID = NULL; - handle->type = type; - handle->passwordKey.data = NULL; - handle->passwordKey.len = 0; - handle->passwordLock = NULL; - if (type == SFTK_KEYDB_TYPE) { - handle->passwordLock = PZ_NewLock(nssILockAttribute); - } - sdb->app_private = handle; - return handle; + SFTKDBHandle *handle = PORT_New(SFTKDBHandle); + handle->ref = 1; + handle->db = sdb; + handle->update = NULL; + handle->peerDB = NULL; + handle->newKey = NULL; + handle->oldKey = NULL; + handle->updatePasswordKey = NULL; + handle->updateID = NULL; + handle->type = type; + handle->passwordKey.data = NULL; + handle->passwordKey.len = 0; + handle->passwordLock = NULL; + if (type == SFTK_KEYDB_TYPE) { + handle->passwordLock = PZ_NewLock(nssILockAttribute); + } + sdb->app_private = handle; + return handle; } /* @@ -2487,12 +2470,12 @@ sftkdb_ResetKeyDB(SFTKDBHandle *handle) /* only rest the key db */ if (handle->type != SFTK_KEYDB_TYPE) { - return SECFailure; + return SECFailure; } crv = sftkdb_ResetDB(handle); if (crv != CKR_OK) { - /* set error */ - return SECFailure; + /* set error */ + return SECFailure; } return SECSuccess; } @@ -2504,49 +2487,49 @@ sftk_oldVersionExists(const char *dir, int version) PRStatus exists = PR_FAILURE; char *file = NULL; - for (i=version; i > 1 ; i--) { - file = PR_smprintf("%s%d.db",dir,i); - if (file == NULL) { - continue; - } - exists = PR_Access(file, PR_ACCESS_EXISTS); - PR_smprintf_free(file); - if (exists == PR_SUCCESS) { - return PR_TRUE; - } + for (i = version; i > 1; i--) { + file = PR_smprintf("%s%d.db", dir, i); + if (file == NULL) { + continue; + } + exists = PR_Access(file, PR_ACCESS_EXISTS); + PR_smprintf_free(file); + if (exists == PR_SUCCESS) { + return PR_TRUE; + } } return PR_FALSE; } static PRBool -sftk_hasLegacyDB(const char *confdir, const char *certPrefix, - const char *keyPrefix, int certVersion, int keyVersion) +sftk_hasLegacyDB(const char *confdir, const char *certPrefix, + const char *keyPrefix, int certVersion, int keyVersion) { char *dir; PRBool exists; if (certPrefix == NULL) { - certPrefix = ""; + certPrefix = ""; } if (keyPrefix == NULL) { - keyPrefix = ""; + keyPrefix = ""; } - dir= PR_smprintf("%s/%scert", confdir, certPrefix); + dir = PR_smprintf("%s/%scert", confdir, certPrefix); if (dir == NULL) { - return PR_FALSE; + return PR_FALSE; } exists = sftk_oldVersionExists(dir, certVersion); PR_smprintf_free(dir); if (exists) { - return PR_TRUE; + return PR_TRUE; } - dir= PR_smprintf("%s/%skey", confdir, keyPrefix); + dir = PR_smprintf("%s/%skey", confdir, keyPrefix); if (dir == NULL) { - return PR_FALSE; + return PR_FALSE; } exists = sftk_oldVersionExists(dir, keyVersion); @@ -2561,13 +2544,13 @@ sftk_hasLegacyDB(const char *confdir, const char *certPrefix, * calls the appropriate low level function to open the database. * It also figures out whether or not to setup up automatic update. */ -CK_RV +CK_RV sftk_DBInit(const char *configdir, const char *certPrefix, - const char *keyPrefix, const char *updatedir, - const char *updCertPrefix, const char *updKeyPrefix, - const char *updateID, PRBool readOnly, PRBool noCertDB, - PRBool noKeyDB, PRBool forceOpen, PRBool isFIPS, - SFTKDBHandle **certDB, SFTKDBHandle **keyDB) + const char *keyPrefix, const char *updatedir, + const char *updCertPrefix, const char *updKeyPrefix, + const char *updateID, PRBool readOnly, PRBool noCertDB, + PRBool noKeyDB, PRBool forceOpen, PRBool isFIPS, + SFTKDBHandle **certDB, SFTKDBHandle **keyDB) { const char *confdir; NSSDBType dbType = NSS_DB_TYPE_NONE; @@ -2579,14 +2562,17 @@ sftk_DBInit(const char *configdir, const char *certPrefix, PRBool needUpdate = PR_FALSE; if (!readOnly) { - flags = SDB_CREATE; + flags = SDB_CREATE; + } + if (isFIPS) { + flags |= SDB_FIPS; } *certDB = NULL; *keyDB = NULL; if (noKeyDB && noCertDB) { - return CKR_OK; + return CKR_OK; } confdir = _NSSUTIL_EvaluateConfigDir(configdir, &dbType, &appName); @@ -2594,88 +2580,87 @@ sftk_DBInit(const char *configdir, const char *certPrefix, * now initialize the appropriate database */ switch (dbType) { - case NSS_DB_TYPE_LEGACY: - crv = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags, - isFIPS, noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB); - break; - case NSS_DB_TYPE_MULTIACCESS: - crv = sftkdbCall_open(configdir, certPrefix, keyPrefix, 8, 3, flags, - isFIPS, noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB); - break; - case NSS_DB_TYPE_SQL: - case NSS_DB_TYPE_EXTERN: /* SHOULD open a loadable db */ - crv = s_open(confdir, certPrefix, keyPrefix, 9, 4, flags, - noCertDB? NULL : &certSDB, noKeyDB ? NULL : &keySDB, &newInit); - - /* - * if we failed to open the DB's read only, use the old ones if - * the exists. - */ - if (crv != CKR_OK) { - if ((flags == SDB_RDONLY) && - sftk_hasLegacyDB(confdir, certPrefix, keyPrefix, 8, 3)) { - /* we have legacy databases, if we failed to open the new format - * DB's read only, just use the legacy ones */ - crv = sftkdbCall_open(confdir, certPrefix, - keyPrefix, 8, 3, flags, isFIPS, - noCertDB? NULL : &certSDB, noKeyDB ? NULL : &keySDB); - } - /* Handle the database merge case. - * - * For the merge case, we need help from the application. Only - * the application knows where the old database is, and what unique - * identifier it has associated with it. - * - * If the client supplies these values, we use them to determine - * if we need to update. - */ - } else if ( - /* both update params have been supplied */ - updatedir && *updatedir && updateID && *updateID - /* old dbs exist? */ - && sftk_hasLegacyDB(updatedir, updCertPrefix, updKeyPrefix, 8, 3) - /* and they have not yet been updated? */ - && ((noKeyDB || !sftkdb_hasUpdate("key", keySDB, updateID)) - || (noCertDB || !sftkdb_hasUpdate("cert", certSDB, updateID)))) { - /* we need to update */ - confdir = updatedir; - certPrefix = updCertPrefix; - keyPrefix = updKeyPrefix; - needUpdate = PR_TRUE; - } else if (newInit) { - /* if the new format DB was also a newly created DB, and we - * succeeded, then need to update that new database with data - * from the existing legacy DB */ - if (sftk_hasLegacyDB(confdir, certPrefix, keyPrefix, 8, 3)) { - needUpdate = PR_TRUE; - } - } - break; - default: - crv = CKR_GENERAL_ERROR; /* can't happen, EvaluationConfigDir MUST - * return one of the types we already - * specified. */ + case NSS_DB_TYPE_LEGACY: + crv = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags, + noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB); + break; + case NSS_DB_TYPE_MULTIACCESS: + crv = sftkdbCall_open(configdir, certPrefix, keyPrefix, 8, 3, flags, + noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB); + break; + case NSS_DB_TYPE_SQL: + case NSS_DB_TYPE_EXTERN: /* SHOULD open a loadable db */ + crv = s_open(confdir, certPrefix, keyPrefix, 9, 4, flags, + noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB, &newInit); + + /* + * if we failed to open the DB's read only, use the old ones if + * the exists. + */ + if (crv != CKR_OK) { + if (((flags & SDB_RDONLY) == SDB_RDONLY) && + sftk_hasLegacyDB(confdir, certPrefix, keyPrefix, 8, 3)) { + /* we have legacy databases, if we failed to open the new format + * DB's read only, just use the legacy ones */ + crv = sftkdbCall_open(confdir, certPrefix, + keyPrefix, 8, 3, flags, + noCertDB ? NULL : &certSDB, noKeyDB ? NULL : &keySDB); + } + /* Handle the database merge case. + * + * For the merge case, we need help from the application. Only + * the application knows where the old database is, and what unique + * identifier it has associated with it. + * + * If the client supplies these values, we use them to determine + * if we need to update. + */ + } else if ( + /* both update params have been supplied */ + updatedir && *updatedir && updateID && *updateID + /* old dbs exist? */ + && sftk_hasLegacyDB(updatedir, updCertPrefix, updKeyPrefix, 8, 3) + /* and they have not yet been updated? */ + && ((noKeyDB || !sftkdb_hasUpdate("key", keySDB, updateID)) || (noCertDB || !sftkdb_hasUpdate("cert", certSDB, updateID)))) { + /* we need to update */ + confdir = updatedir; + certPrefix = updCertPrefix; + keyPrefix = updKeyPrefix; + needUpdate = PR_TRUE; + } else if (newInit) { + /* if the new format DB was also a newly created DB, and we + * succeeded, then need to update that new database with data + * from the existing legacy DB */ + if (sftk_hasLegacyDB(confdir, certPrefix, keyPrefix, 8, 3)) { + needUpdate = PR_TRUE; + } + } + break; + default: + crv = CKR_GENERAL_ERROR; /* can't happen, EvaluationConfigDir MUST + * return one of the types we already + * specified. */ } if (crv != CKR_OK) { - goto done; + goto done; } if (!noCertDB) { - *certDB = sftk_NewDBHandle(certSDB, SFTK_CERTDB_TYPE); + *certDB = sftk_NewDBHandle(certSDB, SFTK_CERTDB_TYPE); } else { - *certDB = NULL; + *certDB = NULL; } if (!noKeyDB) { - *keyDB = sftk_NewDBHandle(keySDB, SFTK_KEYDB_TYPE); + *keyDB = sftk_NewDBHandle(keySDB, SFTK_KEYDB_TYPE); } else { - *keyDB = NULL; + *keyDB = NULL; } /* link them together */ if (*certDB) { - (*certDB)->peerDB = *keyDB; + (*certDB)->peerDB = *keyDB; } if (*keyDB) { - (*keyDB)->peerDB = *certDB; + (*keyDB)->peerDB = *certDB; } /* @@ -2683,51 +2668,49 @@ sftk_DBInit(const char *configdir, const char *certPrefix, * mark the handle as needing update. */ if (needUpdate) { - SDB *updateCert = NULL; - SDB *updateKey = NULL; - CK_RV crv2; - - crv2 = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags, - isFIPS, noCertDB ? NULL : &updateCert, - noKeyDB ? NULL : &updateKey); - if (crv2 == CKR_OK) { - if (*certDB) { - (*certDB)->update = updateCert; - (*certDB)->updateID = updateID && *updateID - ? PORT_Strdup(updateID) : NULL; - updateCert->app_private = (*certDB); - } - if (*keyDB) { - PRBool tokenRemoved = PR_FALSE; - (*keyDB)->update = updateKey; - (*keyDB)->updateID = updateID && *updateID ? - PORT_Strdup(updateID) : NULL; - updateKey->app_private = (*keyDB); - (*keyDB)->updateDBIsInit = PR_TRUE; - (*keyDB)->updateDBIsInit = - (sftkdb_HasPasswordSet(*keyDB) == SECSuccess) ? - PR_TRUE : PR_FALSE; - /* if the password on the key db is NULL, kick off our update - * chain of events */ - sftkdb_CheckPassword((*keyDB), "", &tokenRemoved); - } else { - /* we don't have a key DB, update the certificate DB now */ - sftkdb_Update(*certDB, NULL); - } - } + SDB *updateCert = NULL; + SDB *updateKey = NULL; + CK_RV crv2; + + crv2 = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags, + noCertDB ? NULL : &updateCert, + noKeyDB ? NULL : &updateKey); + if (crv2 == CKR_OK) { + if (*certDB) { + (*certDB)->update = updateCert; + (*certDB)->updateID = updateID && *updateID + ? PORT_Strdup(updateID) + : NULL; + updateCert->app_private = (*certDB); + } + if (*keyDB) { + PRBool tokenRemoved = PR_FALSE; + (*keyDB)->update = updateKey; + (*keyDB)->updateID = updateID && *updateID ? PORT_Strdup(updateID) : NULL; + updateKey->app_private = (*keyDB); + (*keyDB)->updateDBIsInit = PR_TRUE; + (*keyDB)->updateDBIsInit = + (sftkdb_HasPasswordSet(*keyDB) == SECSuccess) ? PR_TRUE : PR_FALSE; + /* if the password on the key db is NULL, kick off our update + * chain of events */ + sftkdb_CheckPassword((*keyDB), "", &tokenRemoved); + } else { + /* we don't have a key DB, update the certificate DB now */ + sftkdb_Update(*certDB, NULL); + } + } } done: if (appName) { - PORT_Free(appName); + PORT_Free(appName); } - return forceOpen ? CKR_OK : crv; + return forceOpen ? CKR_OK : crv; } -CK_RV +CK_RV sftkdb_Shutdown(void) { - s_shutdown(); - sftkdbCall_Shutdown(); - return CKR_OK; + s_shutdown(); + sftkdbCall_Shutdown(); + return CKR_OK; } - diff --git a/nss/lib/softoken/sftkdb.h b/nss/lib/softoken/sftkdb.h index beff9da..a47c896 100644 --- a/nss/lib/softoken/sftkdb.h +++ b/nss/lib/softoken/sftkdb.h @@ -7,16 +7,16 @@ #include "pkcs11t.h" /* raw database stuff */ -CK_RV sftkdb_write(SFTKDBHandle *handle, SFTKObject *,CK_OBJECT_HANDLE *); +CK_RV sftkdb_write(SFTKDBHandle *handle, SFTKObject *, CK_OBJECT_HANDLE *); CK_RV sftkdb_FindObjectsInit(SFTKDBHandle *sdb, const CK_ATTRIBUTE *template, - CK_ULONG count, SDBFind **find); -CK_RV sftkdb_FindObjects(SFTKDBHandle *sdb, SDBFind *find, - CK_OBJECT_HANDLE *ids, int arraySize, CK_ULONG *count); + CK_ULONG count, SDBFind **find); +CK_RV sftkdb_FindObjects(SFTKDBHandle *sdb, SDBFind *find, + CK_OBJECT_HANDLE *ids, int arraySize, CK_ULONG *count); CK_RV sftkdb_FindObjectsFinal(SFTKDBHandle *sdb, SDBFind *find); CK_RV sftkdb_GetAttributeValue(SFTKDBHandle *handle, - CK_OBJECT_HANDLE object_id, CK_ATTRIBUTE *template, CK_ULONG count); -CK_RV sftkdb_SetAttributeValue(SFTKDBHandle *handle, SFTKObject *object, - const CK_ATTRIBUTE *template, CK_ULONG count); + CK_OBJECT_HANDLE object_id, CK_ATTRIBUTE *template, CK_ULONG count); +CK_RV sftkdb_SetAttributeValue(SFTKDBHandle *handle, SFTKObject *object, + const CK_ATTRIBUTE *template, CK_ULONG count); CK_RV sftkdb_DestroyObject(SFTKDBHandle *handle, CK_OBJECT_HANDLE object_id); CK_RV sftkdb_closeDB(SFTKDBHandle *handle); @@ -24,13 +24,13 @@ CK_RV sftkdb_closeDB(SFTKDBHandle *handle); SECStatus sftkdb_PWIsInitialized(SFTKDBHandle *keydb); SECStatus sftkdb_CheckPassword(SFTKDBHandle *keydb, const char *pw, - PRBool *tokenRemoved); + PRBool *tokenRemoved); SECStatus sftkdb_PWCached(SFTKDBHandle *keydb); SECStatus sftkdb_HasPasswordSet(SFTKDBHandle *keydb); SECStatus sftkdb_ResetKeyDB(SFTKDBHandle *keydb); -SECStatus sftkdb_ChangePassword(SFTKDBHandle *keydb, - char *oldPin, char *newPin, - PRBool *tokenRemoved); +SECStatus sftkdb_ChangePassword(SFTKDBHandle *keydb, + char *oldPin, char *newPin, + PRBool *tokenRemoved); SECStatus sftkdb_ClearPassword(SFTKDBHandle *keydb); PRBool sftkdb_InUpdateMerge(SFTKDBHandle *keydb); PRBool sftkdb_NeedUpdateDBPassword(SFTKDBHandle *keydb); @@ -57,15 +57,15 @@ void sftkdb_FreeUpdatePasswordKey(SFTKDBHandle *keydb); * be opened. */ CK_RV sftk_DBInit(const char *configdir, const char *certPrefix, - const char *keyPrefix, const char *updatedir, - const char *updCertPrefix, const char *updKeyPrefix, - const char *updateID, PRBool readOnly, PRBool noCertDB, - PRBool noKeyDB, PRBool forceOpen, PRBool isFIPS, - SFTKDBHandle **certDB, SFTKDBHandle **keyDB); + const char *keyPrefix, const char *updatedir, + const char *updCertPrefix, const char *updKeyPrefix, + const char *updateID, PRBool readOnly, PRBool noCertDB, + PRBool noKeyDB, PRBool forceOpen, PRBool isFIPS, + SFTKDBHandle **certDB, SFTKDBHandle **keyDB); CK_RV sftkdb_Shutdown(void); SFTKDBHandle *sftk_getCertDB(SFTKSlot *slot); SFTKDBHandle *sftk_getKeyDB(SFTKSlot *slot); -SFTKDBHandle *sftk_getDBForTokenObject(SFTKSlot *slot, +SFTKDBHandle *sftk_getDBForTokenObject(SFTKSlot *slot, CK_OBJECT_HANDLE objectID); void sftk_freeDB(SFTKDBHandle *certHandle); diff --git a/nss/lib/softoken/sftkdbt.h b/nss/lib/softoken/sftkdbt.h index 684393c..77beb84 100644 --- a/nss/lib/softoken/sftkdbt.h +++ b/nss/lib/softoken/sftkdbt.h @@ -6,7 +6,7 @@ #define SFTKDBT_H 1 typedef struct SFTKDBHandleStr SFTKDBHandle; -#define SDB_MAX_META_DATA_LEN 256 +#define SDB_MAX_META_DATA_LEN 256 #define SDB_ULONG_SIZE 4 #endif diff --git a/nss/lib/softoken/sftkdbti.h b/nss/lib/softoken/sftkdbti.h index eb777e4..4942e1b 100644 --- a/nss/lib/softoken/sftkdbti.h +++ b/nss/lib/softoken/sftkdbti.h @@ -9,17 +9,17 @@ * private defines */ struct SFTKDBHandleStr { - SDB *db; + SDB *db; PRInt32 ref; - CK_OBJECT_HANDLE type; + CK_OBJECT_HANDLE type; SECItem passwordKey; SECItem *newKey; SECItem *oldKey; SECItem *updatePasswordKey; PZLock *passwordLock; SFTKDBHandle *peerDB; - SDB *update; - char *updateID; + SDB *update; + char *updateID; PRBool updateDBIsInit; }; @@ -34,27 +34,25 @@ struct SFTKDBHandleStr { #define SFTK_MAX_IDS 10 #define SFTK_GET_SDB(handle) \ - ((handle)->update ? (handle)->update : (handle)->db) + ((handle)->update ? (handle)->update : (handle)->db) SECStatus sftkdb_DecryptAttribute(SECItem *passKey, SECItem *cipherText, - SECItem **plainText); + SECItem **plainText); SECStatus sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey, - SECItem *plainText, SECItem **cipherText); + SECItem *plainText, SECItem **cipherText); SECStatus sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, - CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE_TYPE attrType, - SECItem *plainText, SECItem **sigText); + CK_OBJECT_HANDLE objectID, + CK_ATTRIBUTE_TYPE attrType, + SECItem *plainText, SECItem **sigText); SECStatus sftkdb_VerifyAttribute(SECItem *passKey, - CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE_TYPE attrType, - SECItem *plainText, SECItem *sigText); + CK_OBJECT_HANDLE objectID, + CK_ATTRIBUTE_TYPE attrType, + SECItem *plainText, SECItem *sigText); void sftk_ULong2SDBULong(unsigned char *data, CK_ULONG value); CK_RV sftkdb_Update(SFTKDBHandle *handle, SECItem *key); -CK_RV sftkdb_PutAttributeSignature(SFTKDBHandle *handle, - SDB *keyTarget, CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE_TYPE type, SECItem *signText); - - +CK_RV sftkdb_PutAttributeSignature(SFTKDBHandle *handle, + SDB *keyTarget, CK_OBJECT_HANDLE objectID, + CK_ATTRIBUTE_TYPE type, SECItem *signText); #endif diff --git a/nss/lib/softoken/sftkhmac.c b/nss/lib/softoken/sftkhmac.c index f4e859b..be6344c 100644 --- a/nss/lib/softoken/sftkhmac.c +++ b/nss/lib/softoken/sftkhmac.c @@ -15,20 +15,20 @@ static HASH_HashType MACMechanismToHash(CK_MECHANISM_TYPE mech) { switch (mech) { - case CKM_MD5_HMAC: - case CKM_SSL3_MD5_MAC: - return HASH_AlgMD5; - case CKM_SHA_1_HMAC: - case CKM_SSL3_SHA1_MAC: - return HASH_AlgSHA1; - case CKM_SHA224_HMAC: - return HASH_AlgSHA224; - case CKM_SHA256_HMAC: - return HASH_AlgSHA256; - case CKM_SHA384_HMAC: - return HASH_AlgSHA384; - case CKM_SHA512_HMAC: - return HASH_AlgSHA512; + case CKM_MD5_HMAC: + case CKM_SSL3_MD5_MAC: + return HASH_AlgMD5; + case CKM_SHA_1_HMAC: + case CKM_SSL3_SHA1_MAC: + return HASH_AlgSHA1; + case CKM_SHA224_HMAC: + return HASH_AlgSHA224; + case CKM_SHA256_HMAC: + return HASH_AlgSHA256; + case CKM_SHA384_HMAC: + return HASH_AlgSHA384; + case CKM_SHA512_HMAC: + return HASH_AlgSHA512; } return HASH_AlgNULL; } @@ -37,7 +37,7 @@ static sftk_MACConstantTimeCtx * SetupMAC(CK_MECHANISM_PTR mech, SFTKObject *key) { CK_NSS_MAC_CONSTANT_TIME_PARAMS *params = - (CK_NSS_MAC_CONSTANT_TIME_PARAMS *) mech->pParameter; + (CK_NSS_MAC_CONSTANT_TIME_PARAMS *)mech->pParameter; sftk_MACConstantTimeCtx *ctx; HASH_HashType alg; SFTKAttribute *keyval; @@ -45,29 +45,29 @@ SetupMAC(CK_MECHANISM_PTR mech, SFTKObject *key) unsigned int secretLength; if (mech->ulParameterLen != sizeof(CK_NSS_MAC_CONSTANT_TIME_PARAMS)) { - return NULL; + return NULL; } alg = MACMechanismToHash(params->macAlg); if (alg == HASH_AlgNULL) { - return NULL; + return NULL; } - keyval = sftk_FindAttribute(key,CKA_VALUE); + keyval = sftk_FindAttribute(key, CKA_VALUE); if (keyval == NULL) { - return NULL; + return NULL; } secretLength = keyval->attrib.ulValueLen; if (secretLength > sizeof(secret)) { - sftk_FreeAttribute(keyval); - return NULL; + sftk_FreeAttribute(keyval); + return NULL; } memcpy(secret, keyval->attrib.pValue, secretLength); sftk_FreeAttribute(keyval); ctx = PORT_Alloc(sizeof(sftk_MACConstantTimeCtx)); if (!ctx) { - return NULL; + return NULL; } memcpy(ctx->secret, secret, secretLength); @@ -82,15 +82,15 @@ sftk_MACConstantTimeCtx * sftk_HMACConstantTime_New(CK_MECHANISM_PTR mech, SFTKObject *key) { CK_NSS_MAC_CONSTANT_TIME_PARAMS *params = - (CK_NSS_MAC_CONSTANT_TIME_PARAMS *) mech->pParameter; + (CK_NSS_MAC_CONSTANT_TIME_PARAMS *)mech->pParameter; sftk_MACConstantTimeCtx *ctx; if (params->ulHeaderLen > sizeof(ctx->header)) { - return NULL; + return NULL; } ctx = SetupMAC(mech, key); if (!ctx) { - return NULL; + return NULL; } ctx->headerLength = params->ulHeaderLen; @@ -102,30 +102,30 @@ sftk_MACConstantTimeCtx * sftk_SSLv3MACConstantTime_New(CK_MECHANISM_PTR mech, SFTKObject *key) { CK_NSS_MAC_CONSTANT_TIME_PARAMS *params = - (CK_NSS_MAC_CONSTANT_TIME_PARAMS *) mech->pParameter; + (CK_NSS_MAC_CONSTANT_TIME_PARAMS *)mech->pParameter; unsigned int padLength = 40, j; sftk_MACConstantTimeCtx *ctx; if (params->macAlg != CKM_SSL3_MD5_MAC && - params->macAlg != CKM_SSL3_SHA1_MAC) { - return NULL; + params->macAlg != CKM_SSL3_SHA1_MAC) { + return NULL; } ctx = SetupMAC(mech, key); if (!ctx) { - return NULL; + return NULL; } if (params->macAlg == CKM_SSL3_MD5_MAC) { - padLength = 48; + padLength = 48; } ctx->headerLength = - ctx->secretLength + - padLength + - params->ulHeaderLen; + ctx->secretLength + + padLength + + params->ulHeaderLen; if (ctx->headerLength > sizeof(ctx->header)) { - goto loser; + goto loser; } j = 0; @@ -145,41 +145,41 @@ loser: void sftk_HMACConstantTime_Update(void *pctx, const void *data, unsigned int len) { - sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *) pctx; + sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *)pctx; PORT_CheckSuccess(HMAC_ConstantTime( - ctx->mac, NULL, sizeof(ctx->mac), - ctx->hash, - ctx->secret, ctx->secretLength, - ctx->header, ctx->headerLength, - data, len, - ctx->totalLength)); + ctx->mac, NULL, sizeof(ctx->mac), + ctx->hash, + ctx->secret, ctx->secretLength, + ctx->header, ctx->headerLength, + data, len, + ctx->totalLength)); } void sftk_SSLv3MACConstantTime_Update(void *pctx, const void *data, unsigned int len) { - sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *) pctx; + sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *)pctx; PORT_CheckSuccess(SSLv3_MAC_ConstantTime( - ctx->mac, NULL, sizeof(ctx->mac), - ctx->hash, - ctx->secret, ctx->secretLength, - ctx->header, ctx->headerLength, - data, len, - ctx->totalLength)); + ctx->mac, NULL, sizeof(ctx->mac), + ctx->hash, + ctx->secret, ctx->secretLength, + ctx->header, ctx->headerLength, + data, len, + ctx->totalLength)); } void sftk_MACConstantTime_EndHash(void *pctx, void *out, unsigned int *outLength, - unsigned int maxLength) + unsigned int maxLength) { - const sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *) pctx; + const sftk_MACConstantTimeCtx *ctx = (sftk_MACConstantTimeCtx *)pctx; unsigned int toCopy = ctx->hash->length; if (toCopy > maxLength) { - toCopy = maxLength; + toCopy = maxLength; } memcpy(out, ctx->mac, toCopy); if (outLength) { - *outLength = toCopy; + *outLength = toCopy; } } diff --git a/nss/lib/softoken/sftkpars.c b/nss/lib/softoken/sftkpars.c index 465cbce..e972fe8 100644 --- a/nss/lib/softoken/sftkpars.c +++ b/nss/lib/softoken/sftkpars.c @@ -1,126 +1,131 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * The following code handles the storage of PKCS 11 modules used by the * NSS. This file is written to abstract away how the modules are * stored so we can deside that later. */ #include "pkcs11i.h" #include "sdb.h" -#include "prprf.h" +#include "prprf.h" #include "prenv.h" #include "utilpars.h" -#define FREE_CLEAR(p) if (p) { PORT_Free(p); p = NULL; } +#define FREE_CLEAR(p) \ + if (p) { \ + PORT_Free(p); \ + p = NULL; \ + } static void -sftk_parseTokenFlags(char *tmp, sftk_token_parameters *parsed) { - parsed->readOnly = NSSUTIL_ArgHasFlag("flags","readOnly",tmp); - parsed->noCertDB = NSSUTIL_ArgHasFlag("flags","noCertDB",tmp); - parsed->noKeyDB = NSSUTIL_ArgHasFlag("flags","noKeyDB",tmp); - parsed->forceOpen = NSSUTIL_ArgHasFlag("flags","forceOpen",tmp); - parsed->pwRequired = NSSUTIL_ArgHasFlag("flags","passwordRequired",tmp); - parsed->optimizeSpace = NSSUTIL_ArgHasFlag("flags","optimizeSpace",tmp); +sftk_parseTokenFlags(char *tmp, sftk_token_parameters *parsed) +{ + parsed->readOnly = NSSUTIL_ArgHasFlag("flags", "readOnly", tmp); + parsed->noCertDB = NSSUTIL_ArgHasFlag("flags", "noCertDB", tmp); + parsed->noKeyDB = NSSUTIL_ArgHasFlag("flags", "noKeyDB", tmp); + parsed->forceOpen = NSSUTIL_ArgHasFlag("flags", "forceOpen", tmp); + parsed->pwRequired = NSSUTIL_ArgHasFlag("flags", "passwordRequired", tmp); + parsed->optimizeSpace = NSSUTIL_ArgHasFlag("flags", "optimizeSpace", tmp); return; } static void -sftk_parseFlags(char *tmp, sftk_parameters *parsed) { - parsed->noModDB = NSSUTIL_ArgHasFlag("flags","noModDB",tmp); - parsed->readOnly = NSSUTIL_ArgHasFlag("flags","readOnly",tmp); +sftk_parseFlags(char *tmp, sftk_parameters *parsed) +{ + parsed->noModDB = NSSUTIL_ArgHasFlag("flags", "noModDB", tmp); + parsed->readOnly = NSSUTIL_ArgHasFlag("flags", "readOnly", tmp); /* keep legacy interface working */ - parsed->noCertDB = NSSUTIL_ArgHasFlag("flags","noCertDB",tmp); - parsed->forceOpen = NSSUTIL_ArgHasFlag("flags","forceOpen",tmp); - parsed->pwRequired = NSSUTIL_ArgHasFlag("flags","passwordRequired",tmp); - parsed->optimizeSpace = NSSUTIL_ArgHasFlag("flags","optimizeSpace",tmp); + parsed->noCertDB = NSSUTIL_ArgHasFlag("flags", "noCertDB", tmp); + parsed->forceOpen = NSSUTIL_ArgHasFlag("flags", "forceOpen", tmp); + parsed->pwRequired = NSSUTIL_ArgHasFlag("flags", "passwordRequired", tmp); + parsed->optimizeSpace = NSSUTIL_ArgHasFlag("flags", "optimizeSpace", tmp); return; } static CK_RV -sftk_parseTokenParameters(char *param, sftk_token_parameters *parsed) +sftk_parseTokenParameters(char *param, sftk_token_parameters *parsed) { int next; char *tmp = NULL; - char *index; + const char *index; index = NSSUTIL_ArgStrip(param); while (*index) { - NSSUTIL_HANDLE_STRING_ARG(index,parsed->configdir,"configDir=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updatedir,"updateDir=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updCertPrefix, - "updateCertPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updKeyPrefix, - "updateKeyPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updateID,"updateID=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->certPrefix,"certPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->keyPrefix,"keyPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->tokdes,"tokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updtokdes, - "updateTokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->slotdes,"slotDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,tmp,"minPWLen=", - if(tmp) { parsed->minPW=atoi(tmp); PORT_Free(tmp); tmp = NULL; }) - NSSUTIL_HANDLE_STRING_ARG(index,tmp,"flags=", - if(tmp) { sftk_parseTokenFlags(param,parsed); PORT_Free(tmp); - tmp = NULL; }) - NSSUTIL_HANDLE_FINAL_ARG(index) - } - return CKR_OK; + NSSUTIL_HANDLE_STRING_ARG(index, parsed->configdir, "configDir=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updatedir, "updateDir=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updCertPrefix, "updateCertPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updKeyPrefix, "updateKeyPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updateID, "updateID=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->certPrefix, "certPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->keyPrefix, "keyPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->tokdes, "tokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updtokdes, "updateTokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->slotdes, "slotDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, tmp, "minPWLen=", + if (tmp) { parsed->minPW=atoi(tmp); PORT_Free(tmp); tmp = NULL; }) + NSSUTIL_HANDLE_STRING_ARG(index, tmp, "flags=", + if (tmp) { sftk_parseTokenFlags(param,parsed); PORT_Free(tmp); tmp = NULL; }) + NSSUTIL_HANDLE_FINAL_ARG(index) + } + return CKR_OK; } static void sftk_parseTokens(char *tokenParams, sftk_parameters *parsed) { - char *tokenIndex; + const char *tokenIndex; sftk_token_parameters *tokens = NULL; - int i=0,count = 0,next; + int i = 0, count = 0, next; - if ((tokenParams == NULL) || (*tokenParams == 0)) return; + if ((tokenParams == NULL) || (*tokenParams == 0)) + return; /* first count the number of slots */ for (tokenIndex = NSSUTIL_ArgStrip(tokenParams); *tokenIndex; - tokenIndex = NSSUTIL_ArgStrip(NSSUTIL_ArgSkipParameter(tokenIndex))) { - count++; + tokenIndex = NSSUTIL_ArgStrip(NSSUTIL_ArgSkipParameter(tokenIndex))) { + count++; } /* get the data structures */ - tokens = (sftk_token_parameters *) - PORT_ZAlloc(count*sizeof(sftk_token_parameters)); - if (tokens == NULL) return; + tokens = (sftk_token_parameters *) + PORT_ZAlloc(count * sizeof(sftk_token_parameters)); + if (tokens == NULL) + return; for (tokenIndex = NSSUTIL_ArgStrip(tokenParams), i = 0; - *tokenIndex && i < count ; i++ ) { - char *name; - name = NSSUTIL_ArgGetLabel(tokenIndex,&next); - tokenIndex += next; + *tokenIndex && i < count; i++) { + char *name; + name = NSSUTIL_ArgGetLabel(tokenIndex, &next); + tokenIndex += next; - tokens[i].slotID = NSSUTIL_ArgDecodeNumber(name); + tokens[i].slotID = NSSUTIL_ArgDecodeNumber(name); tokens[i].readOnly = PR_FALSE; - tokens[i].noCertDB = PR_FALSE; - tokens[i].noKeyDB = PR_FALSE; - if (!NSSUTIL_ArgIsBlank(*tokenIndex)) { - char *args = NSSUTIL_ArgFetchValue(tokenIndex,&next); - tokenIndex += next; - if (args) { - sftk_parseTokenParameters(args,&tokens[i]); - PORT_Free(args); - } - } - if (name) PORT_Free(name); - tokenIndex = NSSUTIL_ArgStrip(tokenIndex); + tokens[i].noCertDB = PR_FALSE; + tokens[i].noKeyDB = PR_FALSE; + if (!NSSUTIL_ArgIsBlank(*tokenIndex)) { + char *args = NSSUTIL_ArgFetchValue(tokenIndex, &next); + tokenIndex += next; + if (args) { + sftk_parseTokenParameters(args, &tokens[i]); + PORT_Free(args); + } + } + if (name) + PORT_Free(name); + tokenIndex = NSSUTIL_ArgStrip(tokenIndex); } parsed->token_count = i; parsed->tokens = tokens; - return; + return; } CK_RV -sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS) +sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS) { int next; char *tmp = NULL; - char *index; + const char *index; char *certPrefix = NULL, *keyPrefix = NULL; char *tokdes = NULL, *ptokdes = NULL, *pupdtokdes = NULL; char *slotdes = NULL, *pslotdes = NULL; @@ -131,78 +136,77 @@ sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS) PORT_Memset(parsed, 0, sizeof(sftk_parameters)); while (*index) { - NSSUTIL_HANDLE_STRING_ARG(index,parsed->configdir,"configDir=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updatedir,"updateDir=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->updateID,"updateID=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->secmodName,"secmod=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->man,"manufacturerID=",;) - NSSUTIL_HANDLE_STRING_ARG(index,parsed->libdes,"libraryDescription=",;) - /* constructed values, used so legacy interfaces still work */ - NSSUTIL_HANDLE_STRING_ARG(index,certPrefix,"certPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,keyPrefix,"keyPrefix=",;) - NSSUTIL_HANDLE_STRING_ARG(index,tokdes,"cryptoTokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,ptokdes,"dbTokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,slotdes,"cryptoSlotDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,pslotdes,"dbSlotDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,fslotdes,"FIPSSlotDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,ftokdes,"FIPSTokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,pupdtokdes, "updateTokenDescription=",;) - NSSUTIL_HANDLE_STRING_ARG(index,minPW,"minPWLen=",;) - - NSSUTIL_HANDLE_STRING_ARG(index,tmp,"flags=", - if(tmp) { sftk_parseFlags(param,parsed); PORT_Free(tmp); - tmp = NULL; }) - NSSUTIL_HANDLE_STRING_ARG(index,tmp,"tokens=", - if(tmp) { sftk_parseTokens(tmp,parsed); PORT_Free(tmp); tmp = NULL; }) - NSSUTIL_HANDLE_FINAL_ARG(index) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->configdir, "configDir=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updatedir, "updateDir=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->updateID, "updateID=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->secmodName, "secmod=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->man, "manufacturerID=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, parsed->libdes, "libraryDescription=", ;) + /* constructed values, used so legacy interfaces still work */ + NSSUTIL_HANDLE_STRING_ARG(index, certPrefix, "certPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, keyPrefix, "keyPrefix=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, tokdes, "cryptoTokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, ptokdes, "dbTokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, slotdes, "cryptoSlotDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, pslotdes, "dbSlotDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, fslotdes, "FIPSSlotDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, ftokdes, "FIPSTokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, pupdtokdes, "updateTokenDescription=", ;) + NSSUTIL_HANDLE_STRING_ARG(index, minPW, "minPWLen=", ;) + + NSSUTIL_HANDLE_STRING_ARG(index, tmp, "flags=", + if (tmp) { sftk_parseFlags(param,parsed); PORT_Free(tmp); tmp = NULL; }) + NSSUTIL_HANDLE_STRING_ARG(index, tmp, "tokens=", + if (tmp) { sftk_parseTokens(tmp,parsed); PORT_Free(tmp); tmp = NULL; }) + NSSUTIL_HANDLE_FINAL_ARG(index) } if (parsed->tokens == NULL) { - int count = isFIPS ? 1 : 2; - int index = count-1; - sftk_token_parameters *tokens = NULL; - - tokens = (sftk_token_parameters *) - PORT_ZAlloc(count*sizeof(sftk_token_parameters)); - if (tokens == NULL) { - goto loser; - } - parsed->tokens = tokens; - parsed->token_count = count; - tokens[index].slotID = isFIPS ? FIPS_SLOT_ID : PRIVATE_KEY_SLOT_ID; - tokens[index].certPrefix = certPrefix; - tokens[index].keyPrefix = keyPrefix; - tokens[index].minPW = minPW ? atoi(minPW) : 0; - tokens[index].readOnly = parsed->readOnly; - tokens[index].noCertDB = parsed->noCertDB; - tokens[index].noKeyDB = parsed->noCertDB; - tokens[index].forceOpen = parsed->forceOpen; - tokens[index].pwRequired = parsed->pwRequired; - tokens[index].optimizeSpace = parsed->optimizeSpace; - tokens[0].optimizeSpace = parsed->optimizeSpace; - certPrefix = NULL; - keyPrefix = NULL; - if (isFIPS) { - tokens[index].tokdes = ftokdes; - tokens[index].updtokdes = pupdtokdes; - tokens[index].slotdes = fslotdes; - fslotdes = NULL; - ftokdes = NULL; - pupdtokdes = NULL; - } else { - tokens[index].tokdes = ptokdes; - tokens[index].updtokdes = pupdtokdes; - tokens[index].slotdes = pslotdes; - tokens[0].slotID = NETSCAPE_SLOT_ID; - tokens[0].tokdes = tokdes; - tokens[0].slotdes = slotdes; - tokens[0].noCertDB = PR_TRUE; - tokens[0].noKeyDB = PR_TRUE; - pupdtokdes = NULL; - ptokdes = NULL; - pslotdes = NULL; - tokdes = NULL; - slotdes = NULL; - } + int count = isFIPS ? 1 : 2; + int index = count - 1; + sftk_token_parameters *tokens = NULL; + + tokens = (sftk_token_parameters *) + PORT_ZAlloc(count * sizeof(sftk_token_parameters)); + if (tokens == NULL) { + goto loser; + } + parsed->tokens = tokens; + parsed->token_count = count; + tokens[index].slotID = isFIPS ? FIPS_SLOT_ID : PRIVATE_KEY_SLOT_ID; + tokens[index].certPrefix = certPrefix; + tokens[index].keyPrefix = keyPrefix; + tokens[index].minPW = minPW ? atoi(minPW) : 0; + tokens[index].readOnly = parsed->readOnly; + tokens[index].noCertDB = parsed->noCertDB; + tokens[index].noKeyDB = parsed->noCertDB; + tokens[index].forceOpen = parsed->forceOpen; + tokens[index].pwRequired = parsed->pwRequired; + tokens[index].optimizeSpace = parsed->optimizeSpace; + tokens[0].optimizeSpace = parsed->optimizeSpace; + certPrefix = NULL; + keyPrefix = NULL; + if (isFIPS) { + tokens[index].tokdes = ftokdes; + tokens[index].updtokdes = pupdtokdes; + tokens[index].slotdes = fslotdes; + fslotdes = NULL; + ftokdes = NULL; + pupdtokdes = NULL; + } else { + tokens[index].tokdes = ptokdes; + tokens[index].updtokdes = pupdtokdes; + tokens[index].slotdes = pslotdes; + tokens[0].slotID = NETSCAPE_SLOT_ID; + tokens[0].tokdes = tokdes; + tokens[0].slotdes = slotdes; + tokens[0].noCertDB = PR_TRUE; + tokens[0].noKeyDB = PR_TRUE; + pupdtokdes = NULL; + ptokdes = NULL; + pslotdes = NULL; + tokdes = NULL; + slotdes = NULL; + } } loser: @@ -224,25 +228,24 @@ sftk_freeParams(sftk_parameters *params) { int i; - for (i=0; i < params->token_count; i++) { - FREE_CLEAR(params->tokens[i].configdir); - FREE_CLEAR(params->tokens[i].certPrefix); - FREE_CLEAR(params->tokens[i].keyPrefix); - FREE_CLEAR(params->tokens[i].tokdes); - FREE_CLEAR(params->tokens[i].slotdes); - FREE_CLEAR(params->tokens[i].updatedir); - FREE_CLEAR(params->tokens[i].updCertPrefix); - FREE_CLEAR(params->tokens[i].updKeyPrefix); - FREE_CLEAR(params->tokens[i].updateID); - FREE_CLEAR(params->tokens[i].updtokdes); + for (i = 0; i < params->token_count; i++) { + FREE_CLEAR(params->tokens[i].configdir); + FREE_CLEAR(params->tokens[i].certPrefix); + FREE_CLEAR(params->tokens[i].keyPrefix); + FREE_CLEAR(params->tokens[i].tokdes); + FREE_CLEAR(params->tokens[i].slotdes); + FREE_CLEAR(params->tokens[i].updatedir); + FREE_CLEAR(params->tokens[i].updCertPrefix); + FREE_CLEAR(params->tokens[i].updKeyPrefix); + FREE_CLEAR(params->tokens[i].updateID); + FREE_CLEAR(params->tokens[i].updtokdes); } FREE_CLEAR(params->configdir); FREE_CLEAR(params->secmodName); FREE_CLEAR(params->man); - FREE_CLEAR(params->libdes); + FREE_CLEAR(params->libdes); FREE_CLEAR(params->tokens); FREE_CLEAR(params->updatedir); FREE_CLEAR(params->updateID); } - diff --git a/nss/lib/softoken/sftkpars.h b/nss/lib/softoken/sftkpars.h index 6178dff..a7707fc 100644 --- a/nss/lib/softoken/sftkpars.h +++ b/nss/lib/softoken/sftkpars.h @@ -5,13 +5,10 @@ #include "sftkdbt.h" /* parsing functions */ -char * sftk_argFetchValue(char *string, int *pcount); -char * sftk_getSecmodName(char *param, SDBType *dbType, char **appName, char **filename,PRBool *rw); +char *sftk_argFetchValue(char *string, int *pcount); +char *sftk_getSecmodName(char *param, SDBType *dbType, char **appName, char **filename, PRBool *rw); char *sftk_argStrip(char *c); CK_RV sftk_parseParameters(char *param, sftk_parameters *parsed, PRBool isFIPS); void sftk_freeParams(sftk_parameters *params); const char *sftk_EvaluateConfigDir(const char *configdir, SDBType *dbType, char **app); -char * sftk_argGetParamValue(char *paramName,char *parameters); - - - +char *sftk_argGetParamValue(char *paramName, char *parameters); diff --git a/nss/lib/softoken/sftkpwd.c b/nss/lib/softoken/sftkpwd.c index d8ce857..0b8c91b 100644 --- a/nss/lib/softoken/sftkpwd.c +++ b/nss/lib/softoken/sftkpwd.c @@ -1,28 +1,28 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* +/* * The following code handles the storage of PKCS 11 modules used by the * NSS. For the rest of NSS, only one kind of database handle exists: * * SFTKDBHandle * - * There is one SFTKDBHandle for the each key database and one for each cert + * There is one SFTKDBHandle for the each key database and one for each cert * database. These databases are opened as associated pairs, one pair per * slot. SFTKDBHandles are reference counted objects. * * Each SFTKDBHandle points to a low level database handle (SDB). This handle - * represents the underlying physical database. These objects are not + * represents the underlying physical database. These objects are not * reference counted, an are 'owned' by their respective SFTKDBHandles. * - * + * */ #include "sftkdb.h" #include "sftkdbti.h" #include "pkcs11t.h" #include "pkcs11i.h" #include "sdb.h" -#include "prprf.h" +#include "prprf.h" #include "secasn1.h" #include "pratom.h" #include "blapi.h" @@ -33,9 +33,9 @@ #include "lgglue.h" #include "secerr.h" #include "softoken.h" - + /****************************************************************** - * + * * Key DB password handling functions * * These functions manage the key db password (set, reset, initialize, use). @@ -46,45 +46,44 @@ * in the database is no longer considered 'plain text'. */ - /* take string password and turn it into a key. The key is dependent * on a global salt entry acquired from the database. This salted * value will be based to a pkcs5 pbe function before it is used * in an actual encryption */ static SECStatus sftkdb_passwordToKey(SFTKDBHandle *keydb, SECItem *salt, - const char *pw, SECItem *key) + const char *pw, SECItem *key) { SHA1Context *cx = NULL; SECStatus rv = SECFailure; key->data = PORT_Alloc(SHA1_LENGTH); if (key->data == NULL) { - goto loser; + goto loser; } key->len = SHA1_LENGTH; cx = SHA1_NewContext(); - if ( cx == NULL) { - goto loser; + if (cx == NULL) { + goto loser; } SHA1_Begin(cx); - if (salt && salt->data ) { - SHA1_Update(cx, salt->data, salt->len); + if (salt && salt->data) { + SHA1_Update(cx, salt->data, salt->len); } SHA1_Update(cx, (unsigned char *)pw, PORT_Strlen(pw)); SHA1_End(cx, key->data, &key->len, key->len); rv = SECSuccess; - + loser: if (cx) { - SHA1_DestroyContext(cx, PR_TRUE); + SHA1_DestroyContext(cx, PR_TRUE); } if (rv != SECSuccess) { - if (key->data != NULL) { - PORT_ZFree(key->data,key->len); - } - key->data = NULL; + if (key->data != NULL) { + PORT_ZFree(key->data, key->len); + } + key->data = NULL; } return rv; } @@ -101,10 +100,10 @@ loser: typedef struct sftkCipherValueStr sftkCipherValue; struct sftkCipherValueStr { PLArenaPool *arena; - SECOidTag alg; + SECOidTag alg; NSSPKCS5PBEParameter *param; - SECItem salt; - SECItem value; + SECItem salt; + SECItem value; }; #define SFTK_CIPHERTEXT_VERSION 3 @@ -119,12 +118,12 @@ SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate) const SEC_ASN1Template sftkdb_EncryptedDataInfoTemplate[] = { { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SFTKDBEncryptedDataInfo) }, - { SEC_ASN1_INLINE | SEC_ASN1_XTRN , - offsetof(SFTKDBEncryptedDataInfo,algorithm), - SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, + 0, NULL, sizeof(SFTKDBEncryptedDataInfo) }, + { SEC_ASN1_INLINE | SEC_ASN1_XTRN, + offsetof(SFTKDBEncryptedDataInfo, algorithm), + SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) }, { SEC_ASN1_OCTET_STRING, - offsetof(SFTKDBEncryptedDataInfo,encryptedData) }, + offsetof(SFTKDBEncryptedDataInfo, encryptedData) }, { 0 } }; @@ -141,20 +140,20 @@ sftkdb_decodeCipherText(SECItem *cipherText, sftkCipherValue *cipherValue) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - return SECFailure; + return SECFailure; } cipherValue->arena = NULL; cipherValue->param = NULL; rv = SEC_QuickDERDecodeItem(arena, &edi, sftkdb_EncryptedDataInfoTemplate, - cipherText); + cipherText); if (rv != SECSuccess) { - goto loser; + goto loser; } cipherValue->alg = SECOID_GetAlgorithmTag(&edi.algorithm); cipherValue->param = nsspkcs5_AlgidToParam(&edi.algorithm); if (cipherValue->param == NULL) { - goto loser; + goto loser; } cipherValue->value = edi.encryptedData; cipherValue->arena = arena; @@ -162,24 +161,22 @@ sftkdb_decodeCipherText(SECItem *cipherText, sftkCipherValue *cipherValue) return SECSuccess; loser: if (cipherValue->param) { - nsspkcs5_DestroyPBEParameter(cipherValue->param); - cipherValue->param = NULL; + nsspkcs5_DestroyPBEParameter(cipherValue->param); + cipherValue->param = NULL; } if (arena) { - PORT_FreeArena(arena,PR_FALSE); + PORT_FreeArena(arena, PR_FALSE); } return SECFailure; } - - -/* +/* * unlike decode, Encode actually allocates a SECItem the caller must free * The caller can pass an optional arena to to indicate where to place * the resultant cipherText. */ static SECStatus -sftkdb_encodeCipherText(PLArenaPool *arena, sftkCipherValue *cipherValue, +sftkdb_encodeCipherText(PLArenaPool *arena, sftkCipherValue *cipherValue, SECItem **cipherText) { SFTKDBEncryptedDataInfo edi; @@ -187,40 +184,38 @@ sftkdb_encodeCipherText(PLArenaPool *arena, sftkCipherValue *cipherValue, SECStatus rv; PLArenaPool *localArena = NULL; - localArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (localArena == NULL) { - return SECFailure; + return SECFailure; } - algid = nsspkcs5_CreateAlgorithmID(localArena, cipherValue->alg, - cipherValue->param); + algid = nsspkcs5_CreateAlgorithmID(localArena, cipherValue->alg, + cipherValue->param); if (algid == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } rv = SECOID_CopyAlgorithmID(localArena, &edi.algorithm, algid); SECOID_DestroyAlgorithmID(algid, PR_TRUE); if (rv != SECSuccess) { - goto loser; + goto loser; } edi.encryptedData = cipherValue->value; - *cipherText = SEC_ASN1EncodeItem(arena, NULL, &edi, - sftkdb_EncryptedDataInfoTemplate); + *cipherText = SEC_ASN1EncodeItem(arena, NULL, &edi, + sftkdb_EncryptedDataInfoTemplate); if (*cipherText == NULL) { - rv = SECFailure; + rv = SECFailure; } loser: if (localArena) { - PORT_FreeArena(localArena,PR_FALSE); + PORT_FreeArena(localArena, PR_FALSE); } return rv; } - /* * Use our key to decode a cipherText block from the database. * @@ -228,7 +223,7 @@ loser: * with SECITEM_FreeItem by the caller. */ SECStatus -sftkdb_DecryptAttribute(SECItem *passKey, SECItem *cipherText, SECItem **plain) +sftkdb_DecryptAttribute(SECItem *passKey, SECItem *cipherText, SECItem **plain) { SECStatus rv; sftkCipherValue cipherValue; @@ -236,22 +231,22 @@ sftkdb_DecryptAttribute(SECItem *passKey, SECItem *cipherText, SECItem **plain) /* First get the cipher type */ rv = sftkdb_decodeCipherText(cipherText, &cipherValue); if (rv != SECSuccess) { - goto loser; + goto loser; } - *plain = nsspkcs5_CipherData(cipherValue.param, passKey, &cipherValue.value, - PR_FALSE, NULL); + *plain = nsspkcs5_CipherData(cipherValue.param, passKey, &cipherValue.value, + PR_FALSE, NULL); if (*plain == NULL) { - rv = SECFailure; - goto loser; - } + rv = SECFailure; + goto loser; + } loser: if (cipherValue.param) { - nsspkcs5_DestroyPBEParameter(cipherValue.param); + nsspkcs5_DestroyPBEParameter(cipherValue.param); } if (cipherValue.arena) { - PORT_FreeArena(cipherValue.arena,PR_FALSE); + PORT_FreeArena(cipherValue.arena, PR_FALSE); } return rv; } @@ -263,8 +258,8 @@ loser: * salt automatically. */ SECStatus -sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey, - SECItem *plainText, SECItem **cipherText) +sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey, + SECItem *plainText, SECItem **cipherText) { SECStatus rv; sftkCipherValue cipherValue; @@ -275,32 +270,33 @@ sftkdb_EncryptAttribute(PLArenaPool *arena, SECItem *passKey, cipherValue.alg = SEC_OID_PKCS12_PBE_WITH_SHA1_AND_TRIPLE_DES_CBC; cipherValue.salt.len = SHA1_LENGTH; cipherValue.salt.data = saltData; - RNG_GenerateGlobalRandomBytes(saltData,cipherValue.salt.len); + RNG_GenerateGlobalRandomBytes(saltData, cipherValue.salt.len); - param = nsspkcs5_NewParam(cipherValue.alg, &cipherValue.salt, 1); + param = nsspkcs5_NewParam(cipherValue.alg, HASH_AlgSHA1, &cipherValue.salt, + 1); if (param == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } cipher = nsspkcs5_CipherData(param, passKey, plainText, PR_TRUE, NULL); if (cipher == NULL) { - rv = SECFailure; - goto loser; - } + rv = SECFailure; + goto loser; + } cipherValue.value = *cipher; cipherValue.param = param; rv = sftkdb_encodeCipherText(arena, &cipherValue, cipherText); if (rv != SECSuccess) { - goto loser; + goto loser; } loser: if (cipher) { - SECITEM_FreeItem(cipher, PR_TRUE); + SECITEM_FreeItem(cipher, PR_TRUE); } if (param) { - nsspkcs5_DestroyPBEParameter(param); + nsspkcs5_DestroyPBEParameter(param); } return rv; } @@ -312,10 +308,10 @@ loser: * must preallocate the space in the secitem. */ static SECStatus -sftkdb_pbehash(SECOidTag sigOid, SECItem *passKey, - NSSPKCS5PBEParameter *param, - CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType, - SECItem *plainText, SECItem *signData) +sftkdb_pbehash(SECOidTag sigOid, SECItem *passKey, + NSSPKCS5PBEParameter *param, + CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType, + SECItem *plainText, SECItem *signData) { SECStatus rv = SECFailure; SECItem *key = NULL; @@ -326,23 +322,23 @@ sftkdb_pbehash(SECOidTag sigOid, SECItem *passKey, hashType = HASH_FromHMACOid(param->encAlg); if (hashType == HASH_AlgNULL) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); + return SECFailure; } hashObj = HASH_GetRawHashObject(hashType); if (hashObj == NULL) { - goto loser; + goto loser; } key = nsspkcs5_ComputeKeyAndIV(param, passKey, NULL, PR_FALSE); if (!key) { - goto loser; + goto loser; } hashCx = HMAC_Create(hashObj, key->data, key->len, PR_TRUE); if (!hashCx) { - goto loser; + goto loser; } HMAC_Begin(hashCx); /* Tie this value to a particular object. This is most important for @@ -358,10 +354,10 @@ sftkdb_pbehash(SECOidTag sigOid, SECItem *passKey, loser: if (hashCx) { - HMAC_Destroy(hashCx, PR_TRUE); + HMAC_Destroy(hashCx, PR_TRUE); } if (key) { - SECITEM_FreeItem(key,PR_TRUE); + SECITEM_FreeItem(key, PR_TRUE); } return rv; } @@ -372,40 +368,39 @@ loser: * plainText is the plainText of the attribute. */ SECStatus -sftkdb_VerifyAttribute(SECItem *passKey, CK_OBJECT_HANDLE objectID, - CK_ATTRIBUTE_TYPE attrType, - SECItem *plainText, SECItem *signText) +sftkdb_VerifyAttribute(SECItem *passKey, CK_OBJECT_HANDLE objectID, + CK_ATTRIBUTE_TYPE attrType, + SECItem *plainText, SECItem *signText) { SECStatus rv; sftkCipherValue signValue; SECItem signature; unsigned char signData[HASH_LENGTH_MAX]; - /* First get the cipher type */ rv = sftkdb_decodeCipherText(signText, &signValue); if (rv != SECSuccess) { - goto loser; + goto loser; } signature.data = signData; signature.len = sizeof(signData); - rv = sftkdb_pbehash(signValue.alg, passKey, signValue.param, - objectID, attrType, plainText, &signature); + rv = sftkdb_pbehash(signValue.alg, passKey, signValue.param, + objectID, attrType, plainText, &signature); if (rv != SECSuccess) { - goto loser; + goto loser; } - if (SECITEM_CompareItem(&signValue.value,&signature) != 0) { - PORT_SetError(SEC_ERROR_BAD_SIGNATURE); - rv = SECFailure; + if (SECITEM_CompareItem(&signValue.value, &signature) != 0) { + PORT_SetError(SEC_ERROR_BAD_SIGNATURE); + rv = SECFailure; } loser: if (signValue.param) { - nsspkcs5_DestroyPBEParameter(signValue.param); + nsspkcs5_DestroyPBEParameter(signValue.param); } if (signValue.arena) { - PORT_FreeArena(signValue.arena,PR_FALSE); + PORT_FreeArena(signValue.arena, PR_FALSE); } return rv; } @@ -415,9 +410,9 @@ loser: * attribute. The signText is a PKCS 5 v2 pbe. */ SECStatus -sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, - CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType, - SECItem *plainText, SECItem **signature) +sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, + CK_OBJECT_HANDLE objectID, CK_ATTRIBUTE_TYPE attrType, + SECItem *plainText, SECItem **signature) { SECStatus rv; sftkCipherValue signValue; @@ -446,13 +441,13 @@ sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, signValue.salt.data = saltData; signValue.value.data = signData; signValue.value.len = hmacLength; - RNG_GenerateGlobalRandomBytes(saltData,prfLength); + RNG_GenerateGlobalRandomBytes(saltData, prfLength); /* initialize our pkcs5 parameter */ - param = nsspkcs5_NewParam(signValue.alg, &signValue.salt, 1); + param = nsspkcs5_NewParam(signValue.alg, HASH_AlgSHA1, &signValue.salt, 1); if (param == NULL) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } param->keyID = pbeBitGenIntegrityKey; /* set the PKCS 5 v2 parameters, not extractable from the @@ -462,47 +457,46 @@ sftkdb_SignAttribute(PLArenaPool *arena, SECItem *passKey, param->keyLen = hmacLength; rv = SECOID_SetAlgorithmID(param->poolp, ¶m->prfAlg, prfAlg, NULL); if (rv != SECSuccess) { - goto loser; + goto loser; } - /* calculate the mac */ rv = sftkdb_pbehash(signValue.alg, passKey, param, objectID, attrType, - plainText, &signValue.value); + plainText, &signValue.value); if (rv != SECSuccess) { - goto loser; + goto loser; } signValue.param = param; /* write it out */ rv = sftkdb_encodeCipherText(arena, &signValue, signature); if (rv != SECSuccess) { - goto loser; + goto loser; } loser: if (param) { - nsspkcs5_DestroyPBEParameter(param); + nsspkcs5_DestroyPBEParameter(param); } return rv; } /* * safely swith the passed in key for the one caches in the keydb handle - * + * * A key attached to the handle tells us the the token is logged in. - * We can used the key attached to the handle in sftkdb_EncryptAttribute + * We can used the key attached to the handle in sftkdb_EncryptAttribute * and sftkdb_DecryptAttribute calls. - */ -static void + */ +static void sftkdb_switchKeys(SFTKDBHandle *keydb, SECItem *passKey) { unsigned char *data; int len; if (keydb->passwordLock == NULL) { - PORT_Assert(keydb->type != SFTK_KEYDB_TYPE); - return; + PORT_Assert(keydb->type != SFTK_KEYDB_TYPE); + return; } /* an atomic pointer set would be nice */ @@ -533,10 +527,10 @@ PRBool sftkdb_NeedUpdateDBPassword(SFTKDBHandle *keydb) { if (!sftkdb_InUpdateMerge(keydb)) { - return PR_FALSE; + return PR_FALSE; } if (keydb->updateDBIsInit && !keydb->updatePasswordKey) { - return PR_TRUE; + return PR_TRUE; } return PR_FALSE; } @@ -551,17 +545,17 @@ sftkdb_GetUpdatePasswordKey(SFTKDBHandle *handle) /* if we're a cert db, fetch it from our peer key db */ if (handle->type == SFTK_CERTDB_TYPE) { - handle = handle->peerDB; + handle = handle->peerDB; } /* don't have one */ if (!handle) { - return NULL; + return NULL; } PZ_Lock(handle->passwordLock); if (handle->updatePasswordKey) { - key = SECITEM_DupItem(handle->updatePasswordKey); + key = SECITEM_DupItem(handle->updatePasswordKey); } PZ_Unlock(handle->passwordLock); @@ -578,23 +572,23 @@ sftkdb_FreeUpdatePasswordKey(SFTKDBHandle *handle) /* don't have one */ if (!handle) { - return; + return; } /* if we're a cert db, we don't have one */ if (handle->type == SFTK_CERTDB_TYPE) { - return; + return; } PZ_Lock(handle->passwordLock); if (handle->updatePasswordKey) { - key = handle->updatePasswordKey; - handle->updatePasswordKey = NULL; + key = handle->updatePasswordKey; + handle->updatePasswordKey = NULL; } PZ_Unlock(handle->passwordLock); if (key) { - SECITEM_ZfreeItem(key, PR_TRUE); + SECITEM_ZfreeItem(key, PR_TRUE); } return; @@ -602,24 +596,24 @@ sftkdb_FreeUpdatePasswordKey(SFTKDBHandle *handle) /* * what password db we use depends heavily on the update state machine - * + * * 1) no update db, return the normal database. * 2) update db and no merge return the update db. - * 3) update db and in merge: - * return the update db if we need the update db's password, + * 3) update db and in merge: + * return the update db if we need the update db's password, * otherwise return our normal datbase. */ static SDB * sftk_getPWSDB(SFTKDBHandle *keydb) { if (!keydb->update) { - return keydb->db; + return keydb->db; } if (!sftkdb_InUpdateMerge(keydb)) { - return keydb->update; + return keydb->update; } if (sftkdb_NeedUpdateDBPassword(keydb)) { - return keydb->update; + return keydb->update; } return keydb->db; } @@ -629,7 +623,7 @@ sftk_getPWSDB(SFTKDBHandle *keydb) * This is will show up outside of PKCS #11 as CKF_USER_PIN_INIT * in the token flags. */ -SECStatus +SECStatus sftkdb_HasPasswordSet(SFTKDBHandle *keydb) { SECItem salt, value; @@ -639,12 +633,12 @@ sftkdb_HasPasswordSet(SFTKDBHandle *keydb) SDB *db; if (keydb == NULL) { - return SECFailure; + return SECFailure; } db = sftk_getPWSDB(keydb); if (db == NULL) { - return SECFailure; + return SECFailure; } salt.data = saltData; @@ -654,13 +648,12 @@ sftkdb_HasPasswordSet(SFTKDBHandle *keydb) crv = (*db->sdb_GetMetaData)(db, "password", &salt, &value); /* If no password is set, we can update right away */ - if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update - && crv != CKR_OK) { - /* update the peer certdb if it exists */ - if (keydb->peerDB) { - sftkdb_Update(keydb->peerDB, NULL); - } - sftkdb_Update(keydb, NULL); + if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update && crv != CKR_OK) { + /* update the peer certdb if it exists */ + if (keydb->peerDB) { + sftkdb_Update(keydb->peerDB, NULL); + } + sftkdb_Update(keydb, NULL); } return (crv == CKR_OK) ? SECSuccess : SECFailure; } @@ -671,7 +664,7 @@ sftkdb_HasPasswordSet(SFTKDBHandle *keydb) /* * check if the supplied password is valid */ -SECStatus +SECStatus sftkdb_CheckPassword(SFTKDBHandle *keydb, const char *pw, PRBool *tokenRemoved) { SECStatus rv; @@ -684,18 +677,19 @@ sftkdb_CheckPassword(SFTKDBHandle *keydb, const char *pw, PRBool *tokenRemoved) CK_RV crv; if (keydb == NULL) { - return SECFailure; + return SECFailure; } db = sftk_getPWSDB(keydb); if (db == NULL) { - return SECFailure; + return SECFailure; } key.data = NULL; key.len = 0; - if (pw == NULL) pw=""; + if (pw == NULL) + pw = ""; /* get the entry from the database */ salt.data = saltData; @@ -704,148 +698,148 @@ sftkdb_CheckPassword(SFTKDBHandle *keydb, const char *pw, PRBool *tokenRemoved) value.len = sizeof(valueData); crv = (*db->sdb_GetMetaData)(db, "password", &salt, &value); if (crv != CKR_OK) { - rv = SECFailure; - goto done; + rv = SECFailure; + goto done; } /* get our intermediate key based on the entry salt value */ rv = sftkdb_passwordToKey(keydb, &salt, pw, &key); if (rv != SECSuccess) { - goto done; + goto done; } /* decrypt the entry value */ rv = sftkdb_DecryptAttribute(&key, &value, &result); if (rv != SECSuccess) { - goto done; + goto done; } /* if it's what we expect, update our key in the database handle and * return Success */ if ((result->len == SFTK_PW_CHECK_LEN) && - PORT_Memcmp(result->data, SFTK_PW_CHECK_STRING, SFTK_PW_CHECK_LEN) == 0){ - /* - * We have a password, now lets handle any potential update cases.. - * - * First, the normal case: no update. In this case we only need the - * the password for our only DB, which we now have, we switch - * the keys and fall through. - * Second regular (non-merge) update: The target DB does not yet have - * a password initialized, we now have the password for the source DB, - * so we can switch the keys and simply update the target database. - * Merge update case: This one is trickier. - * 1) If we need the source DB password, then we just got it here. - * We need to save that password, - * then we need to check to see if we need or have the target - * database password. - * If we have it (it's the same as the source), or don't need - * it (it's not set or is ""), we can start the update now. - * If we don't have it, we need the application to get it from - * the user. Clear our sessions out to simulate a token - * removal. C_GetTokenInfo will change the token description - * and the token will still appear to be logged out. - * 2) If we already have the source DB password, this password is - * for the target database. We can now move forward with the - * update, as we now have both required passwords. - * - */ + PORT_Memcmp(result->data, SFTK_PW_CHECK_STRING, SFTK_PW_CHECK_LEN) == 0) { + /* + * We have a password, now lets handle any potential update cases.. + * + * First, the normal case: no update. In this case we only need the + * the password for our only DB, which we now have, we switch + * the keys and fall through. + * Second regular (non-merge) update: The target DB does not yet have + * a password initialized, we now have the password for the source DB, + * so we can switch the keys and simply update the target database. + * Merge update case: This one is trickier. + * 1) If we need the source DB password, then we just got it here. + * We need to save that password, + * then we need to check to see if we need or have the target + * database password. + * If we have it (it's the same as the source), or don't need + * it (it's not set or is ""), we can start the update now. + * If we don't have it, we need the application to get it from + * the user. Clear our sessions out to simulate a token + * removal. C_GetTokenInfo will change the token description + * and the token will still appear to be logged out. + * 2) If we already have the source DB password, this password is + * for the target database. We can now move forward with the + * update, as we now have both required passwords. + * + */ PZ_Lock(keydb->passwordLock); - if (sftkdb_NeedUpdateDBPassword(keydb)) { - /* Squirrel this special key away. - * This has the side effect of turning sftkdb_NeedLegacyPW off, - * as well as changing which database is returned from - * SFTK_GET_PW_DB (thus effecting both sftkdb_CheckPassword() - * and sftkdb_HasPasswordSet()) */ - keydb->updatePasswordKey = SECITEM_DupItem(&key); - PZ_Unlock(keydb->passwordLock); - if (keydb->updatePasswordKey == NULL) { - /* PORT_Error set by SECITEM_DupItem */ - rv = SECFailure; - goto done; - } - - /* Simulate a token removal -- we need to do this any + if (sftkdb_NeedUpdateDBPassword(keydb)) { + /* Squirrel this special key away. + * This has the side effect of turning sftkdb_NeedLegacyPW off, + * as well as changing which database is returned from + * SFTK_GET_PW_DB (thus effecting both sftkdb_CheckPassword() + * and sftkdb_HasPasswordSet()) */ + keydb->updatePasswordKey = SECITEM_DupItem(&key); + PZ_Unlock(keydb->passwordLock); + if (keydb->updatePasswordKey == NULL) { + /* PORT_Error set by SECITEM_DupItem */ + rv = SECFailure; + goto done; + } + + /* Simulate a token removal -- we need to do this any * any case at this point so the token name is correct. */ - *tokenRemoved = PR_TRUE; - - /* - * OK, we got the update DB password, see if we need a password - * for the target... - */ - if (sftkdb_HasPasswordSet(keydb) == SECSuccess) { - /* We have a password, do we know what the password is? - * check 1) for the password the user supplied for the - * update DB, - * and 2) for the null password. - * - * RECURSION NOTE: we are calling ourselves here. This means - * any updates, switchKeys, etc will have been completed - * if these functions return successfully, in those cases - * just exit returning Success. We don't recurse infinitely - * because we are making this call from a NeedUpdateDBPassword - * block and we've already set that update password at this - * point. */ - rv = sftkdb_CheckPassword(keydb, pw, tokenRemoved); - if (rv == SECSuccess) { - /* source and target databases have the same password, we - * are good to go */ - goto done; - } - sftkdb_CheckPassword(keydb, "", tokenRemoved); - - /* - * Important 'NULL' code here. At this point either we - * succeeded in logging in with "" or we didn't. + *tokenRemoved = PR_TRUE; + + /* + * OK, we got the update DB password, see if we need a password + * for the target... + */ + if (sftkdb_HasPasswordSet(keydb) == SECSuccess) { + /* We have a password, do we know what the password is? + * check 1) for the password the user supplied for the + * update DB, + * and 2) for the null password. + * + * RECURSION NOTE: we are calling ourselves here. This means + * any updates, switchKeys, etc will have been completed + * if these functions return successfully, in those cases + * just exit returning Success. We don't recurse infinitely + * because we are making this call from a NeedUpdateDBPassword + * block and we've already set that update password at this + * point. */ + rv = sftkdb_CheckPassword(keydb, pw, tokenRemoved); + if (rv == SECSuccess) { + /* source and target databases have the same password, we + * are good to go */ + goto done; + } + sftkdb_CheckPassword(keydb, "", tokenRemoved); + + /* + * Important 'NULL' code here. At this point either we + * succeeded in logging in with "" or we didn't. * * If we did succeed at login, our machine state will be set - * to logged in appropriately. The application will find that - * it's logged in as soon as it opens a new session. We have - * also completed the update. Life is good. - * - * If we did not succeed, well the user still successfully - * logged into the update database, since we faked the token - * removal it's just like the user logged into his smart card - * then removed it. the actual login work, so we report that - * success back to the user, but we won't actually be - * logged in. The application will find this out when it - * checks it's login state, thus triggering another password - * prompt so we can get the real target DB password. - * - * summary, we exit from here with SECSuccess no matter what. - */ - rv = SECSuccess; - goto done; - } else { - /* there is no password, just fall through to update. - * update will write the source DB's password record - * into the target DB just like it would in a non-merge - * update case. */ - } - } else { - PZ_Unlock(keydb->passwordLock); - } - /* load the keys, so the keydb can parse it's key set */ - sftkdb_switchKeys(keydb, &key); - - /* we need to update, do it now */ - if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update) { - /* update the peer certdb if it exists */ - if (keydb->peerDB) { - sftkdb_Update(keydb->peerDB, &key); - } - sftkdb_Update(keydb, &key); - } + * to logged in appropriately. The application will find that + * it's logged in as soon as it opens a new session. We have + * also completed the update. Life is good. + * + * If we did not succeed, well the user still successfully + * logged into the update database, since we faked the token + * removal it's just like the user logged into his smart card + * then removed it. the actual login work, so we report that + * success back to the user, but we won't actually be + * logged in. The application will find this out when it + * checks it's login state, thus triggering another password + * prompt so we can get the real target DB password. + * + * summary, we exit from here with SECSuccess no matter what. + */ + rv = SECSuccess; + goto done; + } else { + /* there is no password, just fall through to update. + * update will write the source DB's password record + * into the target DB just like it would in a non-merge + * update case. */ + } + } else { + PZ_Unlock(keydb->passwordLock); + } + /* load the keys, so the keydb can parse it's key set */ + sftkdb_switchKeys(keydb, &key); + + /* we need to update, do it now */ + if (((keydb->db->sdb_flags & SDB_RDONLY) == 0) && keydb->update) { + /* update the peer certdb if it exists */ + if (keydb->peerDB) { + sftkdb_Update(keydb->peerDB, &key); + } + sftkdb_Update(keydb, &key); + } } else { rv = SECFailure; - /*PORT_SetError( bad password); */ + /*PORT_SetError( bad password); */ } done: if (key.data) { - PORT_ZFree(key.data,key.len); + PORT_ZFree(key.data, key.len); } if (result) { - SECITEM_FreeItem(result,PR_TRUE); + SECITEM_FreeItem(result, PR_TRUE); } return rv; } @@ -859,24 +853,23 @@ sftkdb_PWCached(SFTKDBHandle *keydb) return keydb->passwordKey.data ? SECSuccess : SECFailure; } - static CK_RV sftk_updateMacs(PLArenaPool *arena, SFTKDBHandle *handle, - CK_OBJECT_HANDLE id, SECItem *newKey) + CK_OBJECT_HANDLE id, SECItem *newKey) { CK_ATTRIBUTE authAttrs[] = { - {CKA_MODULUS, NULL, 0}, - {CKA_PUBLIC_EXPONENT, NULL, 0}, - {CKA_CERT_SHA1_HASH, NULL, 0}, - {CKA_CERT_MD5_HASH, NULL, 0}, - {CKA_TRUST_SERVER_AUTH, NULL, 0}, - {CKA_TRUST_CLIENT_AUTH, NULL, 0}, - {CKA_TRUST_EMAIL_PROTECTION, NULL, 0}, - {CKA_TRUST_CODE_SIGNING, NULL, 0}, - {CKA_TRUST_STEP_UP_APPROVED, NULL, 0}, - {CKA_NSS_OVERRIDE_EXTENSIONS, NULL, 0}, + { CKA_MODULUS, NULL, 0 }, + { CKA_PUBLIC_EXPONENT, NULL, 0 }, + { CKA_CERT_SHA1_HASH, NULL, 0 }, + { CKA_CERT_MD5_HASH, NULL, 0 }, + { CKA_TRUST_SERVER_AUTH, NULL, 0 }, + { CKA_TRUST_CLIENT_AUTH, NULL, 0 }, + { CKA_TRUST_EMAIL_PROTECTION, NULL, 0 }, + { CKA_TRUST_CODE_SIGNING, NULL, 0 }, + { CKA_TRUST_STEP_UP_APPROVED, NULL, 0 }, + { CKA_NSS_OVERRIDE_EXTENSIONS, NULL, 0 }, }; - CK_ULONG authAttrCount = sizeof(authAttrs)/sizeof(CK_ATTRIBUTE); + CK_ULONG authAttrCount = sizeof(authAttrs) / sizeof(CK_ATTRIBUTE); unsigned int i, count; SFTKDBHandle *keyHandle = handle; SDB *keyTarget = NULL; @@ -884,39 +877,39 @@ sftk_updateMacs(PLArenaPool *arena, SFTKDBHandle *handle, id &= SFTK_OBJ_ID_MASK; if (handle->type != SFTK_KEYDB_TYPE) { - keyHandle = handle->peerDB; + keyHandle = handle->peerDB; } if (keyHandle == NULL) { - return CKR_OK; + return CKR_OK; } /* old DB's don't have meta data, finished with MACs */ keyTarget = SFTK_GET_SDB(keyHandle); - if ((keyTarget->sdb_flags &SDB_HAS_META) == 0) { - return CKR_OK; + if ((keyTarget->sdb_flags & SDB_HAS_META) == 0) { + return CKR_OK; } /* - * STEP 1: find the MACed attributes of this object + * STEP 1: find the MACed attributes of this object */ (void)sftkdb_GetAttributeValue(handle, id, authAttrs, authAttrCount); count = 0; /* allocate space for the attributes */ - for (i=0; i < authAttrCount; i++) { - if ((authAttrs[i].ulValueLen == -1) || (authAttrs[i].ulValueLen == 0)){ - continue; - } - count++; - authAttrs[i].pValue = PORT_ArenaAlloc(arena,authAttrs[i].ulValueLen); - if (authAttrs[i].pValue == NULL) { - break; - } + for (i = 0; i < authAttrCount; i++) { + if ((authAttrs[i].ulValueLen == -1) || (authAttrs[i].ulValueLen == 0)) { + continue; + } + count++; + authAttrs[i].pValue = PORT_ArenaAlloc(arena, authAttrs[i].ulValueLen); + if (authAttrs[i].pValue == NULL) { + break; + } } /* if count was zero, none were found, finished with MACs */ if (count == 0) { - return CKR_OK; + return CKR_OK; } (void)sftkdb_GetAttributeValue(handle, id, authAttrs, authAttrCount); @@ -924,48 +917,49 @@ sftk_updateMacs(PLArenaPool *arena, SFTKDBHandle *handle, /* GetAttributeValue just verified the old macs, safe to write * them out then... */ - for (i=0; i < authAttrCount; i++) { - SECItem *signText; - SECItem plainText; - SECStatus rv; - - if ((authAttrs[i].ulValueLen == -1) || (authAttrs[i].ulValueLen == 0)){ - continue; - } - - plainText.data = authAttrs[i].pValue; - plainText.len = authAttrs[i].ulValueLen; - rv = sftkdb_SignAttribute(arena, newKey, id, - authAttrs[i].type, &plainText, &signText); - if (rv != SECSuccess) { - return CKR_GENERAL_ERROR; - } - rv = sftkdb_PutAttributeSignature(handle, keyTarget, id, - authAttrs[i].type, signText); - if (rv != SECSuccess) { - return CKR_GENERAL_ERROR; - } + for (i = 0; i < authAttrCount; i++) { + SECItem *signText; + SECItem plainText; + SECStatus rv; + + if ((authAttrs[i].ulValueLen == -1) || (authAttrs[i].ulValueLen == 0)) { + continue; + } + + plainText.data = authAttrs[i].pValue; + plainText.len = authAttrs[i].ulValueLen; + rv = sftkdb_SignAttribute(arena, newKey, id, + authAttrs[i].type, &plainText, &signText); + if (rv != SECSuccess) { + return CKR_GENERAL_ERROR; + } + rv = sftkdb_PutAttributeSignature(handle, keyTarget, id, + authAttrs[i].type, signText); + if (rv != SECSuccess) { + return CKR_GENERAL_ERROR; + } } return CKR_OK; } - + static CK_RV sftk_updateEncrypted(PLArenaPool *arena, SFTKDBHandle *keydb, - CK_OBJECT_HANDLE id, SECItem *newKey) + CK_OBJECT_HANDLE id, SECItem *newKey) { CK_RV crv = CKR_OK; CK_RV crv2; CK_ATTRIBUTE *first, *last; CK_ATTRIBUTE privAttrs[] = { - {CKA_VALUE, NULL, 0}, - {CKA_PRIVATE_EXPONENT, NULL, 0}, - {CKA_PRIME_1, NULL, 0}, - {CKA_PRIME_2, NULL, 0}, - {CKA_EXPONENT_1, NULL, 0}, - {CKA_EXPONENT_2, NULL, 0}, - {CKA_COEFFICIENT, NULL, 0} }; - CK_ULONG privAttrCount = sizeof(privAttrs)/sizeof(CK_ATTRIBUTE); + { CKA_VALUE, NULL, 0 }, + { CKA_PRIVATE_EXPONENT, NULL, 0 }, + { CKA_PRIME_1, NULL, 0 }, + { CKA_PRIME_2, NULL, 0 }, + { CKA_EXPONENT_1, NULL, 0 }, + { CKA_EXPONENT_2, NULL, 0 }, + { CKA_COEFFICIENT, NULL, 0 } + }; + CK_ULONG privAttrCount = sizeof(privAttrs) / sizeof(CK_ATTRIBUTE); unsigned int i, count; /* @@ -980,74 +974,74 @@ sftk_updateEncrypted(PLArenaPool *arena, SFTKDBHandle *keydb, * find the valid block of attributes and fill allocate space for * their data */ first = last = NULL; - for (i=0; i < privAttrCount; i++) { - /* find the block of attributes that are appropriate for this - * objects. There should only be once contiguous block, if not + for (i = 0; i < privAttrCount; i++) { + /* find the block of attributes that are appropriate for this + * objects. There should only be once contiguous block, if not * there's an error. * * find the first and last good entry. */ - if ((privAttrs[i].ulValueLen == -1) || (privAttrs[i].ulValueLen == 0)){ - if (!first) continue; - if (!last) { - /* previous entry was last good entry */ - last= &privAttrs[i-1]; - } - continue; - } - if (!first) { - first = &privAttrs[i]; - } - if (last) { - /* OOPS, we've found another good entry beyond the end of the - * last good entry, we need to fail here. */ - crv = CKR_GENERAL_ERROR; - break; - } - privAttrs[i].pValue = PORT_ArenaAlloc(arena,privAttrs[i].ulValueLen); - if (privAttrs[i].pValue == NULL) { - crv = CKR_HOST_MEMORY; - break; - } + if ((privAttrs[i].ulValueLen == -1) || (privAttrs[i].ulValueLen == 0)) { + if (!first) + continue; + if (!last) { + /* previous entry was last good entry */ + last = &privAttrs[i - 1]; + } + continue; + } + if (!first) { + first = &privAttrs[i]; + } + if (last) { + /* OOPS, we've found another good entry beyond the end of the + * last good entry, we need to fail here. */ + crv = CKR_GENERAL_ERROR; + break; + } + privAttrs[i].pValue = PORT_ArenaAlloc(arena, privAttrs[i].ulValueLen); + if (privAttrs[i].pValue == NULL) { + crv = CKR_HOST_MEMORY; + break; + } } if (first == NULL) { - /* no valid entries found, return error based on crv2 */ - return crv2; + /* no valid entries found, return error based on crv2 */ + return crv2; } if (last == NULL) { - last = &privAttrs[privAttrCount-1]; + last = &privAttrs[privAttrCount - 1]; } if (crv != CKR_OK) { - return crv; + return crv; } /* read the attributes */ - count = (last-first)+1; + count = (last - first) + 1; crv = sftkdb_GetAttributeValue(keydb, id, first, count); if (crv != CKR_OK) { - return crv; + return crv; } /* * STEP 2: read the encrypt the attributes with the new key. */ - for (i=0; i < count; i++) { - SECItem plainText; - SECItem *result; - SECStatus rv; - - plainText.data = first[i].pValue; - plainText.len = first[i].ulValueLen; - rv = sftkdb_EncryptAttribute(arena, newKey, &plainText, &result); - if (rv != SECSuccess) { - return CKR_GENERAL_ERROR; - } - first[i].pValue = result->data; - first[i].ulValueLen = result->len; - /* clear our sensitive data out */ - PORT_Memset(plainText.data, 0, plainText.len); + for (i = 0; i < count; i++) { + SECItem plainText; + SECItem *result; + SECStatus rv; + + plainText.data = first[i].pValue; + plainText.len = first[i].ulValueLen; + rv = sftkdb_EncryptAttribute(arena, newKey, &plainText, &result); + if (rv != SECSuccess) { + return CKR_GENERAL_ERROR; + } + first[i].pValue = result->data; + first[i].ulValueLen = result->len; + /* clear our sensitive data out */ + PORT_Memset(plainText.data, 0, plainText.len); } - /* * STEP 3: write the newly encrypted attributes out directly */ @@ -1058,10 +1052,10 @@ sftk_updateEncrypted(PLArenaPool *arena, SFTKDBHandle *keydb, return crv; } - + static CK_RV -sftk_convertAttributes(SFTKDBHandle *handle, - CK_OBJECT_HANDLE id, SECItem *newKey) +sftk_convertAttributes(SFTKDBHandle *handle, + CK_OBJECT_HANDLE id, SECItem *newKey) { CK_RV crv = CKR_OK; PLArenaPool *arena = NULL; @@ -1069,7 +1063,7 @@ sftk_convertAttributes(SFTKDBHandle *handle, /* get a new arena to simplify cleanup */ arena = PORT_NewArena(1024); if (!arena) { - return CKR_HOST_MEMORY; + return CKR_HOST_MEMORY; } /* @@ -1077,14 +1071,14 @@ sftk_convertAttributes(SFTKDBHandle *handle, */ crv = sftk_updateMacs(arena, handle, id, newKey); if (crv != CKR_OK) { - goto loser; + goto loser; } if (handle->type == SFTK_KEYDB_TYPE) { - crv = sftk_updateEncrypted(arena, handle, id, newKey); - if (crv != CKR_OK) { - goto loser; - } + crv = sftk_updateEncrypted(arena, handle, id, newKey); + if (crv != CKR_OK) { + goto loser; + } } /* free up our mess */ @@ -1098,13 +1092,12 @@ loser: return crv; } - /* * must be called with the old key active. */ CK_RV -sftkdb_convertObjects(SFTKDBHandle *handle, CK_ATTRIBUTE *template, - CK_ULONG count, SECItem *newKey) +sftkdb_convertObjects(SFTKDBHandle *handle, CK_ATTRIBUTE *template, + CK_ULONG count, SECItem *newKey) { SDBFind *find = NULL; CK_ULONG idCount = SFTK_MAX_IDS; @@ -1115,26 +1108,26 @@ sftkdb_convertObjects(SFTKDBHandle *handle, CK_ATTRIBUTE *template, crv = sftkdb_FindObjectsInit(handle, template, count, &find); if (crv != CKR_OK) { - return crv; + return crv; } while ((crv == CKR_OK) && (idCount == SFTK_MAX_IDS)) { - crv = sftkdb_FindObjects(handle, find, ids, SFTK_MAX_IDS, &idCount); - for (i=0; (crv == CKR_OK) && (i < idCount); i++) { - crv = sftk_convertAttributes(handle, ids[i], newKey); - } + crv = sftkdb_FindObjects(handle, find, ids, SFTK_MAX_IDS, &idCount); + for (i = 0; (crv == CKR_OK) && (i < idCount); i++) { + crv = sftk_convertAttributes(handle, ids[i], newKey); + } } crv2 = sftkdb_FindObjectsFinal(handle, find); - if (crv == CKR_OK) crv = crv2; + if (crv == CKR_OK) + crv = crv2; return crv; } - /* * change the database password. */ SECStatus -sftkdb_ChangePassword(SFTKDBHandle *keydb, +sftkdb_ChangePassword(SFTKDBHandle *keydb, char *oldPin, char *newPin, PRBool *tokenRemoved) { SECStatus rv = SECSuccess; @@ -1149,12 +1142,12 @@ sftkdb_ChangePassword(SFTKDBHandle *keydb, SDB *db; if (keydb == NULL) { - return SECFailure; + return SECFailure; } db = SFTK_GET_SDB(keydb); if (db == NULL) { - return SECFailure; + return SECFailure; } newKey.data = NULL; @@ -1162,8 +1155,8 @@ sftkdb_ChangePassword(SFTKDBHandle *keydb, /* make sure we have a valid old pin */ crv = (*keydb->db->sdb_Begin)(keydb->db); if (crv != CKR_OK) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } salt.data = saltData; salt.len = sizeof(saltData); @@ -1171,68 +1164,66 @@ sftkdb_ChangePassword(SFTKDBHandle *keydb, value.len = sizeof(valueData); crv = (*db->sdb_GetMetaData)(db, "password", &salt, &value); if (crv == CKR_OK) { - rv = sftkdb_CheckPassword(keydb, oldPin, tokenRemoved); - if (rv == SECFailure) { - goto loser; - } + rv = sftkdb_CheckPassword(keydb, oldPin, tokenRemoved); + if (rv == SECFailure) { + goto loser; + } } else { - salt.len = SHA1_LENGTH; - RNG_GenerateGlobalRandomBytes(salt.data,salt.len); + salt.len = SHA1_LENGTH; + RNG_GenerateGlobalRandomBytes(salt.data, salt.len); } rv = sftkdb_passwordToKey(keydb, &salt, newPin, &newKey); if (rv != SECSuccess) { - goto loser; + goto loser; } - /* * convert encrypted entries here. */ crv = sftkdb_convertObjects(keydb, NULL, 0, &newKey); if (crv != CKR_OK) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } /* fix up certdb macs */ certdb = keydb->peerDB; if (certdb) { - CK_ATTRIBUTE objectType = { CKA_CLASS, 0, sizeof(CK_OBJECT_CLASS) }; - CK_OBJECT_CLASS myClass = CKO_NETSCAPE_TRUST; - - objectType.pValue = &myClass; - crv = sftkdb_convertObjects(certdb, &objectType, 1, &newKey); - if (crv != CKR_OK) { - rv = SECFailure; - goto loser; - } - myClass = CKO_PUBLIC_KEY; - crv = sftkdb_convertObjects(certdb, &objectType, 1, &newKey); - if (crv != CKR_OK) { - rv = SECFailure; - goto loser; - } + CK_ATTRIBUTE objectType = { CKA_CLASS, 0, sizeof(CK_OBJECT_CLASS) }; + CK_OBJECT_CLASS myClass = CKO_NETSCAPE_TRUST; + + objectType.pValue = &myClass; + crv = sftkdb_convertObjects(certdb, &objectType, 1, &newKey); + if (crv != CKR_OK) { + rv = SECFailure; + goto loser; + } + myClass = CKO_PUBLIC_KEY; + crv = sftkdb_convertObjects(certdb, &objectType, 1, &newKey); + if (crv != CKR_OK) { + rv = SECFailure; + goto loser; + } } - plainText.data = (unsigned char *)SFTK_PW_CHECK_STRING; plainText.len = SFTK_PW_CHECK_LEN; rv = sftkdb_EncryptAttribute(NULL, &newKey, &plainText, &result); if (rv != SECSuccess) { - goto loser; + goto loser; } value.data = result->data; value.len = result->len; crv = (*keydb->db->sdb_PutMetaData)(keydb->db, "password", &salt, &value); if (crv != CKR_OK) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } crv = (*keydb->db->sdb_Commit)(keydb->db); if (crv != CKR_OK) { - rv = SECFailure; - goto loser; + rv = SECFailure; + goto loser; } keydb->newKey = NULL; @@ -1241,15 +1232,15 @@ sftkdb_ChangePassword(SFTKDBHandle *keydb, loser: if (newKey.data) { - PORT_ZFree(newKey.data,newKey.len); + PORT_ZFree(newKey.data, newKey.len); } if (result) { - SECITEM_FreeItem(result, PR_TRUE); + SECITEM_FreeItem(result, PR_TRUE); } if (rv != SECSuccess) { (*keydb->db->sdb_Abort)(keydb->db); } - + return rv; } @@ -1264,9 +1255,7 @@ sftkdb_ClearPassword(SFTKDBHandle *keydb) oldKey.len = 0; sftkdb_switchKeys(keydb, &oldKey); if (oldKey.data) { - PORT_ZFree(oldKey.data, oldKey.len); + PORT_ZFree(oldKey.data, oldKey.len); } return SECSuccess; } - - diff --git a/nss/lib/softoken/softkver.h b/nss/lib/softoken/softkver.h index c7e25e1..cbdd29b 100644 --- a/nss/lib/softoken/softkver.h +++ b/nss/lib/softoken/softkver.h @@ -9,11 +9,7 @@ #define _SOFTKVER_H_ #ifndef NSS_DISABLE_ECC -#ifdef NSS_ECC_MORE_THAN_SUITE_B -#define SOFTOKEN_ECC_STRING " Extended ECC" -#else #define SOFTOKEN_ECC_STRING " Basic ECC" -#endif #else #define SOFTOKEN_ECC_STRING "" #endif @@ -25,11 +21,11 @@ * The format of the version string should be * "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]" */ -#define SOFTOKEN_VERSION "3.21" SOFTOKEN_ECC_STRING -#define SOFTOKEN_VMAJOR 3 -#define SOFTOKEN_VMINOR 21 -#define SOFTOKEN_VPATCH 0 -#define SOFTOKEN_VBUILD 0 -#define SOFTOKEN_BETA PR_FALSE +#define SOFTOKEN_VERSION "3.28.1" SOFTOKEN_ECC_STRING +#define SOFTOKEN_VMAJOR 3 +#define SOFTOKEN_VMINOR 28 +#define SOFTOKEN_VPATCH 1 +#define SOFTOKEN_VBUILD 0 +#define SOFTOKEN_BETA PR_FALSE #endif /* _SOFTKVER_H_ */ diff --git a/nss/lib/softoken/softoken.gyp b/nss/lib/softoken/softoken.gyp new file mode 100644 index 0000000..8d72e60 --- /dev/null +++ b/nss/lib/softoken/softoken.gyp @@ -0,0 +1,71 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +{ + 'includes': [ + '../../coreconf/config.gypi' + ], + 'targets': [ + { + 'target_name': 'softokn', + 'type': 'static_library', + 'sources': [ + 'fipsaudt.c', + 'fipstest.c', + 'fipstokn.c', + 'jpakesftk.c', + 'lgglue.c', + 'lowkey.c', + 'lowpbe.c', + 'padbuf.c', + 'pkcs11.c', + 'pkcs11c.c', + 'pkcs11u.c', + 'sdb.c', + 'sftkdb.c', + 'sftkhmac.c', + 'sftkpars.c', + 'sftkpwd.c', + 'softkver.c', + 'tlsprf.c' + ], + 'dependencies': [ + '<(DEPTH)/exports.gyp:nss_exports', + '<(DEPTH)/lib/sqlite/sqlite.gyp:sqlite3', + '<(DEPTH)/lib/freebl/freebl.gyp:freebl', + ] + }, + { + 'target_name': 'softokn3', + 'type': 'shared_library', + 'dependencies': [ + 'softokn', + ], + 'conditions': [ + [ 'moz_fold_libs==0', { + 'dependencies': [ + '<(DEPTH)/lib/util/util.gyp:nssutil3', + ], + }, { + 'libraries': [ + '<(moz_folded_library_name)', + ], + }], + ], + 'variables': { + 'mapfile': 'softokn.def' + } + } + ], + 'target_defaults': { + 'defines': [ + 'SHLIB_SUFFIX=\"<(dll_suffix)\"', + 'SHLIB_PREFIX=\"<(dll_prefix)\"', + 'SOFTOKEN_LIB_NAME=\"libsoftokn3.so\"', + 'SHLIB_VERSION=\"3\"' + ] + }, + 'variables': { + 'module': 'nss' + } +} diff --git a/nss/lib/softoken/softoken.h b/nss/lib/softoken/softoken.h index fbd00b6..0e943d3 100644 --- a/nss/lib/softoken/softoken.h +++ b/nss/lib/softoken/softoken.h @@ -36,7 +36,7 @@ RSA_HashCheckSign(SECOidTag hashOid, NSSLOWKEYPublicKey *key, const unsigned char *hash, unsigned int hashLen); /* -** Prepare a buffer for padded CBC encryption, growing to the appropriate +** Prepare a buffer for padded CBC encryption, growing to the appropriate ** boundary, filling with the appropriate padding. ** ** blockSize must be a power of 2. @@ -48,21 +48,20 @@ RSA_HashCheckSign(SECOidTag hashOid, NSSLOWKEYPublicKey *key, ** NOTE: If arena is non-NULL, we re-allocate from there, otherwise ** we assume (and use) PR memory (re)allocation. */ -extern unsigned char * CBC_PadBuffer(PLArenaPool *arena, unsigned char *inbuf, - unsigned int inlen, unsigned int *outlen, - int blockSize); - +extern unsigned char *CBC_PadBuffer(PLArenaPool *arena, unsigned char *inbuf, + unsigned int inlen, unsigned int *outlen, + int blockSize); /****************************************/ /* -** Power-Up selftests required for FIPS and invoked only -** under PKCS #11 FIPS mode. +** Power-Up selftests are required for FIPS. */ -extern CK_RV sftk_fipsPowerUpSelfTest( void ); +/* make sure Power-up selftests have been run. */ +extern CK_RV sftk_FIPSEntryOK(void); /* ** make known fixed PKCS #11 key types to their sizes in bytes -*/ +*/ unsigned long sftk_MapKeySize(CK_KEY_TYPE keyType); /* @@ -70,73 +69,73 @@ unsigned long sftk_MapKeySize(CK_KEY_TYPE keyType); */ extern PRBool sftk_audit_enabled; -extern void sftk_LogAuditMessage(NSSAuditSeverity severity, - NSSAuditType, const char *msg); +extern void sftk_LogAuditMessage(NSSAuditSeverity severity, + NSSAuditType, const char *msg); extern void sftk_AuditCreateObject(CK_SESSION_HANDLE hSession, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phObject, CK_RV rv); + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phObject, CK_RV rv); extern void sftk_AuditCopyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phNewObject, CK_RV rv); + CK_OBJECT_HANDLE hObject, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phNewObject, CK_RV rv); extern void sftk_AuditDestroyObject(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_RV rv); + CK_OBJECT_HANDLE hObject, CK_RV rv); extern void sftk_AuditGetObjectSize(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize, - CK_RV rv); + CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize, + CK_RV rv); extern void sftk_AuditGetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_RV rv); + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_RV rv); extern void sftk_AuditSetAttributeValue(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, - CK_ULONG ulCount, CK_RV rv); + CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, + CK_ULONG ulCount, CK_RV rv); extern void sftk_AuditCryptInit(const char *opName, - CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hKey, CK_RV rv); + CK_SESSION_HANDLE hSession, + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hKey, CK_RV rv); extern void sftk_AuditGenerateKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, - CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); + CK_MECHANISM_PTR pMechanism, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, + CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); extern void sftk_AuditGenerateKeyPair(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_ATTRIBUTE_PTR pPublicKeyTemplate, - CK_ULONG ulPublicKeyAttributeCount, - CK_ATTRIBUTE_PTR pPrivateKeyTemplate, - CK_ULONG ulPrivateKeyAttributeCount, - CK_OBJECT_HANDLE_PTR phPublicKey, - CK_OBJECT_HANDLE_PTR phPrivateKey, CK_RV rv); + CK_MECHANISM_PTR pMechanism, + CK_ATTRIBUTE_PTR pPublicKeyTemplate, + CK_ULONG ulPublicKeyAttributeCount, + CK_ATTRIBUTE_PTR pPrivateKeyTemplate, + CK_ULONG ulPrivateKeyAttributeCount, + CK_OBJECT_HANDLE_PTR phPublicKey, + CK_OBJECT_HANDLE_PTR phPrivateKey, CK_RV rv); extern void sftk_AuditWrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, - CK_BYTE_PTR pWrappedKey, - CK_ULONG_PTR pulWrappedKeyLen, CK_RV rv); + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, + CK_BYTE_PTR pWrappedKey, + CK_ULONG_PTR pulWrappedKeyLen, CK_RV rv); extern void sftk_AuditUnwrapKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hUnwrappingKey, - CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hUnwrappingKey, + CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); extern void sftk_AuditDeriveKey(CK_SESSION_HANDLE hSession, - CK_MECHANISM_PTR pMechanism, - CK_OBJECT_HANDLE hBaseKey, - CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, - CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); + CK_MECHANISM_PTR pMechanism, + CK_OBJECT_HANDLE hBaseKey, + CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, + CK_OBJECT_HANDLE_PTR phKey, CK_RV rv); extern void sftk_AuditDigestKey(CK_SESSION_HANDLE hSession, - CK_OBJECT_HANDLE hKey, CK_RV rv); + CK_OBJECT_HANDLE hKey, CK_RV rv); /* ** FIPS 140-2 Error state @@ -150,12 +149,12 @@ extern PRBool sftk_fatalError; #ifdef DEBUG -#define FORK_ASSERT() \ - { \ - char* forkAssert = getenv("NSS_STRICT_NOFORK"); \ - if ( (!forkAssert) || (0 == strcmp(forkAssert, "1")) ) { \ - PORT_Assert(0); \ - } \ +#define FORK_ASSERT() \ + { \ + char *forkAssert = PR_GetEnvSecure("NSS_STRICT_NOFORK"); \ + if ((!forkAssert) || (0 == strcmp(forkAssert, "1"))) { \ + PORT_Assert(0); \ + } \ } #else @@ -170,8 +169,8 @@ extern PRBool sftk_fatalError; * - getpid method */ -#if !defined (CHECK_FORK_MIXED) && !defined(CHECK_FORK_PTHREAD) && \ - !defined (CHECK_FORK_GETPID) +#if !defined(CHECK_FORK_MIXED) && !defined(CHECK_FORK_PTHREAD) && \ + !defined(CHECK_FORK_GETPID) /* Choose fork check method automatically unless specified * This section should be updated as more platforms get pthread fixes @@ -221,31 +220,32 @@ extern PRBool forked; extern pid_t myPid; #define PARENT_FORKED() (myPid && myPid != getpid()) - + #endif extern PRBool parentForkedAfterC_Initialize; extern PRBool sftkForkCheckDisabled; -#define CHECK_FORK() \ - do { \ +#define CHECK_FORK() \ + do { \ if (!sftkForkCheckDisabled && PARENT_FORKED()) { \ - FORK_ASSERT(); \ - return CKR_DEVICE_ERROR; \ - } \ + FORK_ASSERT(); \ + return CKR_DEVICE_ERROR; \ + } \ } while (0) -#define SKIP_AFTER_FORK(x) if (!parentForkedAfterC_Initialize) x +#define SKIP_AFTER_FORK(x) \ + if (!parentForkedAfterC_Initialize) \ + x -#define ENABLE_FORK_CHECK() \ - { \ - char* doForkCheck = getenv("NSS_STRICT_NOFORK"); \ - if ( doForkCheck && !strcmp(doForkCheck, "DISABLED") ) { \ - sftkForkCheckDisabled = PR_TRUE; \ - } \ +#define ENABLE_FORK_CHECK() \ + { \ + char *doForkCheck = PR_GetEnvSecure("NSS_STRICT_NOFORK"); \ + if (doForkCheck && !strcmp(doForkCheck, "DISABLED")) { \ + sftkForkCheckDisabled = PR_TRUE; \ + } \ } - #else /* non-Unix platforms, or fork check disabled */ @@ -260,7 +260,6 @@ extern PRBool sftkForkCheckDisabled; #endif - SEC_END_PROTOS #endif /* _SOFTOKEN_H_ */ diff --git a/nss/lib/softoken/softokn.def b/nss/lib/softoken/softokn.def index 24c5915..0c71a1b 100644 --- a/nss/lib/softoken/softokn.def +++ b/nss/lib/softoken/softokn.def @@ -5,13 +5,13 @@ ;+# ;+# OK, this file is meant to support SUN, LINUX, AIX and WINDOWS ;+# 1. For all unix platforms, the string ";-" means "remove this line" -;+# 2. For all unix platforms, the string " DATA " will be removed from any +;+# 2. For all unix platforms, the string " DATA " will be removed from any ;+# line on which it occurs. ;+# 3. Lines containing ";+" will have ";+" removed on SUN and LINUX. -;+# On AIX, lines containing ";+" will be removed. +;+# On AIX, lines containing ";+" will be removed. ;+# 4. For all unix platforms, the string ";;" will thave the ";;" removed. ;+# 5. For all unix platforms, after the above processing has taken place, -;+# all characters after the first ";" on the line will be removed. +;+# all characters after the first ";" on the line will be removed. ;+# And for AIX, the first ";" will also be removed. ;+# This file is passed directly to windows. Since ';' is a comment, all UNIX ;+# directives are hidden behind ";", ";+", and ";-" diff --git a/nss/lib/softoken/softoknt.h b/nss/lib/softoken/softoknt.h index 67dc294..0716898 100644 --- a/nss/lib/softoken/softoknt.h +++ b/nss/lib/softoken/softoknt.h @@ -8,15 +8,15 @@ #ifndef _SOFTOKNT_H_ #define _SOFTOKNT_H_ -#define NSS_SOFTOKEN_DEFAULT_CHUNKSIZE 2048 +#define NSS_SOFTOKEN_DEFAULT_CHUNKSIZE 2048 /* * FIPS 140-2 auditing */ typedef enum { - NSS_AUDIT_ERROR = 3, /* errors */ - NSS_AUDIT_WARNING = 2, /* warning messages */ - NSS_AUDIT_INFO = 1 /* informational messages */ + NSS_AUDIT_ERROR = 3, /* errors */ + NSS_AUDIT_WARNING = 2, /* warning messages */ + NSS_AUDIT_INFO = 1 /* informational messages */ } NSSAuditSeverity; typedef enum { diff --git a/nss/lib/softoken/tlsprf.c b/nss/lib/softoken/tlsprf.c index 0ebad60..05e2468 100644 --- a/nss/lib/softoken/tlsprf.c +++ b/nss/lib/softoken/tlsprf.c @@ -8,71 +8,70 @@ #include "blapi.h" #include "secerr.h" -#define SFTK_OFFSETOF(str, memb) ((PRPtrdiff)(&(((str *)0)->memb))) - -static void sftk_TLSPRFNull(void *data, PRBool freeit) +static void +sftk_TLSPRFNull(void *data, PRBool freeit) { return; -} +} typedef struct { - PRUint32 cxSize; /* size of allocated block, in bytes. */ - PRUint32 cxBufSize; /* sizeof buffer at cxBufPtr. */ - unsigned char *cxBufPtr; /* points to real buffer, may be cxBuf. */ - PRUint32 cxKeyLen; /* bytes of cxBufPtr containing key. */ - PRUint32 cxDataLen; /* bytes of cxBufPtr containing data. */ - SECStatus cxRv; /* records failure of void functions. */ - PRBool cxIsFIPS; /* true if conforming to FIPS 198. */ - HASH_HashType cxHashAlg; /* hash algorithm to use for TLS 1.2+ */ - unsigned int cxOutLen; /* bytes of output if nonzero */ - unsigned char cxBuf[512]; /* actual size may be larger than 512. */ + PRUint32 cxSize; /* size of allocated block, in bytes. */ + PRUint32 cxBufSize; /* sizeof buffer at cxBufPtr. */ + unsigned char *cxBufPtr; /* points to real buffer, may be cxBuf. */ + PRUint32 cxKeyLen; /* bytes of cxBufPtr containing key. */ + PRUint32 cxDataLen; /* bytes of cxBufPtr containing data. */ + SECStatus cxRv; /* records failure of void functions. */ + PRBool cxIsFIPS; /* true if conforming to FIPS 198. */ + HASH_HashType cxHashAlg; /* hash algorithm to use for TLS 1.2+ */ + unsigned int cxOutLen; /* bytes of output if nonzero */ + unsigned char cxBuf[512]; /* actual size may be larger than 512. */ } TLSPRFContext; static void -sftk_TLSPRFHashUpdate(TLSPRFContext *cx, const unsigned char *data, - unsigned int data_len) +sftk_TLSPRFHashUpdate(TLSPRFContext *cx, const unsigned char *data, + unsigned int data_len) { PRUint32 bytesUsed = cx->cxKeyLen + cx->cxDataLen; - if (cx->cxRv != SECSuccess) /* function has previously failed. */ - return; + if (cx->cxRv != SECSuccess) /* function has previously failed. */ + return; if (bytesUsed + data_len > cx->cxBufSize) { - /* We don't use realloc here because - ** (a) realloc doesn't zero out the old block, and - ** (b) if realloc fails, we lose the old block. - */ - PRUint32 newBufSize = bytesUsed + data_len + 512; - unsigned char * newBuf = (unsigned char *)PORT_Alloc(newBufSize); - if (!newBuf) { - cx->cxRv = SECFailure; - return; - } - PORT_Memcpy(newBuf, cx->cxBufPtr, bytesUsed); - if (cx->cxBufPtr != cx->cxBuf) { - PORT_ZFree(cx->cxBufPtr, bytesUsed); - } - cx->cxBufPtr = newBuf; - cx->cxBufSize = newBufSize; + /* We don't use realloc here because + ** (a) realloc doesn't zero out the old block, and + ** (b) if realloc fails, we lose the old block. + */ + PRUint32 newBufSize = bytesUsed + data_len + 512; + unsigned char *newBuf = (unsigned char *)PORT_Alloc(newBufSize); + if (!newBuf) { + cx->cxRv = SECFailure; + return; + } + PORT_Memcpy(newBuf, cx->cxBufPtr, bytesUsed); + if (cx->cxBufPtr != cx->cxBuf) { + PORT_ZFree(cx->cxBufPtr, bytesUsed); + } + cx->cxBufPtr = newBuf; + cx->cxBufSize = newBufSize; } PORT_Memcpy(cx->cxBufPtr + bytesUsed, data, data_len); cx->cxDataLen += data_len; } -static void +static void sftk_TLSPRFEnd(TLSPRFContext *ctx, unsigned char *hashout, - unsigned int *pDigestLen, unsigned int maxDigestLen) + unsigned int *pDigestLen, unsigned int maxDigestLen) { *pDigestLen = 0; /* tells Verify that no data has been input yet. */ } /* Compute the PRF values from the data previously input. */ static SECStatus -sftk_TLSPRFUpdate(TLSPRFContext *cx, - unsigned char *sig, /* output goes here. */ - unsigned int * sigLen, /* how much output. */ - unsigned int maxLen, /* output buffer size */ - unsigned char *hash, /* unused. */ - unsigned int hashLen) /* unused. */ +sftk_TLSPRFUpdate(TLSPRFContext *cx, + unsigned char *sig, /* output goes here. */ + unsigned int *sigLen, /* how much output. */ + unsigned int maxLen, /* output buffer size */ + unsigned char *hash, /* unused. */ + unsigned int hashLen) /* unused. */ { SECStatus rv; SECItem sigItem; @@ -80,58 +79,57 @@ sftk_TLSPRFUpdate(TLSPRFContext *cx, SECItem secretItem; if (cx->cxRv != SECSuccess) - return cx->cxRv; + return cx->cxRv; secretItem.data = cx->cxBufPtr; - secretItem.len = cx->cxKeyLen; + secretItem.len = cx->cxKeyLen; seedItem.data = cx->cxBufPtr + cx->cxKeyLen; - seedItem.len = cx->cxDataLen; + seedItem.len = cx->cxDataLen; sigItem.data = sig; if (cx->cxOutLen == 0) { - sigItem.len = maxLen; + sigItem.len = maxLen; } else if (cx->cxOutLen <= maxLen) { - sigItem.len = cx->cxOutLen; + sigItem.len = cx->cxOutLen; } else { - PORT_SetError(SEC_ERROR_OUTPUT_LEN); - return SECFailure; + PORT_SetError(SEC_ERROR_OUTPUT_LEN); + return SECFailure; } if (cx->cxHashAlg != HASH_AlgNULL) { - rv = TLS_P_hash(cx->cxHashAlg, &secretItem, NULL, &seedItem, &sigItem, - cx->cxIsFIPS); + rv = TLS_P_hash(cx->cxHashAlg, &secretItem, NULL, &seedItem, &sigItem, + cx->cxIsFIPS); } else { - rv = TLS_PRF(&secretItem, NULL, &seedItem, &sigItem, cx->cxIsFIPS); + rv = TLS_PRF(&secretItem, NULL, &seedItem, &sigItem, cx->cxIsFIPS); } if (rv == SECSuccess && sigLen != NULL) - *sigLen = sigItem.len; + *sigLen = sigItem.len; return rv; - } static SECStatus -sftk_TLSPRFVerify(TLSPRFContext *cx, - unsigned char *sig, /* input, for comparison. */ - unsigned int sigLen, /* length of sig. */ - unsigned char *hash, /* data to be verified. */ - unsigned int hashLen) /* size of hash data. */ +sftk_TLSPRFVerify(TLSPRFContext *cx, + unsigned char *sig, /* input, for comparison. */ + unsigned int sigLen, /* length of sig. */ + unsigned char *hash, /* data to be verified. */ + unsigned int hashLen) /* size of hash data. */ { - unsigned char * tmp = (unsigned char *)PORT_Alloc(sigLen); - unsigned int tmpLen = sigLen; - SECStatus rv; + unsigned char *tmp = (unsigned char *)PORT_Alloc(sigLen); + unsigned int tmpLen = sigLen; + SECStatus rv; if (!tmp) - return SECFailure; + return SECFailure; if (hashLen) { - /* hashLen is non-zero when the user does a one-step verify. - ** In this case, none of the data has been input yet. - */ - sftk_TLSPRFHashUpdate(cx, hash, hashLen); + /* hashLen is non-zero when the user does a one-step verify. + ** In this case, none of the data has been input yet. + */ + sftk_TLSPRFHashUpdate(cx, hash, hashLen); } rv = sftk_TLSPRFUpdate(cx, tmp, &tmpLen, sigLen, NULL, 0); if (rv == SECSuccess) { - rv = (SECStatus)(1 - !PORT_Memcmp(tmp, sig, sigLen)); + rv = (SECStatus)(1 - !PORT_Memcmp(tmp, sig, sigLen)); } PORT_ZFree(tmp, sigLen); return rv; @@ -141,27 +139,27 @@ static void sftk_TLSPRFHashDestroy(TLSPRFContext *cx, PRBool freeit) { if (freeit) { - if (cx->cxBufPtr != cx->cxBuf) - PORT_ZFree(cx->cxBufPtr, cx->cxBufSize); - PORT_ZFree(cx, cx->cxSize); + if (cx->cxBufPtr != cx->cxBuf) + PORT_ZFree(cx->cxBufPtr, cx->cxBufSize); + PORT_ZFree(cx, cx->cxSize); } } CK_RV -sftk_TLSPRFInit(SFTKSessionContext *context, - SFTKObject * key, - CK_KEY_TYPE key_type, - HASH_HashType hash_alg, - unsigned int out_len) +sftk_TLSPRFInit(SFTKSessionContext *context, + SFTKObject *key, + CK_KEY_TYPE key_type, + HASH_HashType hash_alg, + unsigned int out_len) { - SFTKAttribute * keyVal; - TLSPRFContext * prf_cx; - CK_RV crv = CKR_HOST_MEMORY; - PRUint32 keySize; - PRUint32 blockSize; + SFTKAttribute *keyVal; + TLSPRFContext *prf_cx; + CK_RV crv = CKR_HOST_MEMORY; + PRUint32 keySize; + PRUint32 blockSize; if (key_type != CKK_GENERIC_SECRET) - return CKR_KEY_TYPE_INCONSISTENT; /* CKR_KEY_FUNCTION_NOT_PERMITTED */ + return CKR_KEY_TYPE_INCONSISTENT; /* CKR_KEY_FUNCTION_NOT_PERMITTED */ context->multi = PR_TRUE; @@ -169,33 +167,32 @@ sftk_TLSPRFInit(SFTKSessionContext *context, keySize = (!keyVal) ? 0 : keyVal->attrib.ulValueLen; blockSize = keySize + sizeof(TLSPRFContext); prf_cx = (TLSPRFContext *)PORT_Alloc(blockSize); - if (!prf_cx) - goto done; - prf_cx->cxSize = blockSize; - prf_cx->cxKeyLen = keySize; + if (!prf_cx) + goto done; + prf_cx->cxSize = blockSize; + prf_cx->cxKeyLen = keySize; prf_cx->cxDataLen = 0; - prf_cx->cxBufSize = blockSize - SFTK_OFFSETOF(TLSPRFContext, cxBuf); - prf_cx->cxRv = SECSuccess; - prf_cx->cxIsFIPS = (key->slot->slotID == FIPS_SLOT_ID); - prf_cx->cxBufPtr = prf_cx->cxBuf; + prf_cx->cxBufSize = blockSize - offsetof(TLSPRFContext, cxBuf); + prf_cx->cxRv = SECSuccess; + prf_cx->cxIsFIPS = (key->slot->slotID == FIPS_SLOT_ID); + prf_cx->cxBufPtr = prf_cx->cxBuf; prf_cx->cxHashAlg = hash_alg; - prf_cx->cxOutLen = out_len; + prf_cx->cxOutLen = out_len; if (keySize) - PORT_Memcpy(prf_cx->cxBufPtr, keyVal->attrib.pValue, keySize); - - context->hashInfo = (void *) prf_cx; - context->cipherInfo = (void *) prf_cx; - context->hashUpdate = (SFTKHash) sftk_TLSPRFHashUpdate; - context->end = (SFTKEnd) sftk_TLSPRFEnd; - context->update = (SFTKCipher) sftk_TLSPRFUpdate; - context->verify = (SFTKVerify) sftk_TLSPRFVerify; - context->destroy = (SFTKDestroy) sftk_TLSPRFNull; - context->hashdestroy = (SFTKDestroy) sftk_TLSPRFHashDestroy; + PORT_Memcpy(prf_cx->cxBufPtr, keyVal->attrib.pValue, keySize); + + context->hashInfo = (void *)prf_cx; + context->cipherInfo = (void *)prf_cx; + context->hashUpdate = (SFTKHash)sftk_TLSPRFHashUpdate; + context->end = (SFTKEnd)sftk_TLSPRFEnd; + context->update = (SFTKCipher)sftk_TLSPRFUpdate; + context->verify = (SFTKVerify)sftk_TLSPRFVerify; + context->destroy = (SFTKDestroy)sftk_TLSPRFNull; + context->hashdestroy = (SFTKDestroy)sftk_TLSPRFHashDestroy; crv = CKR_OK; done: - if (keyVal) - sftk_FreeAttribute(keyVal); + if (keyVal) + sftk_FreeAttribute(keyVal); return crv; } - |