diff options
Diffstat (limited to 'security/nss/lib/dev')
-rw-r--r-- | security/nss/lib/dev/Makefile | 53 | ||||
-rw-r--r-- | security/nss/lib/dev/ckhelper.c | 722 | ||||
-rw-r--r-- | security/nss/lib/dev/ckhelper.h | 189 | ||||
-rw-r--r-- | security/nss/lib/dev/config.mk | 48 | ||||
-rw-r--r-- | security/nss/lib/dev/dev.h | 970 | ||||
-rw-r--r-- | security/nss/lib/dev/devm.h | 242 | ||||
-rw-r--r-- | security/nss/lib/dev/devmod.c | 900 | ||||
-rw-r--r-- | security/nss/lib/dev/devslot.c | 834 | ||||
-rw-r--r-- | security/nss/lib/dev/devt.h | 202 | ||||
-rw-r--r-- | security/nss/lib/dev/devtm.h | 58 | ||||
-rw-r--r-- | security/nss/lib/dev/devtoken.c | 1664 | ||||
-rw-r--r-- | security/nss/lib/dev/devutil.c | 1445 | ||||
-rw-r--r-- | security/nss/lib/dev/manifest.mn | 66 | ||||
-rw-r--r-- | security/nss/lib/dev/nssdev.h | 72 | ||||
-rw-r--r-- | security/nss/lib/dev/nssdevt.h | 69 |
15 files changed, 7534 insertions, 0 deletions
diff --git a/security/nss/lib/dev/Makefile b/security/nss/lib/dev/Makefile new file mode 100644 index 000000000..cd7561ce6 --- /dev/null +++ b/security/nss/lib/dev/Makefile @@ -0,0 +1,53 @@ +# +# The contents of this file are subject to the Mozilla Public +# License Version 1.1 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.mozilla.org/MPL/ +# +# Software distributed under the License is distributed on an "AS +# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or +# implied. See the License for the specific language governing +# rights and limitations under the License. +# +# The Original Code is the Netscape security libraries. +# +# The Initial Developer of the Original Code is Netscape +# Communications Corporation. Portions created by Netscape are +# Copyright (C) 1994-2000 Netscape Communications Corporation. All +# Rights Reserved. +# +# Contributor(s): +# +# Alternatively, the contents of this file may be used under the +# terms of the GNU General Public License Version 2 or later (the +# "GPL"), in which case the provisions of the GPL are applicable +# instead of those above. If you wish to allow use of your +# version of this file only under the terms of the GPL and not to +# allow others to use your version of this file under the MPL, +# indicate your decision by deleting the provisions above and +# replace them with the notice and other provisions required by +# the GPL. If you do not delete the provisions above, a recipient +# may use your version of this file under either the MPL or the +# GPL. +# +MAKEFILE_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$" + +include manifest.mn +include $(CORE_DEPTH)/coreconf/config.mk +include config.mk +include $(CORE_DEPTH)/coreconf/rules.mk + +# On AIX 4.3, IBM xlC_r compiler (version 3.6.6) cannot compile +# ckhelper.c in 64-bit mode for unknown reasons. A workaround is +# to compile it with optimizations turned on. (Bugzilla bug #63815) +ifeq ($(OS_TARGET)$(OS_RELEASE),AIX4.3) +ifeq ($(USE_64),1) +ifndef BUILD_OPT +$(OBJDIR)/ckhelper.o: ckhelper.c + @$(MAKE_OBJDIR) + $(CC) -o $@ -c -O2 $(CFLAGS) $< +endif +endif +endif + +export:: private_export diff --git a/security/nss/lib/dev/ckhelper.c b/security/nss/lib/dev/ckhelper.c new file mode 100644 index 000000000..1f3f1e3bc --- /dev/null +++ b/security/nss/lib/dev/ckhelper.c @@ -0,0 +1,722 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifdef DEBUG +static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKEPV_H +#include "nssckepv.h" +#endif /* NSSCKEPV_H */ + +#ifndef DEVM_H +#include "devm.h" +#endif /* DEVM_H */ + +#ifndef CKHELPER_H +#include "ckhelper.h" +#endif /* CKHELPER_H */ + +static const CK_BBOOL s_true = CK_TRUE; +NSS_IMPLEMENT_DATA const NSSItem +g_ck_true = { (CK_VOID_PTR)&s_true, sizeof(s_true) }; + +static const CK_BBOOL s_false = CK_FALSE; +NSS_IMPLEMENT_DATA const NSSItem +g_ck_false = { (CK_VOID_PTR)&s_false, sizeof(s_false) }; + +static const CK_OBJECT_CLASS s_class_cert = CKO_CERTIFICATE; +NSS_IMPLEMENT_DATA const NSSItem +g_ck_class_cert = { (CK_VOID_PTR)&s_class_cert, sizeof(s_class_cert) }; + +static const CK_OBJECT_CLASS s_class_pubkey = CKO_PUBLIC_KEY; +NSS_IMPLEMENT_DATA const NSSItem +g_ck_class_pubkey = { (CK_VOID_PTR)&s_class_pubkey, sizeof(s_class_pubkey) }; + +static const CK_OBJECT_CLASS s_class_privkey = CKO_PRIVATE_KEY; +NSS_IMPLEMENT_DATA const NSSItem +g_ck_class_privkey = { (CK_VOID_PTR)&s_class_privkey, sizeof(s_class_privkey) }; + +static PRBool +is_string_attribute +( + CK_ATTRIBUTE_TYPE aType +) +{ + PRBool isString; + switch (aType) { + case CKA_LABEL: + case CKA_NETSCAPE_EMAIL: + isString = PR_TRUE; + break; + default: + isString = PR_FALSE; + break; + } + return isString; +} + +NSS_IMPLEMENT PRStatus +nssCKObject_GetAttributes +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG count, + NSSArena *arenaOpt, + nssSession *session, + NSSSlot *slot +) +{ + nssArenaMark *mark = NULL; + CK_SESSION_HANDLE hSession; + CK_ULONG i = 0; + CK_RV ckrv; + PRStatus nssrv; + PRBool alloced = PR_FALSE; + void *epv = nssSlot_GetCryptokiEPV(slot); + hSession = session->handle; + if (arenaOpt) { + mark = nssArena_Mark(arenaOpt); + if (!mark) { + goto loser; + } + } + nssSession_EnterMonitor(session); + /* XXX kinda hacky, if the storage size is already in the first template + * item, then skip the alloc portion + */ + if (obj_template[0].ulValueLen == 0) { + /* Get the storage size needed for each attribute */ + ckrv = CKAPI(epv)->C_GetAttributeValue(hSession, + object, obj_template, count); + if (ckrv != CKR_OK && + ckrv != CKR_ATTRIBUTE_TYPE_INVALID && + ckrv != CKR_ATTRIBUTE_SENSITIVE) + { + nssSession_ExitMonitor(session); + /* set an error here */ + goto loser; + } + /* Allocate memory for each attribute. */ + for (i=0; i<count; i++) { + CK_ULONG ulValueLen = obj_template[i].ulValueLen; + if (ulValueLen == 0) continue; + if (ulValueLen == (CK_ULONG) -1) { + obj_template[i].ulValueLen = 0; + continue; + } + if (is_string_attribute(obj_template[i].type)) { + ulValueLen++; + } + obj_template[i].pValue = nss_ZAlloc(arenaOpt, ulValueLen); + if (!obj_template[i].pValue) { + nssSession_ExitMonitor(session); + goto loser; + } + } + alloced = PR_TRUE; + } + /* Obtain the actual attribute values. */ + ckrv = CKAPI(epv)->C_GetAttributeValue(hSession, + object, obj_template, count); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK && + ckrv != CKR_ATTRIBUTE_TYPE_INVALID && + ckrv != CKR_ATTRIBUTE_SENSITIVE) + { + /* set an error here */ + goto loser; + } + if (alloced && arenaOpt) { + nssrv = nssArena_Unmark(arenaOpt, mark); + if (nssrv != PR_SUCCESS) { + goto loser; + } + } + + if (count > 1 && ((ckrv == CKR_ATTRIBUTE_TYPE_INVALID) || + (ckrv == CKR_ATTRIBUTE_SENSITIVE))) { + /* old tokens would keep the length of '0' and not deal with any + * of the attributes we passed. For those tokens read them one at + * a time */ + for (i=0; i < count; i++) { + if ((obj_template[i].ulValueLen == 0) + || (obj_template[i].ulValueLen == -1)) { + obj_template[i].ulValueLen=0; + (void) nssCKObject_GetAttributes(object,&obj_template[i], 1, + arenaOpt, session, slot); + } + } + } + return PR_SUCCESS; +loser: + if (alloced) { + if (arenaOpt) { + /* release all arena memory allocated before the failure. */ + (void)nssArena_Release(arenaOpt, mark); + } else { + CK_ULONG j; + /* free each heap object that was allocated before the failure. */ + for (j=0; j<i; j++) { + nss_ZFreeIf(obj_template[j].pValue); + } + } + } + return PR_FAILURE; +} + +NSS_IMPLEMENT PRStatus +nssCKObject_GetAttributeItem +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_TYPE attribute, + NSSArena *arenaOpt, + nssSession *session, + NSSSlot *slot, + NSSItem *rvItem +) +{ + CK_ATTRIBUTE attr = { 0, NULL, 0 }; + PRStatus nssrv; + attr.type = attribute; + nssrv = nssCKObject_GetAttributes(object, &attr, 1, + arenaOpt, session, slot); + if (nssrv != PR_SUCCESS) { + return nssrv; + } + rvItem->data = (void *)attr.pValue; + rvItem->size = (PRUint32)attr.ulValueLen; + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRBool +nssCKObject_IsAttributeTrue +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_TYPE attribute, + nssSession *session, + NSSSlot *slot, + PRStatus *rvStatus +) +{ + CK_BBOOL bool; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE atemplate = { 0, NULL, 0 }; + CK_RV ckrv; + void *epv = nssSlot_GetCryptokiEPV(slot); + attr = &atemplate; + NSS_CK_SET_ATTRIBUTE_VAR(attr, attribute, bool); + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_GetAttributeValue(session->handle, object, + &atemplate, 1); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK) { + *rvStatus = PR_FAILURE; + return PR_FALSE; + } + *rvStatus = PR_SUCCESS; + return (PRBool)(bool == CK_TRUE); +} + +NSS_IMPLEMENT PRStatus +nssCKObject_SetAttributes +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG count, + nssSession *session, + NSSSlot *slot +) +{ + CK_RV ckrv; + void *epv = nssSlot_GetCryptokiEPV(slot); + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_SetAttributeValue(session->handle, object, + obj_template, count); + nssSession_ExitMonitor(session); + if (ckrv == CKR_OK) { + return PR_SUCCESS; + } else { + return PR_FAILURE; + } +} + +NSS_IMPLEMENT PRBool +nssCKObject_IsTokenObjectTemplate +( + CK_ATTRIBUTE_PTR objectTemplate, + CK_ULONG otsize +) +{ + CK_ULONG ul; + for (ul=0; ul<otsize; ul++) { + if (objectTemplate[ul].type == CKA_TOKEN) { + return (*((CK_BBOOL*)objectTemplate[ul].pValue) == CK_TRUE); + } + } + return PR_FALSE; +} + +static NSSCertificateType +nss_cert_type_from_ck_attrib(CK_ATTRIBUTE_PTR attrib) +{ + CK_CERTIFICATE_TYPE ckCertType; + if (!attrib->pValue) { + /* default to PKIX */ + return NSSCertificateType_PKIX; + } + ckCertType = *((CK_ULONG *)attrib->pValue); + switch (ckCertType) { + case CKC_X_509: + return NSSCertificateType_PKIX; + default: + break; + } + return NSSCertificateType_Unknown; +} + +/* incoming pointers must be valid */ +NSS_IMPLEMENT PRStatus +nssCryptokiCertificate_GetAttributes +( + nssCryptokiObject *certObject, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSCertificateType *certTypeOpt, + NSSItem *idOpt, + NSSDER *encodingOpt, + NSSDER *issuerOpt, + NSSDER *serialOpt, + NSSDER *subjectOpt, + NSSASCII7 **emailOpt +) +{ + PRStatus status; + PRUint32 i; + nssSession *session; + NSSSlot *slot; + CK_ULONG template_size; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE cert_template[7]; + /* Set up a template of all options chosen by caller */ + NSS_CK_TEMPLATE_START(cert_template, attr, template_size); + if (certTypeOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_CERTIFICATE_TYPE); + } + if (idOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_ID); + } + if (encodingOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_VALUE); + } + if (issuerOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_ISSUER); + } + if (serialOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_SERIAL_NUMBER); + } + if (subjectOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_SUBJECT); + } + if (emailOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_NETSCAPE_EMAIL); + } + NSS_CK_TEMPLATE_FINISH(cert_template, attr, template_size); + if (template_size == 0) { + /* caller didn't want anything */ + return PR_SUCCESS; + } + + status = nssToken_GetCachedObjectAttributes(certObject->token, arenaOpt, + certObject, CKO_CERTIFICATE, + cert_template, template_size); + if (status != PR_SUCCESS) { + + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(certObject->token); + + slot = nssToken_GetSlot(certObject->token); + status = nssCKObject_GetAttributes(certObject->handle, + cert_template, template_size, + arenaOpt, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + return status; + } + } + + i=0; + if (certTypeOpt) { + *certTypeOpt = nss_cert_type_from_ck_attrib(&cert_template[i]); i++; + } + if (idOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&cert_template[i], idOpt); i++; + } + if (encodingOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&cert_template[i], encodingOpt); i++; + } + if (issuerOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&cert_template[i], issuerOpt); i++; + } + if (serialOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&cert_template[i], serialOpt); i++; + } + if (subjectOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&cert_template[i], subjectOpt); i++; + } + if (emailOpt) { + NSS_CK_ATTRIBUTE_TO_UTF8(&cert_template[i], *emailOpt); i++; + } + return PR_SUCCESS; +} + +#ifdef PURE_STAN_BUILD +static NSSKeyPairType +nss_key_pair_type_from_ck_attrib(CK_ATTRIBUTE_PTR attrib) +{ + CK_KEY_TYPE ckKeyType; + PR_ASSERT(attrib->pValue); + ckKeyType = *((CK_ULONG *)attrib->pValue); + switch (ckKeyType) { + case CKK_RSA: return NSSKeyPairType_RSA; + case CKK_DSA: return NSSKeyPairType_DSA; + default: break; + } + return NSSKeyPairType_Unknown; +} + +NSS_IMPLEMENT PRStatus +nssCryptokiPrivateKey_GetAttributes +( + nssCryptokiObject *keyObject, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSKeyPairType *keyTypeOpt, + NSSItem *idOpt +) +{ + PRStatus status; + PRUint32 i; + nssSession *session; + NSSSlot *slot; + CK_ULONG template_size; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[2]; + /* Set up a template of all options chosen by caller */ + NSS_CK_TEMPLATE_START(key_template, attr, template_size); + if (keyTypeOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_KEY_TYPE); + } + if (idOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_ID); + } + NSS_CK_TEMPLATE_FINISH(key_template, attr, template_size); + if (template_size == 0) { + /* caller didn't want anything */ + return PR_SUCCESS; + } + + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(keyObject->token); + + slot = nssToken_GetSlot(keyObject->token); + status = nssCKObject_GetAttributes(keyObject->handle, + key_template, template_size, + arenaOpt, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + return status; + } + + i=0; + if (keyTypeOpt) { + *keyTypeOpt = nss_key_pair_type_from_ck_attrib(&key_template[i]); i++; + } + if (idOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&key_template[i], idOpt); i++; + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssCryptokiPublicKey_GetAttributes +( + nssCryptokiObject *keyObject, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSKeyPairType *keyTypeOpt, + NSSItem *idOpt +) +{ + PRStatus status; + PRUint32 i; + nssSession *session; + NSSSlot *slot; + CK_ULONG template_size; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[2]; + /* Set up a template of all options chosen by caller */ + NSS_CK_TEMPLATE_START(key_template, attr, template_size); + if (keyTypeOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_KEY_TYPE); + } + if (idOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_ID); + } + NSS_CK_TEMPLATE_FINISH(key_template, attr, template_size); + if (template_size == 0) { + /* caller didn't want anything */ + return PR_SUCCESS; + } + + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(keyObject->token); + + slot = nssToken_GetSlot(keyObject->token); + status = nssCKObject_GetAttributes(keyObject->handle, + key_template, template_size, + arenaOpt, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + return status; + } + + i=0; + if (keyTypeOpt) { + *keyTypeOpt = nss_key_pair_type_from_ck_attrib(&key_template[i]); i++; + } + if (idOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&key_template[i], idOpt); i++; + } + return PR_SUCCESS; +} +#endif /* PURE_STAN_BUILD */ + +static nssTrustLevel +get_nss_trust +( + CK_TRUST ckt +) +{ + nssTrustLevel t; + switch (ckt) { + case CKT_NETSCAPE_UNTRUSTED: t = nssTrustLevel_NotTrusted; break; + case CKT_NETSCAPE_TRUSTED_DELEGATOR: t = nssTrustLevel_TrustedDelegator; + break; + case CKT_NETSCAPE_VALID_DELEGATOR: t = nssTrustLevel_ValidDelegator; break; + case CKT_NETSCAPE_TRUSTED: t = nssTrustLevel_Trusted; break; + case CKT_NETSCAPE_VALID: t = nssTrustLevel_Valid; break; + case CKT_NETSCAPE_MUST_VERIFY: + case CKT_NETSCAPE_TRUST_UNKNOWN: + default: + t = nssTrustLevel_Unknown; break; + } + return t; +} + +NSS_IMPLEMENT PRStatus +nssCryptokiTrust_GetAttributes +( + nssCryptokiObject *trustObject, + nssSession *sessionOpt, + nssTrustLevel *serverAuth, + nssTrustLevel *clientAuth, + nssTrustLevel *codeSigning, + nssTrustLevel *emailProtection +) +{ + PRStatus status; + NSSSlot *slot; + nssSession *session; + CK_BBOOL isToken; + CK_TRUST saTrust, caTrust, epTrust, csTrust; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE trust_template[5]; + CK_ULONG trust_size; + + /* Use the trust object to find the trust settings */ + NSS_CK_TEMPLATE_START(trust_template, attr, trust_size); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TOKEN, isToken); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_SERVER_AUTH, saTrust); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CLIENT_AUTH, caTrust); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_EMAIL_PROTECTION, epTrust); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CODE_SIGNING, csTrust); + NSS_CK_TEMPLATE_FINISH(trust_template, attr, trust_size); + + status = nssToken_GetCachedObjectAttributes(trustObject->token, NULL, + trustObject, + CKO_NETSCAPE_TRUST, + trust_template, trust_size); + if (status != PR_SUCCESS) { + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(trustObject->token); + + slot = nssToken_GetSlot(trustObject->token); + status = nssCKObject_GetAttributes(trustObject->handle, + trust_template, trust_size, + NULL, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + return status; + } + } + + *serverAuth = get_nss_trust(saTrust); + *clientAuth = get_nss_trust(caTrust); + *emailProtection = get_nss_trust(epTrust); + *codeSigning = get_nss_trust(csTrust); + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssCryptokiCRL_GetAttributes +( + nssCryptokiObject *crlObject, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSItem *encodingOpt, + NSSUTF8 **urlOpt, + PRBool *isKRLOpt +) +{ + PRStatus status; + NSSSlot *slot; + nssSession *session; + CK_BBOOL isToken; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE crl_template[5]; + CK_ULONG crl_size; + PRUint32 i; + + NSS_CK_TEMPLATE_START(crl_template, attr, crl_size); + /* NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TOKEN, isToken); */ + if (encodingOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_VALUE); + } + if (urlOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_NETSCAPE_URL); + } + if (isKRLOpt) { + NSS_CK_SET_ATTRIBUTE_NULL(attr, CKA_NETSCAPE_KRL); + } + NSS_CK_TEMPLATE_FINISH(crl_template, attr, crl_size); + + status = nssToken_GetCachedObjectAttributes(crlObject->token, NULL, + crlObject, + CKO_NETSCAPE_CRL, + crl_template, crl_size); + if (status != PR_SUCCESS) { + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(crlObject->token); + + slot = nssToken_GetSlot(crlObject->token); + status = nssCKObject_GetAttributes(crlObject->handle, + crl_template, crl_size, + arenaOpt, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + return status; + } + } + + i=0; + if (encodingOpt) { + NSS_CK_ATTRIBUTE_TO_ITEM(&crl_template[i], encodingOpt); i++; + } + if (urlOpt) { + NSS_CK_ATTRIBUTE_TO_UTF8(&crl_template[i], *urlOpt); i++; + } + if (isKRLOpt) { + NSS_CK_ATTRIBUTE_TO_BOOL(&crl_template[i], *isKRLOpt); i++; + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssCryptokiPrivateKey_SetCertificate +( + nssCryptokiObject *keyObject, + nssSession *sessionOpt, + NSSUTF8 *nickname, + NSSItem *id, + NSSDER *subject +) +{ + CK_RV ckrv; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[3]; + CK_ULONG key_size; + void *epv = nssToken_GetCryptokiEPV(keyObject->token); + nssSession *session; + NSSToken *token = keyObject->token; + nssSession *defaultSession = nssToken_GetDefaultSession(token); + PRBool createdSession = PR_FALSE; + + NSS_CK_TEMPLATE_START(key_template, attr, key_size); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_LABEL, nickname); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, id); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SUBJECT, subject); + NSS_CK_TEMPLATE_FINISH(key_template, attr, key_size); + + if (sessionOpt) { + if (!nssSession_IsReadWrite(sessionOpt)) { + return PR_FAILURE; + } else { + session = sessionOpt; + } + } else if (nssSession_IsReadWrite(defaultSession)) { + session = defaultSession; + } else { + NSSSlot *slot = nssToken_GetSlot(token); + session = nssSlot_CreateSession(token->slot, NULL, PR_TRUE); + createdSession = PR_TRUE; + nssSlot_Destroy(slot); + } + + ckrv = CKAPI(epv)->C_SetAttributeValue(session->handle, + keyObject->handle, + key_template, + key_size); + + if (createdSession) { + nssSession_Destroy(session); + } + + return (ckrv == CKR_OK) ? PR_SUCCESS : PR_FAILURE; +} + diff --git a/security/nss/lib/dev/ckhelper.h b/security/nss/lib/dev/ckhelper.h new file mode 100644 index 000000000..9beab920d --- /dev/null +++ b/security/nss/lib/dev/ckhelper.h @@ -0,0 +1,189 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +/* + * ckhelper.h + * + * This file contains some helper utilities for interaction with cryptoki. + */ + +#ifndef CKHELPER_H +#define CKHELPER_H + +#ifdef DEBUG +static const char CKHELPER_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKT_H +#include "nssckt.h" +#endif /* NSSCKT_H */ + +PR_BEGIN_EXTERN_C + +/* Some globals to keep from constantly redeclaring common cryptoki + * attribute types on the stack. + */ + +/* Boolean values */ +NSS_EXTERN_DATA const NSSItem g_ck_true; +NSS_EXTERN_DATA const NSSItem g_ck_false; + +/* Object classes */ +NSS_EXTERN_DATA const NSSItem g_ck_class_cert; +NSS_EXTERN_DATA const NSSItem g_ck_class_pubkey; +NSS_EXTERN_DATA const NSSItem g_ck_class_privkey; + +#define NSS_CK_TEMPLATE_START(_template, attr, size) \ + attr = _template; \ + size = 0; + +#define NSS_CK_SET_ATTRIBUTE_ITEM(pattr, kind, item) \ + (pattr)->type = kind; \ + (pattr)->pValue = (CK_VOID_PTR)(item)->data; \ + (pattr)->ulValueLen = (CK_ULONG)(item)->size; \ + (pattr)++; + +#define NSS_CK_SET_ATTRIBUTE_UTF8(pattr, kind, utf8) \ + (pattr)->type = kind; \ + (pattr)->pValue = (CK_VOID_PTR)utf8; \ + (pattr)->ulValueLen = (CK_ULONG)nssUTF8_Size(utf8, NULL); \ + if ((pattr)->ulValueLen) ((pattr)->ulValueLen)--; \ + (pattr)++; + +#define NSS_CK_SET_ATTRIBUTE_VAR(pattr, kind, var) \ + (pattr)->type = kind; \ + (pattr)->pValue = (CK_VOID_PTR)&var; \ + (pattr)->ulValueLen = (CK_ULONG)sizeof(var); \ + (pattr)++; + +#define NSS_CK_SET_ATTRIBUTE_NULL(pattr, kind) \ + (pattr)->type = kind; \ + (pattr)->pValue = (CK_VOID_PTR)NULL; \ + (pattr)->ulValueLen = 0; \ + (pattr)++; + +#define NSS_CK_TEMPLATE_FINISH(_template, attr, size) \ + size = (attr) - (_template); \ + PR_ASSERT(size <= sizeof(_template)/sizeof(_template[0])); + +/* NSS_CK_ATTRIBUTE_TO_ITEM(attrib, item) + * + * Convert a CK_ATTRIBUTE to an NSSItem. + */ +#define NSS_CK_ATTRIBUTE_TO_ITEM(attrib, item) \ + if ((CK_LONG)(attrib)->ulValueLen > 0) { \ + (item)->data = (void *)(attrib)->pValue; \ + (item)->size = (PRUint32)(attrib)->ulValueLen; \ + } else { \ + (item)->data = 0; \ + (item)->size = 0; \ + } + +#define NSS_CK_ATTRIBUTE_TO_BOOL(attrib, boolvar) \ + if ((attrib)->ulValueLen > 0) { \ + if (*((CK_BBOOL*)(attrib)->pValue) == CK_TRUE) { \ + boolvar = PR_TRUE; \ + } else { \ + boolvar = PR_FALSE; \ + } \ + } + +/* NSS_CK_ATTRIBUTE_TO_UTF8(attrib, str) + * + * Convert a CK_ATTRIBUTE to a string. + */ +#define NSS_CK_ATTRIBUTE_TO_UTF8(attrib, str) \ + str = (NSSUTF8 *)((attrib)->pValue); + +/* NSS_CK_ITEM_TO_ATTRIBUTE(item, attrib) + * + * Convert an NSSItem to a CK_ATTRIBUTE. + */ +#define NSS_CK_ITEM_TO_ATTRIBUTE(item, attrib) \ + (attrib)->pValue = (CK_VOID_PTR)(item)->data; \ + (attrib)->ulValueLen = (CK_ULONG)(item)->size; \ + +/* Get an array of attributes from an object. */ +NSS_EXTERN PRStatus +nssCKObject_GetAttributes +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG count, + NSSArena *arenaOpt, + nssSession *session, + NSSSlot *slot +); + +/* Get a single attribute as an item. */ +NSS_EXTERN PRStatus +nssCKObject_GetAttributeItem +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_TYPE attribute, + NSSArena *arenaOpt, + nssSession *session, + NSSSlot *slot, + NSSItem *rvItem +); + +NSS_EXTERN PRBool +nssCKObject_IsAttributeTrue +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_TYPE attribute, + nssSession *session, + NSSSlot *slot, + PRStatus *rvStatus +); + +NSS_EXTERN PRStatus +nssCKObject_SetAttributes +( + CK_OBJECT_HANDLE object, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG count, + nssSession *session, + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssCKObject_IsTokenObjectTemplate +( + CK_ATTRIBUTE_PTR objectTemplate, + CK_ULONG otsize +); + +PR_END_EXTERN_C + +#endif /* CKHELPER_H */ diff --git a/security/nss/lib/dev/config.mk b/security/nss/lib/dev/config.mk new file mode 100644 index 000000000..4a9ed7dda --- /dev/null +++ b/security/nss/lib/dev/config.mk @@ -0,0 +1,48 @@ +# +# The contents of this file are subject to the Mozilla Public +# License Version 1.1 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.mozilla.org/MPL/ +# +# Software distributed under the License is distributed on an "AS +# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or +# implied. See the License for the specific language governing +# rights and limitations under the License. +# +# The Original Code is the Netscape security libraries. +# +# The Initial Developer of the Original Code is Netscape +# Communications Corporation. Portions created by Netscape are +# Copyright (C) 1994-2000 Netscape Communications Corporation. All +# Rights Reserved. +# +# Contributor(s): +# +# Alternatively, the contents of this file may be used under the +# terms of the GNU General Public License Version 2 or later (the +# "GPL"), in which case the provisions of the GPL are applicable +# instead of those above. If you wish to allow use of your +# version of this file only under the terms of the GPL and not to +# allow others to use your version of this file under the MPL, +# indicate your decision by deleting the provisions above and +# replace them with the notice and other provisions required by +# the GPL. If you do not delete the provisions above, a recipient +# may use your version of this file under either the MPL or the +# GPL. +# +CONFIG_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$" + +ifdef BUILD_IDG +DEFINES += -DNSSDEBUG +endif + +# +# Override TARGETS variable so that only static libraries +# are specifed as dependencies within rules.mk. +# + +TARGETS = $(LIBRARY) +SHARED_LIBRARY = +IMPORT_LIBRARY = +PROGRAM = + diff --git a/security/nss/lib/dev/dev.h b/security/nss/lib/dev/dev.h new file mode 100644 index 000000000..9967d32e5 --- /dev/null +++ b/security/nss/lib/dev/dev.h @@ -0,0 +1,970 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef DEV_H +#define DEV_H + +/* + * dev.h + * + * Low-level methods for interaction with cryptoki devices + */ + +#ifdef DEBUG +static const char DEV_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKT_H +#include "nssckt.h" +#endif /* NSSCKT_H */ + +#ifndef NSSDEV_H +#include "nssdev.h" +#endif /* NSSDEV_H */ + +#ifndef DEVT_H +#include "devt.h" +#endif /* DEVT_H */ + +PR_BEGIN_EXTERN_C + +/* the global module list + * + * These functions are for managing the global set of modules. Trust Domains, + * etc., will draw from this set. These functions are completely internal + * and only invoked when there are changes to the global module state + * (load or unload). + * + * nss_InitializeGlobalModuleList + * nss_DestroyGlobalModuleList + * nss_GetLoadedModules + * + * nssGlobalModuleList_Add + * nssGlobalModuleList_Remove + * nssGlobalModuleList_FindModuleByName + * nssGlobalModuleList_FindSlotByName + * nssGlobalModuleList_FindTokenByName + */ + +NSS_EXTERN PRStatus +nss_InitializeGlobalModuleList +( + void +); + +NSS_EXTERN PRStatus +nss_DestroyGlobalModuleList +( + void +); + +NSS_EXTERN NSSModule ** +nss_GetLoadedModules +( + void +); + +NSS_EXTERN PRStatus +nssGlobalModuleList_Add +( + NSSModule *module +); + +NSS_EXTERN PRStatus +nssGlobalModuleList_Remove +( + NSSModule *module +); + +NSS_EXTERN NSSModule * +nssGlobalModuleList_FindModuleByName +( + NSSUTF8 *moduleName +); + +NSS_EXTERN NSSSlot * +nssGlobalModuleList_FindSlotByName +( + NSSUTF8 *slotName +); + +NSS_EXTERN NSSToken * +nssGlobalModuleList_FindTokenByName +( + NSSUTF8 *tokenName +); + +NSS_EXTERN NSSToken * +nss_GetDefaultCryptoToken +( + void +); + +NSS_EXTERN NSSToken * +nss_GetDefaultDatabaseToken +( + void +); + +/* + * |-----------|<---> NSSSlot <--> NSSToken + * | NSSModule |<---> NSSSlot <--> NSSToken + * |-----------|<---> NSSSlot <--> NSSToken + */ + +/* NSSModule + * + * nssModule_Create + * nssModule_CreateFromSpec + * nssModule_AddRef + * nssModule_GetName + * nssModule_GetSlots + * nssModule_FindSlotByName + * nssModule_FindTokenByName + * nssModule_GetCertOrder + */ + +NSS_EXTERN NSSModule * +nssModule_Create +( + NSSUTF8 *moduleOpt, + NSSUTF8 *uriOpt, + NSSUTF8 *opaqueOpt, + void *reserved +); + +/* This is to use the new loading mechanism. */ +NSS_EXTERN NSSModule * +nssModule_CreateFromSpec +( + NSSUTF8 *moduleSpec, + NSSModule *parent, + PRBool loadSubModules +); + +NSS_EXTERN PRStatus +nssModule_Destroy +( + NSSModule *mod +); + +NSS_EXTERN NSSModule * +nssModule_AddRef +( + NSSModule *mod +); + +NSS_EXTERN NSSUTF8 * +nssModule_GetName +( + NSSModule *mod +); + +NSS_EXTERN NSSSlot ** +nssModule_GetSlots +( + NSSModule *mod +); + +NSS_EXTERN NSSSlot * +nssModule_FindSlotByName +( + NSSModule *mod, + NSSUTF8 *slotName +); + +NSS_EXTERN NSSToken * +nssModule_FindTokenByName +( + NSSModule *mod, + NSSUTF8 *tokenName +); + +NSS_EXTERN PRInt32 +nssModule_GetCertOrder +( + NSSModule *module +); + +/* NSSSlot + * + * nssSlot_Destroy + * nssSlot_AddRef + * nssSlot_GetName + * nssSlot_GetTokenName + * nssSlot_IsTokenPresent + * nssSlot_IsPermanent + * nssSlot_IsFriendly + * nssSlot_IsHardware + * nssSlot_Refresh + * nssSlot_GetModule + * nssSlot_GetToken + * nssSlot_Login + * nssSlot_Logout + * nssSlot_SetPassword + * nssSlot_CreateSession + */ + +NSS_EXTERN PRStatus +nssSlot_Destroy +( + NSSSlot *slot +); + +NSS_EXTERN NSSSlot * +nssSlot_AddRef +( + NSSSlot *slot +); + +NSS_EXTERN NSSUTF8 * +nssSlot_GetName +( + NSSSlot *slot +); + +NSS_EXTERN NSSUTF8 * +nssSlot_GetTokenName +( + NSSSlot *slot +); + +NSS_EXTERN NSSModule * +nssSlot_GetModule +( + NSSSlot *slot +); + +NSS_EXTERN NSSToken * +nssSlot_GetToken +( + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssSlot_IsTokenPresent +( + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssSlot_IsPermanent +( + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssSlot_IsFriendly +( + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssSlot_IsHardware +( + NSSSlot *slot +); + +NSS_EXTERN PRBool +nssSlot_IsLoggedIn +( + NSSSlot *slot +); + +NSS_EXTERN PRStatus +nssSlot_Refresh +( + NSSSlot *slot +); + +NSS_EXTERN PRStatus +nssSlot_Login +( + NSSSlot *slot, + NSSCallback *pwcb +); +extern const NSSError NSS_ERROR_INVALID_PASSWORD; +extern const NSSError NSS_ERROR_USER_CANCELED; + +NSS_EXTERN PRStatus +nssSlot_Logout +( + NSSSlot *slot, + nssSession *sessionOpt +); + +#define NSSSLOT_ASK_PASSWORD_FIRST_TIME -1 +#define NSSSLOT_ASK_PASSWORD_EVERY_TIME 0 +NSS_EXTERN void +nssSlot_SetPasswordDefaults +( + NSSSlot *slot, + PRInt32 askPasswordTimeout +); + +NSS_EXTERN PRStatus +nssSlot_SetPassword +( + NSSSlot *slot, + NSSUTF8 *oldPasswordOpt, + NSSUTF8 *newPassword +); +extern const NSSError NSS_ERROR_INVALID_PASSWORD; +extern const NSSError NSS_ERROR_USER_CANCELED; + +/* + * nssSlot_IsLoggedIn + */ + +NSS_EXTERN nssSession * +nssSlot_CreateSession +( + NSSSlot *slot, + NSSArena *arenaOpt, + PRBool readWrite /* so far, this is the only flag used */ +); + +/* NSSToken + * + * nssToken_Destroy + * nssToken_AddRef + * nssToken_GetName + * nssToken_GetModule + * nssToken_GetSlot + * nssToken_NeedsPINInitialization + * nssToken_ImportCertificate + * nssToken_ImportTrust + * nssToken_ImportCRL + * nssToken_GenerateKeyPair + * nssToken_GenerateSymmetricKey + * nssToken_DeleteStoredObject + * nssToken_FindCertificates + * nssToken_FindCertificatesBySubject + * nssToken_FindCertificatesByNickname + * nssToken_FindCertificatesByEmail + * nssToken_FindCertificateByIssuerAndSerialNumber + * nssToken_FindCertificateByEncodedCertificate + * nssToken_FindTrustObjects + * nssToken_FindTrustForCertificate + * nssToken_FindCRLs + * nssToken_FindCRLsBySubject + * nssToken_FindPrivateKeys + * nssToken_FindPrivateKeyByID + * nssToken_Digest + * nssToken_BeginDigest + * nssToken_ContinueDigest + * nssToken_FinishDigest + */ + +NSS_EXTERN PRStatus +nssToken_Destroy +( + NSSToken *tok +); + +NSS_EXTERN NSSToken * +nssToken_AddRef +( + NSSToken *tok +); + +NSS_EXTERN NSSUTF8 * +nssToken_GetName +( + NSSToken *tok +); + +NSS_EXTERN NSSModule * +nssToken_GetModule +( + NSSToken *token +); + +NSS_EXTERN NSSSlot * +nssToken_GetSlot +( + NSSToken *tok +); + +NSS_EXTERN PRBool +nssToken_NeedsPINInitialization +( + NSSToken *token +); + +NSS_EXTERN nssCryptokiObject * +nssToken_ImportCertificate +( + NSSToken *tok, + nssSession *sessionOpt, + NSSCertificateType certType, + NSSItem *id, + NSSUTF8 *nickname, + NSSDER *encoding, + NSSDER *issuer, + NSSDER *subject, + NSSDER *serial, + NSSASCII7 *emailAddr, + PRBool asTokenObject +); + +NSS_EXTERN nssCryptokiObject * +nssToken_ImportTrust +( + NSSToken *tok, + nssSession *sessionOpt, + NSSDER *certEncoding, + NSSDER *certIssuer, + NSSDER *certSerial, + nssTrustLevel serverAuth, + nssTrustLevel clientAuth, + nssTrustLevel codeSigning, + nssTrustLevel emailProtection, + PRBool asTokenObject +); + +NSS_EXTERN nssCryptokiObject * +nssToken_ImportCRL +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + NSSDER *encoding, + PRBool isKRL, + NSSUTF8 *url, + PRBool asTokenObject +); + +/* Permanently remove an object from the token. */ +NSS_EXTERN PRStatus +nssToken_DeleteStoredObject +( + nssCryptokiObject *instance +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCertificates +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCertificatesBySubject +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCertificatesByNickname +( + NSSToken *token, + nssSession *sessionOpt, + NSSUTF8 *name, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCertificatesByEmail +( + NSSToken *token, + nssSession *sessionOpt, + NSSASCII7 *email, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCertificatesByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *id, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject * +nssToken_FindCertificateByIssuerAndSerialNumber +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *issuer, + NSSDER *serial, + nssTokenSearchType searchType, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject * +nssToken_FindCertificateByEncodedCertificate +( + NSSToken *token, + nssSession *sessionOpt, + NSSBER *encodedCertificate, + nssTokenSearchType searchType, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindTrustObjects +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject * +nssToken_FindTrustForCertificate +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *certEncoding, + NSSDER *certIssuer, + NSSDER *certSerial, + nssTokenSearchType searchType +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCRLs +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindCRLsBySubject +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject ** +nssToken_FindPrivateKeys +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN nssCryptokiObject * +nssToken_FindPrivateKeyByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *keyID +); + +NSS_EXTERN nssCryptokiObject * +nssToken_FindPublicKeyByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *keyID +); + +NSS_EXTERN NSSItem * +nssToken_Digest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSAlgorithmAndParameters *ap, + NSSItem *data, + NSSItem *rvOpt, + NSSArena *arenaOpt +); + +NSS_EXTERN PRStatus +nssToken_BeginDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSAlgorithmAndParameters *ap +); + +NSS_EXTERN PRStatus +nssToken_ContinueDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSItem *item +); + +NSS_EXTERN NSSItem * +nssToken_FinishDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSItem *rvOpt, + NSSArena *arenaOpt +); + +/* nssSession + * + * nssSession_Destroy + * nssSession_EnterMonitor + * nssSession_ExitMonitor + * nssSession_IsReadWrite + */ + +NSS_EXTERN PRStatus +nssSession_Destroy +( + nssSession *s +); + +/* would like to inline */ +NSS_EXTERN PRStatus +nssSession_EnterMonitor +( + nssSession *s +); + +/* would like to inline */ +NSS_EXTERN PRStatus +nssSession_ExitMonitor +( + nssSession *s +); + +/* would like to inline */ +NSS_EXTERN PRBool +nssSession_IsReadWrite +( + nssSession *s +); + +/* nssCryptokiObject + * + * An object living on a cryptoki token. + * Not really proper to mix up the object types just because + * nssCryptokiObject itself is generic, but doing so anyway. + * + * nssCryptokiObject_Destroy + * nssCryptokiObject_Equal + * nssCryptokiObject_Clone + * nssCryptokiCertificate_GetAttributes + * nssCryptokiPrivateKey_GetAttributes + * nssCryptokiPublicKey_GetAttributes + * nssCryptokiTrust_GetAttributes + * nssCryptokiCRL_GetAttributes + */ + +NSS_EXTERN void +nssCryptokiObject_Destroy +( + nssCryptokiObject *object +); + +NSS_EXTERN PRBool +nssCryptokiObject_Equal +( + nssCryptokiObject *object1, + nssCryptokiObject *object2 +); + +NSS_EXTERN nssCryptokiObject * +nssCryptokiObject_Clone +( + nssCryptokiObject *object +); + +NSS_EXTERN PRStatus +nssCryptokiCertificate_GetAttributes +( + nssCryptokiObject *object, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSCertificateType *certTypeOpt, + NSSItem *idOpt, + NSSDER *encodingOpt, + NSSDER *issuerOpt, + NSSDER *serialOpt, + NSSDER *subjectOpt, + NSSASCII7 **emailOpt +); + +NSS_EXTERN PRStatus +nssCryptokiTrust_GetAttributes +( + nssCryptokiObject *trustObject, + nssSession *sessionOpt, + nssTrustLevel *serverAuth, + nssTrustLevel *clientAuth, + nssTrustLevel *codeSigning, + nssTrustLevel *emailProtection +); + +NSS_EXTERN PRStatus +nssCryptokiCRL_GetAttributes +( + nssCryptokiObject *crlObject, + nssSession *sessionOpt, + NSSArena *arenaOpt, + NSSItem *encodingOpt, + NSSUTF8 **urlOpt, + PRBool *isKRLOpt +); + +/* I'm including this to handle import of certificates in NSS 3.5. This + * function will set the cert-related attributes of a key, in order to + * associate it with a cert. Does it stay like this for 4.0? + */ +NSS_EXTERN PRStatus +nssCryptokiPrivateKey_SetCertificate +( + nssCryptokiObject *keyObject, + nssSession *sessionOpt, + NSSUTF8 *nickname, + NSSItem *id, + NSSDER *subject +); + +NSS_EXTERN void +nssModuleArray_Destroy +( + NSSModule **modules +); + +/* nssSlotArray + * + * nssSlotArray_Destroy + */ + +NSS_EXTERN void +nssSlotArray_Destroy +( + NSSSlot **slots +); + +/* nssTokenArray + * + * nssTokenArray_Destroy + */ + +NSS_EXTERN void +nssTokenArray_Destroy +( + NSSToken **tokens +); + +/* nssCryptokiObjectArray + * + * nssCryptokiObjectArray_Destroy + */ +NSS_EXTERN void +nssCryptokiObjectArray_Destroy +( + nssCryptokiObject **object +); + +/* nssSlotList +* + * An ordered list of slots. The order can be anything, it is set in the + * Add methods. Perhaps it should be CreateInCertOrder, ...? + * + * nssSlotList_Create + * nssSlotList_Destroy + * nssSlotList_Add + * nssSlotList_AddModuleSlots + * nssSlotList_GetSlots + * nssSlotList_FindSlotByName + * nssSlotList_FindTokenByName + * nssSlotList_GetBestSlot + * nssSlotList_GetBestSlotForAlgorithmAndParameters + * nssSlotList_GetBestSlotForAlgorithmsAndParameters + */ + +/* nssSlotList_Create + */ +NSS_EXTERN nssSlotList * +nssSlotList_Create +( + NSSArena *arenaOpt +); + +/* nssSlotList_Destroy + */ +NSS_EXTERN void +nssSlotList_Destroy +( + nssSlotList *slotList +); + +/* nssSlotList_Add + * + * Add the given slot in the given order. + */ +NSS_EXTERN PRStatus +nssSlotList_Add +( + nssSlotList *slotList, + NSSSlot *slot, + PRUint32 order +); + +/* nssSlotList_AddModuleSlots + * + * Add all slots in the module, in the given order (the slots will have + * equal weight). + */ +NSS_EXTERN PRStatus +nssSlotList_AddModuleSlots +( + nssSlotList *slotList, + NSSModule *module, + PRUint32 order +); + +/* nssSlotList_GetSlots + */ +NSS_EXTERN NSSSlot ** +nssSlotList_GetSlots +( + nssSlotList *slotList +); + +/* nssSlotList_FindSlotByName + */ +NSS_EXTERN NSSSlot * +nssSlotList_FindSlotByName +( + nssSlotList *slotList, + NSSUTF8 *slotName +); + +/* nssSlotList_FindTokenByName + */ +NSS_EXTERN NSSToken * +nssSlotList_FindTokenByName +( + nssSlotList *slotList, + NSSUTF8 *tokenName +); + +/* nssSlotList_GetBestSlot + * + * The best slot is the highest ranking in order, i.e., the first in the + * list. + */ +NSS_EXTERN NSSSlot * +nssSlotList_GetBestSlot +( + nssSlotList *slotList +); + +/* nssSlotList_GetBestSlotForAlgorithmAndParameters + * + * Highest-ranking slot than can handle algorithm/parameters. + */ +NSS_EXTERN NSSSlot * +nssSlotList_GetBestSlotForAlgorithmAndParameters +( + nssSlotList *slotList, + NSSAlgorithmAndParameters *ap +); + +/* nssSlotList_GetBestSlotForAlgorithmsAndParameters + * + * Highest-ranking slot than can handle all algorithms/parameters. + */ +NSS_EXTERN NSSSlot * +nssSlotList_GetBestSlotForAlgorithmsAndParameters +( + nssSlotList *slotList, + NSSAlgorithmAndParameters **ap +); + +#ifdef NSS_3_4_CODE + +NSS_EXTERN PRBool +nssToken_IsPresent +( + NSSToken *token +); + +NSS_EXTERN nssSession * +nssToken_GetDefaultSession +( + NSSToken *token +); + +NSS_EXTERN PRStatus +nssToken_GetTrustOrder +( + NSSToken *tok +); + +NSS_EXTERN PRStatus +nssToken_NotifyCertsNotVisible +( + NSSToken *tok +); + +NSS_EXTERN PRStatus +nssToken_TraverseCertificates +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRStatus (* callback)(nssCryptokiObject *instance, void *arg), + void *arg +); + +#endif + +PR_END_EXTERN_C + +#endif /* DEV_H */ diff --git a/security/nss/lib/dev/devm.h b/security/nss/lib/dev/devm.h new file mode 100644 index 000000000..0dd0d5b36 --- /dev/null +++ b/security/nss/lib/dev/devm.h @@ -0,0 +1,242 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef DEVM_H +#define DEVM_H + +#ifdef DEBUG +static const char DEVM_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef BASE_H +#include "base.h" +#endif /* BASE_H */ + +#ifndef NSSCKT_H +#include "nssckt.h" +#endif /* NSSCKT_H */ + +#ifndef DEV_H +#include "dev.h" +#endif /* DEV_H */ + +#ifndef DEVTM_H +#include "devtm.h" +#endif /* DEVTM_H */ + +PR_BEGIN_EXTERN_C + +/* Shortcut to cryptoki API functions. */ +#define CKAPI(epv) \ + ((CK_FUNCTION_LIST_PTR)(epv)) + +NSS_EXTERN void +nssDevice_AddRef +( + struct nssDeviceBaseStr *device +); + +NSS_EXTERN PRBool +nssDevice_Destroy +( + struct nssDeviceBaseStr *device +); + +NSS_EXTERN PRBool +nssModule_IsThreadSafe +( + NSSModule *module +); + +NSS_EXTERN PRBool +nssModule_IsInternal +( + NSSModule *mod +); + +NSS_EXTERN PRBool +nssModule_IsModuleDBOnly +( + NSSModule *mod +); + +NSS_EXTERN void * +nssModule_GetCryptokiEPV +( + NSSModule *mod +); + +NSS_EXTERN NSSSlot * +nssSlot_Create +( + CK_SLOT_ID slotId, + NSSModule *parent +); + +NSS_EXTERN void * +nssSlot_GetCryptokiEPV +( + NSSSlot *slot +); + +NSS_EXTERN NSSToken * +nssToken_Create +( + CK_SLOT_ID slotID, + NSSSlot *peer +); + +NSS_EXTERN void * +nssToken_GetCryptokiEPV +( + NSSToken *token +); + +NSS_EXTERN nssSession * +nssToken_GetDefaultSession +( + NSSToken *token +); + +NSS_EXTERN PRBool +nssToken_IsLoginRequired +( + NSSToken *token +); + +NSS_EXTERN void +nssToken_Remove +( + NSSToken *token +); + +NSS_EXTERN nssCryptokiObject * +nssCryptokiObject_Create +( + NSSToken *t, + nssSession *session, + CK_OBJECT_HANDLE h +); + +NSS_EXTERN nssTokenObjectCache * +nssTokenObjectCache_Create +( + NSSToken *token, + PRBool cacheCerts, + PRBool cacheTrust, + PRBool cacheCRLs +); + +NSS_EXTERN void +nssTokenObjectCache_Destroy +( + nssTokenObjectCache *cache +); + +NSS_EXTERN void +nssTokenObjectCache_Clear +( + nssTokenObjectCache *cache +); + +NSS_EXTERN PRBool +nssTokenObjectCache_HaveObjectClass +( + nssTokenObjectCache *cache, + CK_OBJECT_CLASS objclass +); + +NSS_EXTERN nssCryptokiObject ** +nssTokenObjectCache_FindObjectsByTemplate +( + nssTokenObjectCache *cache, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR otemplate, + CK_ULONG otlen, + PRUint32 maximumOpt, + PRStatus *statusOpt +); + +NSS_EXTERN PRStatus +nssTokenObjectCache_GetObjectAttributes +( + nssTokenObjectCache *cache, + NSSArena *arenaOpt, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR atemplate, + CK_ULONG atlen +); + +NSS_EXTERN PRStatus +nssTokenObjectCache_ImportObject +( + nssTokenObjectCache *cache, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR ot, + CK_ULONG otlen +); + +NSS_EXTERN void +nssTokenObjectCache_RemoveObject +( + nssTokenObjectCache *cache, + nssCryptokiObject *object +); + +/* XXX allows peek back into token */ +NSS_EXTERN PRStatus +nssToken_GetCachedObjectAttributes +( + NSSToken *token, + NSSArena *arenaOpt, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR atemplate, + CK_ULONG atlen +); + +/* PKCS#11 stores strings in a fixed-length buffer padded with spaces. This + * function gets the length of the actual string. + */ +NSS_EXTERN PRUint32 +nssPKCS11String_Length +( + CK_CHAR *pkcs11str, + PRUint32 bufLen +); + +PR_END_EXTERN_C + +#endif /* DEV_H */ diff --git a/security/nss/lib/dev/devmod.c b/security/nss/lib/dev/devmod.c new file mode 100644 index 000000000..e0006370f --- /dev/null +++ b/security/nss/lib/dev/devmod.c @@ -0,0 +1,900 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifdef DEBUG +static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKEPV_H +#include "nssckepv.h" +#endif /* NSSCKEPV_H */ + +#ifndef DEVM_H +#include "devm.h" +#endif /* DEVM_H */ + +#ifndef CKHELPER_H +#include "ckhelper.h" +#endif /* CKHELPER_H */ + +#ifdef PURE_STAN_CODE + +extern void FC_GetFunctionList(void); +extern void NSC_GetFunctionList(void); +extern void NSC_ModuleDBFunc(void); + +/* The list of boolean flags used to describe properties of a + * module. + */ +#define NSSMODULE_FLAGS_NOT_THREADSAFE 0x0001 /* isThreadSafe */ +#define NSSMODULE_FLAGS_INTERNAL 0x0002 /* isInternal */ +#define NSSMODULE_FLAGS_FIPS 0x0004 /* isFIPS */ +#define NSSMODULE_FLAGS_MODULE_DB 0x0008 /* isModuleDB */ +#define NSSMODULE_FLAGS_MODULE_DB_ONLY 0x0010 /* moduleDBOnly */ +#define NSSMODULE_FLAGS_CRITICAL 0x0020 /* isCritical */ + +struct NSSModuleStr { + struct nssDeviceBaseStr base; + NSSUTF8 *libraryName; + PRLibrary *library; + char *libraryParams; + void *moduleDBFunc; + void *epv; + CK_INFO info; + NSSSlot **slots; + PRUint32 numSlots; + PRBool isLoaded; + struct { + PRInt32 trust; + PRInt32 cipher; + PRInt32 certStorage; + } order; +}; + +#define NSSMODULE_IS_THREADSAFE(module) \ + (!(module->base.flags & NSSMODULE_FLAGS_NOT_THREADSAFE)) + +#define NSSMODULE_IS_INTERNAL(module) \ + (module->base.flags & NSSMODULE_FLAGS_INTERNAL) + +#define NSSMODULE_IS_FIPS(module) \ + (module->base.flags & NSSMODULE_FLAGS_FIPS) + +#define NSSMODULE_IS_MODULE_DB(module) \ + (module->base.flags & NSSMODULE_FLAGS_MODULE_DB) + +#define NSSMODULE_IS_MODULE_DB_ONLY(module) \ + (module->base.flags & NSSMODULE_FLAGS_MODULE_DB_ONLY) + +#define NSSMODULE_IS_CRITICAL(module) \ + (module->base.flags & NSSMODULE_FLAGS_CRITICAL) + +/* Threading callbacks for C_Initialize. Use NSPR threads. */ + +CK_RV PR_CALLBACK +nss_ck_CreateMutex(CK_VOID_PTR_PTR pMutex) +{ + CK_VOID_PTR mutex = (CK_VOID_PTR)PZ_NewLock(nssILockOther); + if (mutex != NULL) { + *pMutex = (CK_VOID_PTR)mutex; + return CKR_OK; + } + return CKR_HOST_MEMORY; +} + +CK_RV PR_CALLBACK +nss_ck_DestroyMutex(CK_VOID_PTR mutex) +{ + PZ_DestroyLock((PZLock *)mutex); + return CKR_OK; +} + +CK_RV PR_CALLBACK +nss_ck_LockMutex(CK_VOID_PTR mutex) +{ + PZ_Lock((PZLock *)mutex); + return CKR_OK; +} + +CK_RV PR_CALLBACK +nss_ck_UnlockMutex(CK_VOID_PTR mutex) +{ + return (PZ_Unlock((PZLock *)mutex) == PR_SUCCESS) ? + CKR_OK : CKR_MUTEX_NOT_LOCKED; +} + +/* Default callback args to C_Initialize */ +/* XXX not const because we are modifying the pReserved argument in order + * to use the libraryParams extension. + */ +static CK_C_INITIALIZE_ARGS +s_ck_initialize_args = { + nss_ck_CreateMutex, /* CreateMutex */ + nss_ck_DestroyMutex, /* DestroyMutex */ + nss_ck_LockMutex, /* LockMutex */ + nss_ck_UnlockMutex, /* UnlockMutex */ + CKF_LIBRARY_CANT_CREATE_OS_THREADS | + CKF_OS_LOCKING_OK, /* flags */ + NULL /* pReserved */ +}; + +/* load all slots in a module. */ +static PRStatus +module_load_slots(NSSModule *mod) +{ + CK_ULONG i, ulNumSlots; + CK_SLOT_ID *slotIDs; + nssArenaMark *mark = NULL; + NSSSlot **slots; + PRStatus nssrv; + CK_RV ckrv; + /* Get the number of slots */ + ckrv = CKAPI(mod->epv)->C_GetSlotList(CK_FALSE, NULL, &ulNumSlots); + if (ckrv != CKR_OK) { + /* what is the error? */ + return PR_FAILURE; + } + /* Alloc memory for the array of slot ID's */ + slotIDs = nss_ZNEWARRAY(NULL, CK_SLOT_ID, ulNumSlots); + if (!slotIDs) { + goto loser; + } + /* Get the actual slot list */ + ckrv = CKAPI(mod->epv)->C_GetSlotList(CK_FALSE, slotIDs, &ulNumSlots); + if (ckrv != CKR_OK) { + /* what is the error? */ + goto loser; + } + /* Alloc memory for the array of slots, in the module's arena */ + mark = nssArena_Mark(mod->base.arena); /* why mark? it'll be destroyed */ + if (!mark) { + return PR_FAILURE; + } + slots = nss_ZNEWARRAY(mod->base.arena, NSSSlot *, ulNumSlots); + if (!slots) { + goto loser; + } + /* Initialize each slot */ + for (i=0; i<ulNumSlots; i++) { + slots[i] = nssSlot_Create(slotIDs[i], mod); + } + nss_ZFreeIf(slotIDs); + nssrv = nssArena_Unmark(mod->base.arena, mark); + if (nssrv != PR_SUCCESS) { + goto loser; + } + mod->slots = slots; + mod->numSlots = ulNumSlots; + return PR_SUCCESS; +loser: + if (mark) { + nssArena_Release(mod->base.arena, mark); + } + nss_ZFreeIf(slotIDs); + return PR_FAILURE; +} + +NSS_IMPLEMENT PRStatus +nssModule_Load +( + NSSModule *mod +) +{ + PRLibrary *library = NULL; + CK_C_GetFunctionList epv; + CK_RV ckrv; + if (NSSMODULE_IS_INTERNAL(mod)) { + /* internal, statically get the C_GetFunctionList function */ + if (NSSMODULE_IS_FIPS(mod)) { + epv = (CK_C_GetFunctionList) FC_GetFunctionList; + } else { + epv = (CK_C_GetFunctionList) NSC_GetFunctionList; + } + if (NSSMODULE_IS_MODULE_DB(mod)) { + mod->moduleDBFunc = (void *) NSC_ModuleDBFunc; + } + if (NSSMODULE_IS_MODULE_DB_ONLY(mod)) { + mod->isLoaded = PR_TRUE; /* XXX needed? */ + return PR_SUCCESS; + } + } else { + /* Use NSPR to load the library */ + library = PR_LoadLibrary(mod->libraryName); + if (!library) { + /* what's the error to set? */ + return PR_FAILURE; + } + mod->library = library; + /* Skip if only getting the db loader function */ + if (!NSSMODULE_IS_MODULE_DB_ONLY(mod)) { + /* Load the cryptoki entry point function */ + epv = (CK_C_GetFunctionList)PR_FindSymbol(library, + "C_GetFunctionList"); + } + /* Load the module database loader function */ + if (NSSMODULE_IS_MODULE_DB(mod)) { + mod->moduleDBFunc = (void *)PR_FindSymbol(library, + "NSS_ReturnModuleSpecData"); + } + } + if (epv == NULL) { + goto loser; + } + /* Load the cryptoki entry point vector (function list) */ + ckrv = (*epv)((CK_FUNCTION_LIST_PTR *)&mod->epv); + if (ckrv != CKR_OK) { + goto loser; + } + /* Initialize the module */ + if (mod->libraryParams) { + s_ck_initialize_args.LibraryParameters = (void *)mod->libraryParams; + } else { + s_ck_initialize_args.LibraryParameters = NULL; + } + ckrv = CKAPI(mod->epv)->C_Initialize(&s_ck_initialize_args); + if (ckrv != CKR_OK) { + /* Apparently the token is not thread safe. Retry without + * threading parameters. + */ + mod->base.flags |= NSSMODULE_FLAGS_NOT_THREADSAFE; + ckrv = CKAPI(mod->epv)->C_Initialize((CK_VOID_PTR)NULL); + if (ckrv != CKR_OK) { + goto loser; + } + } + /* TODO: check the version # using C_GetInfo */ + ckrv = CKAPI(mod->epv)->C_GetInfo(&mod->info); + if (ckrv != CKR_OK) { + goto loser; + } + /* TODO: if the name is not set, get it from info.libraryDescription */ + /* Now load the slots */ + if (module_load_slots(mod) != PR_SUCCESS) { + goto loser; + } + /* Module has successfully loaded */ + mod->isLoaded = PR_TRUE; + return PR_SUCCESS; +loser: + if (library) { + PR_UnloadLibrary(library); + } + /* clear all values set above, they are invalid now */ + mod->library = NULL; + mod->epv = NULL; + return PR_FAILURE; +} + +NSS_IMPLEMENT PRStatus +nssModule_Unload +( + NSSModule *mod +) +{ + PRStatus nssrv = PR_SUCCESS; + if (mod->library) { + (void)CKAPI(mod->epv)->C_Finalize(NULL); + nssrv = PR_UnloadLibrary(mod->library); + } + /* Free the slots, yes? */ + mod->library = NULL; + mod->epv = NULL; + mod->isLoaded = PR_FALSE; + return nssrv; +} + +/* Alloc memory for a module. Copy in the module name and library path + * if provided. XXX use the opaque arg also, right? + */ +NSS_IMPLEMENT NSSModule * +nssModule_Create +( + NSSUTF8 *moduleOpt, + NSSUTF8 *uriOpt, + NSSUTF8 *opaqueOpt, + void *reserved +) +{ + NSSArena *arena; + NSSModule *rvMod; + arena = NSSArena_Create(); + if(!arena) { + return (NSSModule *)NULL; + } + rvMod = nss_ZNEW(arena, NSSModule); + if (!rvMod) { + goto loser; + } + if (moduleOpt) { + /* XXX making the gross assumption this is just the module name */ + /* if the name is a duplicate, should that be tested here? or + * wait for Load? + */ + rvMod->base.name = nssUTF8_Duplicate(moduleOpt, arena); + if (!rvMod->base.name) { + goto loser; + } + } + if (uriOpt) { + /* Load the module from a URI. */ + /* XXX at this time - only file URI (even worse, no file:// for now) */ + rvMod->libraryName = nssUTF8_Duplicate(uriOpt, arena); + if (!rvMod->libraryName) { + goto loser; + } + } + rvMod->base.arena = arena; + rvMod->base.refCount = 1; + rvMod->base.lock = PZ_NewLock(nssNSSILockOther); + if (!rvMod->base.lock) { + goto loser; + } + /* everything else is 0/NULL at this point. */ + return rvMod; +loser: + nssArena_Destroy(arena); + return (NSSModule *)NULL; +} + +NSS_EXTERN PRStatus +nssCryptokiArgs_ParseNextPair +( + NSSUTF8 *start, + NSSUTF8 **attrib, + NSSUTF8 **value, + NSSUTF8 **remainder, + NSSArena *arenaOpt +); + +static PRStatus +parse_slot_flags +( + NSSSlot *slot, + NSSUTF8 *slotFlags +) +{ + PRStatus nssrv = PR_SUCCESS; +#if 0 + PRBool done = PR_FALSE; + NSSUTF8 *mark, *last; + last = mark = slotFlags; + while (PR_TRUE) { + while (*mark && *mark != ',') ++mark; + if (!*mark) done = PR_TRUE; + *mark = '\0'; + if (nssUTF8_Equal(last, "RANDOM", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_HAS_RANDOM; + } else if (nssUTF8_Equal(last, "RSA", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_RSA; + } else if (nssUTF8_Equal(last, "DSA", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_DSA; + } else if (nssUTF8_Equal(last, "DH", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_DH; + } else if (nssUTF8_Equal(last, "RC2", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_RC2; + } else if (nssUTF8_Equal(last, "RC4", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_RC4; + } else if (nssUTF8_Equal(last, "RC5", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_RC5; + } else if (nssUTF8_Equal(last, "DES", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_DES; + } else if (nssUTF8_Equal(last, "AES", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_AES; + } else if (nssUTF8_Equal(last, "SHA1", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_SHA1; + } else if (nssUTF8_Equal(last, "MD2", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_MD2; + } else if (nssUTF8_Equal(last, "MD5", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_MD5; + } else if (nssUTF8_Equal(last, "SSL", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_SSL; + } else if (nssUTF8_Equal(last, "TLS", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_TLS; + } else if (nssUTF8_Equal(last, "PublicCerts", &nssrv)) { + slot->base.flags |= NSSSLOT_FLAGS_FRIENDLY; + } else { + return PR_FAILURE; + } + if (done) break; + last = ++mark; + } +#endif + return nssrv; +} + +static PRStatus +parse_slot_parameters +( + NSSSlot *slot, + NSSUTF8 *slotParams, + NSSArena *tmparena +) +{ + PRStatus nssrv = PR_SUCCESS; + NSSUTF8 *current, *remainder; + NSSUTF8 *attrib, *value; + current = slotParams; + while (nssrv == PR_SUCCESS) { + nssrv = nssCryptokiArgs_ParseNextPair(current, + &attrib, &value, + &remainder, tmparena); + if (nssrv != PR_SUCCESS) break; + if (value) { + if (nssUTF8_Equal(attrib, "slotFlags", &nssrv)) { + nssrv = parse_slot_flags(slot, value); + } else if (nssUTF8_Equal(attrib, "askpw", &nssrv)) { + } else if (nssUTF8_Equal(attrib, "timeout", &nssrv)) { + } + } + if (*remainder == '\0') break; + current = remainder; + } + return nssrv; +} + +/* softoken seems to use "0x0000001", but no standard yet... perhaps this + * should store the number as an ID, in case the input isn't 1,2,3,...? + */ +static PRIntn +get_slot_number(NSSUTF8* snString) +{ + /* XXX super big hack */ + return atoi(&snString[strlen(snString)-1]); +} + +static PRStatus +parse_module_slot_parameters +( + NSSModule *mod, + NSSUTF8 *slotParams +) +{ + PRStatus nssrv = PR_SUCCESS; + NSSUTF8 *current, *remainder; + NSSUTF8 *attrib, *value; + NSSArena *tmparena; + PRIntn slotNum; + tmparena = nssArena_Create(); + if (!tmparena) { + return PR_FAILURE; + } + current = slotParams; + while (nssrv == PR_SUCCESS) { + nssrv = nssCryptokiArgs_ParseNextPair(current, + &attrib, &value, + &remainder, tmparena); + if (nssrv != PR_SUCCESS) break; + if (value) { + slotNum = get_slot_number(attrib); + if (slotNum < 0 || slotNum > mod->numSlots) { + return PR_FAILURE; + } + nssrv = parse_slot_parameters(mod->slots[slotNum], + value, tmparena); + if (nssrv != PR_SUCCESS) break; + } + if (*remainder == '\0') break; + current = remainder; + } + return nssrv; +} + +static PRStatus +parse_nss_flags +( + NSSModule *mod, + NSSUTF8 *nssFlags +) +{ + PRStatus nssrv = PR_SUCCESS; + PRBool done = PR_FALSE; + NSSUTF8 *mark, *last; + last = mark = nssFlags; + while (PR_TRUE) { + while (*mark && *mark != ',') ++mark; + if (!*mark) done = PR_TRUE; + *mark = '\0'; + if (nssUTF8_Equal(last, "internal", &nssrv)) { + mod->base.flags |= NSSMODULE_FLAGS_INTERNAL; + } else if (nssUTF8_Equal(last, "moduleDB", &nssrv)) { + mod->base.flags |= NSSMODULE_FLAGS_MODULE_DB; + } else if (nssUTF8_Equal(last, "moduleDBOnly", &nssrv)) { + mod->base.flags |= NSSMODULE_FLAGS_MODULE_DB_ONLY; + } else if (nssUTF8_Equal(last, "critical", &nssrv)) { + mod->base.flags |= NSSMODULE_FLAGS_CRITICAL; + } else { + return PR_FAILURE; + } + if (done) break; + last = ++mark; + } + return nssrv; +} + +static PRStatus +parse_nss_parameters +( + NSSModule *mod, + NSSUTF8 *nssParams, + NSSArena *tmparena, + NSSUTF8 **slotParams +) +{ + PRStatus nssrv = PR_SUCCESS; + NSSUTF8 *current, *remainder; + NSSUTF8 *attrib, *value; + current = nssParams; + while (nssrv == PR_SUCCESS) { + nssrv = nssCryptokiArgs_ParseNextPair(current, + &attrib, &value, + &remainder, tmparena); + if (nssrv != PR_SUCCESS) break; + if (value) { + if (nssUTF8_Equal(attrib, "flags", &nssrv) || + nssUTF8_Equal(attrib, "Flags", &nssrv)) { + nssrv = parse_nss_flags(mod, value); + } else if (nssUTF8_Equal(attrib, "trustOrder", &nssrv)) { + mod->order.trust = atoi(value); + } else if (nssUTF8_Equal(attrib, "cipherOrder", &nssrv)) { + mod->order.cipher = atoi(value); + } else if (nssUTF8_Equal(attrib, "ciphers", &nssrv)) { + } else if (nssUTF8_Equal(attrib, "slotParams", &nssrv)) { + /* slotParams doesn't get an arena, it is handled separately */ + *slotParams = nssUTF8_Duplicate(value, NULL); + } + } + if (*remainder == '\0') break; + current = remainder; + } + return nssrv; +} + +static PRStatus +parse_module_parameters +( + NSSModule *mod, + NSSUTF8 *moduleParams, + NSSUTF8 **slotParams +) +{ + PRStatus nssrv = PR_SUCCESS; + NSSUTF8 *current, *remainder; + NSSUTF8 *attrib, *value; + NSSArena *arena = mod->base.arena; + NSSArena *tmparena; + current = moduleParams; + tmparena = nssArena_Create(); + if (!tmparena) { + return PR_FAILURE; + } + while (nssrv == PR_SUCCESS) { + nssrv = nssCryptokiArgs_ParseNextPair(current, + &attrib, &value, + &remainder, tmparena); + if (nssrv != PR_SUCCESS) break; + if (value) { + if (nssUTF8_Equal(attrib, "name", &nssrv)) { + mod->base.name = nssUTF8_Duplicate(value, arena); + } else if (nssUTF8_Equal(attrib, "library", &nssrv)) { + mod->libraryName = nssUTF8_Duplicate(value, arena); + } else if (nssUTF8_Equal(attrib, "parameters", &nssrv)) { + mod->libraryParams = nssUTF8_Duplicate(value, arena); + } else if (nssUTF8_Equal(attrib, "NSS", &nssrv)) { + parse_nss_parameters(mod, value, tmparena, slotParams); + } + } + if (*remainder == '\0') break; + current = remainder; + } + nssArena_Destroy(tmparena); + return nssrv; +} + +static NSSUTF8 ** +get_module_specs +( + NSSModule *mod +) +{ + SECMODModuleDBFunc func = (SECMODModuleDBFunc)mod->moduleDBFunc; + if (func) { + return (*func)(SECMOD_MODULE_DB_FUNCTION_FIND, + mod->libraryParams, + NULL); + } + return NULL; +} + +/* XXX continue working on */ +NSS_IMPLEMENT NSSModule * +nssModule_CreateFromSpec +( + NSSUTF8 *moduleSpec, + NSSModule *parent, + PRBool loadSubModules +) +{ + PRStatus nssrv; + NSSModule *thisModule; + NSSArena *arena; + NSSUTF8 *slotParams = NULL; + arena = nssArena_Create(); + if (!arena) { + return NULL; + } + thisModule = nss_ZNEW(arena, NSSModule); + if (!thisModule) { + goto loser; + } + thisModule->base.lock = PZ_NewLock(nssILockOther); + if (!thisModule->base.lock) { + goto loser; + } + PR_AtomicIncrement(&thisModule->base.refCount); + thisModule->base.arena = arena; + thisModule->base.lock = PZ_NewLock(nssNSSILockOther); + if (!thisModule->base.lock) { + goto loser; + } + nssrv = parse_module_parameters(thisModule, moduleSpec, &slotParams); + if (nssrv != PR_SUCCESS) { + goto loser; + } + nssrv = nssModule_Load(thisModule); + if (nssrv != PR_SUCCESS) { + goto loser; + } + if (slotParams) { + nssrv = parse_module_slot_parameters(thisModule, slotParams); + nss_ZFreeIf(slotParams); + if (nssrv != PR_SUCCESS) { + goto loser; + } + } + if (loadSubModules && NSSMODULE_IS_MODULE_DB(thisModule)) { + NSSUTF8 **moduleSpecs; + NSSUTF8 **index; + /* get the array of sub modules one level below this module */ + moduleSpecs = get_module_specs(thisModule); + /* iterate over the array */ + for (index = moduleSpecs; index && *index; index++) { + NSSModule *child; + /* load the child recursively */ + child = nssModule_CreateFromSpec(*index, thisModule, PR_TRUE); + if (!child) { + /* when children fail, does the parent? */ + nssrv = PR_FAILURE; + break; + } + if (NSSMODULE_IS_CRITICAL(child) && !child->isLoaded) { + nssrv = PR_FAILURE; + nssModule_Destroy(child); + break; + } + nssModule_Destroy(child); + /*nss_ZFreeIf(*index);*/ + } + /*nss_ZFreeIf(moduleSpecs);*/ + } + /* The global list inherits the reference */ + nssrv = nssGlobalModuleList_Add(thisModule); + if (nssrv != PR_SUCCESS) { + goto loser; + } + return thisModule; +loser: + if (thisModule->base.lock) { + PZ_DestroyLock(thisModule->base.lock); + } + nssArena_Destroy(arena); + return (NSSModule *)NULL; +} + +NSS_IMPLEMENT PRStatus +nssModule_Destroy +( + NSSModule *mod +) +{ + PRUint32 i, numSlots; + PR_AtomicDecrement(&mod->base.refCount); + if (mod->base.refCount == 0) { + if (mod->numSlots == 0) { + (void)nssModule_Unload(mod); + return nssArena_Destroy(mod->base.arena); + } else { + numSlots = mod->numSlots; + for (i=0; i<numSlots; i++) { + nssSlot_Destroy(mod->slots[i]); + } + } + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssModule_DestroyFromSlot +( + NSSModule *mod, + NSSSlot *slot +) +{ + PRUint32 i, numSlots = 0; + PR_ASSERT(mod->base.refCount == 0); + for (i=0; i<mod->numSlots; i++) { + if (mod->slots[i] == slot) { + mod->slots[i] = NULL; + } else if (mod->slots[i]) { + numSlots++; + } + } + if (numSlots == 0) { + (void)nssModule_Unload(mod); + return nssArena_Destroy(mod->base.arena); + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT NSSModule * +nssModule_AddRef +( + NSSModule *mod +) +{ + PR_AtomicIncrement(&mod->base.refCount); + return mod; +} + +NSS_IMPLEMENT NSSUTF8 * +nssModule_GetName +( + NSSModule *mod +) +{ + return mod->base.name; +} + +NSS_IMPLEMENT PRBool +nssModule_IsThreadSafe +( + NSSModule *module +) +{ + return NSSMODULE_IS_THREADSAFE(module); +} + +NSS_IMPLEMENT PRBool +nssModule_IsInternal +( + NSSModule *mod +) +{ + return NSSMODULE_IS_INTERNAL(mod); +} + +NSS_IMPLEMENT PRBool +nssModule_IsModuleDBOnly +( + NSSModule *mod +) +{ + return NSSMODULE_IS_MODULE_DB_ONLY(mod); +} + +NSS_IMPLEMENT void * +nssModule_GetCryptokiEPV +( + NSSModule *mod +) +{ + return mod->epv; +} + +NSS_IMPLEMENT NSSSlot ** +nssModule_GetSlots +( + NSSModule *mod +) +{ + PRUint32 i; + NSSSlot **rvSlots; + rvSlots = nss_ZNEWARRAY(NULL, NSSSlot *, mod->numSlots + 1); + if (rvSlots) { + for (i=0; i<mod->numSlots; i++) { + rvSlots[i] = nssSlot_AddRef(mod->slots[i]); + } + } + return rvSlots; +} + +NSS_IMPLEMENT NSSSlot * +nssModule_FindSlotByName +( + NSSModule *mod, + NSSUTF8 *slotName +) +{ + PRUint32 i; + PRStatus nssrv; + NSSSlot *slot; + NSSUTF8 *name; + for (i=0; i<mod->numSlots; i++) { + slot = mod->slots[i]; + name = nssSlot_GetName(slot); + if (nssUTF8_Equal(name, slotName, &nssrv)) { + return nssSlot_AddRef(slot); + } + if (nssrv != PR_SUCCESS) { + break; + } + } + return (NSSSlot *)NULL; +} + +NSS_IMPLEMENT NSSToken * +nssModule_FindTokenByName +( + NSSModule *mod, + NSSUTF8 *tokenName +) +{ + PRUint32 i; + PRStatus nssrv; + NSSToken *tok; + NSSUTF8 *name; + for (i=0; i<mod->numSlots; i++) { + tok = nssSlot_GetToken(mod->slots[i]); + if (tok) { + name = nssToken_GetName(tok); + if (nssUTF8_Equal(name, tokenName, &nssrv)) { + return tok; + } + if (nssrv != PR_SUCCESS) { + break; + } + } + } + return (NSSToken *)NULL; +} + +NSS_IMPLEMENT PRInt32 +nssModule_GetCertOrder +( + NSSModule *module +) +{ + return 1; /* XXX */ +} + +#endif /* PURE_STAN_BUILD */ + diff --git a/security/nss/lib/dev/devslot.c b/security/nss/lib/dev/devslot.c new file mode 100644 index 000000000..0370b9be3 --- /dev/null +++ b/security/nss/lib/dev/devslot.c @@ -0,0 +1,834 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifdef DEBUG +static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKEPV_H +#include "nssckepv.h" +#endif /* NSSCKEPV_H */ + +#ifndef DEVM_H +#include "devm.h" +#endif /* DEVM_H */ + +#ifndef CKHELPER_H +#include "ckhelper.h" +#endif /* CKHELPER_H */ + +/* measured in seconds */ +#define NSSSLOT_TOKEN_DELAY_TIME 10 + +/* this should track global and per-transaction login information */ + +#ifdef PURE_STAN_CODE +typedef enum { + nssSlotAskPasswordTimes_FirstTime = 0, + nssSlotAskPasswordTimes_EveryTime = 1, + nssSlotAskPasswordTimes_Timeout = 2 +} +nssSlotAskPasswordTimes; + +struct nssSlotAuthInfoStr +{ + PRTime lastLogin; + nssSlotAskPasswordTimes askTimes; + PRIntervalTime askPasswordTimeout; +}; + +struct NSSSlotStr +{ + struct nssDeviceBaseStr base; + NSSModule *module; /* Parent */ + NSSToken *token; /* Peer */ + CK_SLOT_ID slotID; + CK_FLAGS ckFlags; /* from CK_SLOT_INFO.flags */ + struct nssSlotAuthInfoStr authInfo; + PRIntervalTime lastTokenPing; +#ifdef NSS_3_4_CODE + PK11SlotInfo *pk11slot; +#endif +}; +#endif /* PURE_STAN_CODE */ + +#define NSSSLOT_IS_FRIENDLY(slot) \ + (slot->base.flags & NSSSLOT_FLAGS_FRIENDLY) + +/* measured as interval */ +static PRIntervalTime s_token_delay_time = 0; + +/* The flags needed to open a read-only session. */ +static const CK_FLAGS s_ck_readonly_flags = CKF_SERIAL_SESSION; + +/* In pk11slot.c, this was a no-op. So it is here also. */ +static CK_RV PR_CALLBACK +nss_ck_slot_notify +( + CK_SESSION_HANDLE session, + CK_NOTIFICATION event, + CK_VOID_PTR pData +) +{ + return CKR_OK; +} + +#ifdef PURE_STAN_BUILD +NSS_IMPLEMENT NSSSlot * +nssSlot_Create +( + CK_SLOT_ID slotID, + NSSModule *parent +) +{ + NSSArena *arena = NULL; + NSSSlot *rvSlot; + NSSToken *token = NULL; + NSSUTF8 *slotName = NULL; + PRUint32 length; + CK_SLOT_INFO slotInfo; + CK_RV ckrv; + void *epv; + arena = NSSArena_Create(); + if(!arena) { + return (NSSSlot *)NULL; + } + rvSlot = nss_ZNEW(arena, NSSSlot); + if (!rvSlot) { + goto loser; + } + /* Get slot information */ + epv = nssModule_GetCryptokiEPV(parent); + ckrv = CKAPI(epv)->C_GetSlotInfo(slotID, &slotInfo); + if (ckrv != CKR_OK) { + /* set an error here, eh? */ + goto loser; + } + /* Grab the slot description from the PKCS#11 fixed-length buffer */ + length = nssPKCS11String_Length(slotInfo.slotDescription, + sizeof(slotInfo.slotDescription)); + if (length > 0) { + slotName = nssUTF8_Create(arena, nssStringType_UTF8String, + (void *)slotInfo.slotDescription, length); + if (!slotName) { + goto loser; + } + } + rvSlot->base.arena = arena; + rvSlot->base.refCount = 1; + rvSlot->base.name = slotName; + rvSlot->base.lock = PZ_NewLock(nssNSSILockOther); /* XXX */ + if (!rvSlot->base.lock) { + goto loser; + } + rvSlot->module = parent; /* refs go from module to slots */ + rvSlot->slotID = slotID; + rvSlot->ckFlags = slotInfo.flags; + /* Initialize the token if present. */ + if (slotInfo.flags & CKF_TOKEN_PRESENT) { + token = nssToken_Create(slotID, rvSlot); + if (!token) { + goto loser; + } + } + rvSlot->token = token; + return rvSlot; +loser: + nssArena_Destroy(arena); + /* everything was created in the arena, nothing to see here, move along */ + return (NSSSlot *)NULL; +} +#endif /* PURE_STAN_BUILD */ + +NSS_IMPLEMENT PRStatus +nssSlot_Destroy +( + NSSSlot *slot +) +{ + if (slot) { + PR_AtomicDecrement(&slot->base.refCount); + if (slot->base.refCount == 0) { + PZ_DestroyLock(slot->base.lock); +#ifdef PURE_STAN_BUILD + nssToken_Destroy(slot->token); + nssModule_DestroyFromSlot(slot->module, slot); +#endif + return nssArena_Destroy(slot->base.arena); + } + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT void +NSSSlot_Destroy +( + NSSSlot *slot +) +{ + (void)nssSlot_Destroy(slot); +} + +NSS_IMPLEMENT NSSSlot * +nssSlot_AddRef +( + NSSSlot *slot +) +{ + PR_AtomicIncrement(&slot->base.refCount); + return slot; +} + +NSS_IMPLEMENT NSSUTF8 * +nssSlot_GetName +( + NSSSlot *slot +) +{ + return slot->base.name; +} + +NSS_IMPLEMENT NSSUTF8 * +nssSlot_GetTokenName +( + NSSSlot *slot +) +{ + return nssToken_GetName(slot->token); +} + +static PRBool +within_token_delay_period(NSSSlot *slot) +{ + PRIntervalTime time, lastTime; + /* Set the delay time for checking the token presence */ + if (s_token_delay_time == 0) { + s_token_delay_time = PR_SecondsToInterval(NSSSLOT_TOKEN_DELAY_TIME); + } + time = PR_IntervalNow(); + lastTime = slot->lastTokenPing; + if ((time > lastTime) && ((time - lastTime) < s_token_delay_time)) { + return PR_TRUE; + } + slot->lastTokenPing = time; + return PR_FALSE; +} + +NSS_IMPLEMENT PRBool +nssSlot_IsTokenPresent +( + NSSSlot *slot +) +{ + CK_RV ckrv; + PRStatus nssrv; + /* XXX */ + nssSession *session; + CK_SLOT_INFO slotInfo; + void *epv; + /* permanent slots are always present */ + if (nssSlot_IsPermanent(slot)) { + return PR_TRUE; + } + /* avoid repeated calls to check token status within set interval */ + if (within_token_delay_period(slot)) { + return (PRBool)((slot->ckFlags & CKF_TOKEN_PRESENT) != 0); + } + /* First obtain the slot info */ +#ifdef PURE_STAN_BUILD + epv = nssModule_GetCryptokiEPV(slot->module); +#else + epv = slot->epv; +#endif + if (!epv) { + return PR_FALSE; + } + ckrv = CKAPI(epv)->C_GetSlotInfo(slot->slotID, &slotInfo); + if (ckrv != CKR_OK) { + slot->token->base.name[0] = 0; /* XXX */ + return PR_FALSE; + } + slot->ckFlags = slotInfo.flags; + /* check for the presence of the token */ + if ((slot->ckFlags & CKF_TOKEN_PRESENT) == 0) { + if (!slot->token) { + /* token was ne'er present */ + return PR_FALSE; + } + session = nssToken_GetDefaultSession(slot->token); + nssSession_EnterMonitor(session); + /* token is not present */ + if (session->handle != CK_INVALID_SESSION) { + /* session is valid, close and invalidate it */ + CKAPI(epv)->C_CloseSession(session->handle); + session->handle = CK_INVALID_SESSION; + } + nssSession_ExitMonitor(session); +#ifdef NSS_3_4_CODE + if (slot->token->base.name[0] != 0) { + /* notify the high-level cache that the token is removed */ + slot->token->base.name[0] = 0; /* XXX */ + nssToken_NotifyCertsNotVisible(slot->token); + } +#endif + slot->token->base.name[0] = 0; /* XXX */ + /* clear the token cache */ + nssToken_Remove(slot->token); + return PR_FALSE; +#ifdef PURE_STAN_CODE + } else if (!slot->token) { + /* token was not present at boot time, is now */ + slot->token = nssToken_Create(slot->slotID, slot); + return (slot->token != NULL); +#endif + } + /* token is present, use the session info to determine if the card + * has been removed and reinserted. + */ + session = nssToken_GetDefaultSession(slot->token); + nssSession_EnterMonitor(session); + if (session->handle != CK_INVALID_SESSION) { + CK_SESSION_INFO sessionInfo; + ckrv = CKAPI(epv)->C_GetSessionInfo(session->handle, &sessionInfo); + if (ckrv != CKR_OK) { + /* session is screwy, close and invalidate it */ + CKAPI(epv)->C_CloseSession(session->handle); + session->handle = CK_INVALID_SESSION; + } + } + nssSession_ExitMonitor(session); + /* token not removed, finished */ + if (session->handle != CK_INVALID_SESSION) { + return PR_TRUE; + } else { + /* token has been removed, need to refresh with new session */ + nssrv = nssSlot_Refresh(slot); + if (nssrv != PR_SUCCESS) { + slot->token->base.name[0] = 0; /* XXX */ + return PR_FALSE; + } + return PR_TRUE; + } +} + +#ifdef PURE_STAN_BUILD +NSS_IMPLEMENT NSSModule * +nssSlot_GetModule +( + NSSSlot *slot +) +{ + return nssModule_AddRef(slot->module); +} +#endif /* PURE_STAN_BUILD */ + +NSS_IMPLEMENT void * +nssSlot_GetCryptokiEPV +( + NSSSlot *slot +) +{ +#ifdef PURE_STAN_BUILD + return nssModule_GetCryptokiEPV(slot->module); +#else + return slot->epv; +#endif +} + +NSS_IMPLEMENT NSSToken * +nssSlot_GetToken +( + NSSSlot *slot +) +{ + if (nssSlot_IsTokenPresent(slot)) { + return nssToken_AddRef(slot->token); + } + return (NSSToken *)NULL; +} + +#ifdef PURE_STAN_BUILD +NSS_IMPLEMENT PRBool +nssSlot_IsPermanent +( + NSSSlot *slot +) +{ + return (!(slot->ckFlags & CKF_REMOVABLE_DEVICE)); +} + +NSS_IMPLEMENT PRBool +nssSlot_IsFriendly +( + NSSSlot *slot +) +{ + return PR_TRUE /* XXX NSSSLOT_IS_FRIENDLY(slot)*/; +} + +NSS_IMPLEMENT PRBool +nssSlot_IsHardware +( + NSSSlot *slot +) +{ + return (slot->ckFlags & CKF_HW_SLOT); +} + +NSS_IMPLEMENT PRStatus +nssSlot_Refresh +( + NSSSlot *slot +) +{ + /* XXX */ +#if 0 + nssToken_Destroy(slot->token); + if (slotInfo.flags & CKF_TOKEN_PRESENT) { + slot->token = nssToken_Create(NULL, slotID, slot); + } +#endif + return PR_SUCCESS; +} + +static PRBool +slot_needs_login +( + NSSSlot *slot, + nssSession *session +) +{ + PRBool needsLogin, logout; + struct nssSlotAuthInfoStr *authInfo = &slot->authInfo; + void *epv = nssModule_GetCryptokiEPV(slot->module); + if (!nssToken_IsLoginRequired(slot->token)) { + return PR_FALSE; + } + if (authInfo->askTimes == nssSlotAskPasswordTimes_EveryTime) { + logout = PR_TRUE; + } else if (authInfo->askTimes == nssSlotAskPasswordTimes_Timeout) { + PRIntervalTime currentTime = PR_IntervalNow(); + if (authInfo->lastLogin - currentTime < authInfo->askPasswordTimeout) { + logout = PR_FALSE; + } else { + logout = PR_TRUE; + } + } else { /* nssSlotAskPasswordTimes_FirstTime */ + logout = PR_FALSE; + } + if (logout) { + /* The login has expired, timeout */ + nssSession_EnterMonitor(session); + CKAPI(epv)->C_Logout(session->handle); + nssSession_ExitMonitor(session); + needsLogin = PR_TRUE; + } else { + CK_RV ckrv; + CK_SESSION_INFO sessionInfo; + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_GetSessionInfo(session->handle, &sessionInfo); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK) { + /* XXX error -- invalidate session */ + return PR_FALSE; + } + switch (sessionInfo.state) { + case CKS_RW_PUBLIC_SESSION: + case CKS_RO_PUBLIC_SESSION: + default: + needsLogin = PR_TRUE; + break; + case CKS_RW_USER_FUNCTIONS: + case CKS_RW_SO_FUNCTIONS: + case CKS_RO_USER_FUNCTIONS: + needsLogin = PR_FALSE; + break; + } + } + return needsLogin; +} + +static PRStatus +slot_login +( + NSSSlot *slot, + nssSession *session, + CK_USER_TYPE userType, + NSSCallback *pwcb +) +{ + PRStatus nssrv; + PRUint32 attempts; + PRBool keepTrying; + NSSUTF8 *password = NULL; + CK_ULONG pwLen; + CK_RV ckrv; + void *epv; + if (!pwcb->getPW) { + /* set error INVALID_ARG */ + return PR_FAILURE; + } + epv = nssModule_GetCryptokiEPV(slot->module); + keepTrying = PR_TRUE; + nssrv = PR_FAILURE; + attempts = 0; + while (keepTrying) { + /* use the token name, since it is present */ + NSSUTF8 *tokenName = nssToken_GetName(slot->token); + nssrv = pwcb->getPW(tokenName, attempts, pwcb->arg, &password); + if (nssrv != PR_SUCCESS) { + nss_SetError(NSS_ERROR_USER_CANCELED); + break; + } + pwLen = (CK_ULONG)nssUTF8_Length(password, &nssrv); + if (nssrv != PR_SUCCESS) { + break; + } + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_Login(session->handle, userType, + (CK_CHAR_PTR)password, pwLen); + nssSession_ExitMonitor(session); + switch (ckrv) { + case CKR_OK: + case CKR_USER_ALREADY_LOGGED_IN: + slot->authInfo.lastLogin = PR_Now(); + nssrv = PR_SUCCESS; + keepTrying = PR_FALSE; + break; + case CKR_PIN_INCORRECT: + nss_SetError(NSS_ERROR_INVALID_PASSWORD); + keepTrying = PR_TRUE; /* received bad pw, keep going */ + break; + default: + nssrv = PR_FAILURE; + keepTrying = PR_FALSE; + break; + } + nss_ZFreeIf(password); + password = NULL; + ++attempts; + } + return nssrv; +} + +static PRStatus +init_slot_password +( + NSSSlot *slot, + nssSession *rwSession, + NSSUTF8 *password +) +{ + PRStatus status; + NSSUTF8 *ssoPW = ""; + CK_ULONG userPWLen, ssoPWLen; + CK_RV ckrv; + void *epv = nssModule_GetCryptokiEPV(slot->module); + /* Get the SO and user passwords */ + userPWLen = (CK_ULONG)nssUTF8_Length(password, &status); + if (status != PR_SUCCESS) { + goto loser; + } + ssoPWLen = (CK_ULONG)nssUTF8_Length(ssoPW, &status); + if (status != PR_SUCCESS) { + goto loser; + } + /* First log in as SO */ + ckrv = CKAPI(epv)->C_Login(rwSession->handle, CKU_SO, + (CK_CHAR_PTR)ssoPW, ssoPWLen); + if (ckrv != CKR_OK) { + /* set error ...SO_LOGIN_FAILED */ + goto loser; + } + /* Now change the user PIN */ + ckrv = CKAPI(epv)->C_InitPIN(rwSession->handle, + (CK_CHAR_PTR)password, userPWLen); + if (ckrv != CKR_OK) { + /* set error */ + goto loser; + } + return PR_SUCCESS; +loser: + return PR_FAILURE; +} + +static PRStatus +change_slot_password +( + NSSSlot *slot, + nssSession *rwSession, + NSSUTF8 *oldPassword, + NSSUTF8 *newPassword +) +{ + PRStatus status; + CK_ULONG userPWLen, newPWLen; + CK_RV ckrv; + void *epv = nssModule_GetCryptokiEPV(slot->module); + userPWLen = (CK_ULONG)nssUTF8_Length(oldPassword, &status); + if (status != PR_SUCCESS) { + return status; + } + newPWLen = (CK_ULONG)nssUTF8_Length(newPassword, &status); + if (status != PR_SUCCESS) { + return status; + } + nssSession_EnterMonitor(rwSession); + ckrv = CKAPI(epv)->C_SetPIN(rwSession->handle, + (CK_CHAR_PTR)oldPassword, userPWLen, + (CK_CHAR_PTR)newPassword, newPWLen); + nssSession_ExitMonitor(rwSession); + switch (ckrv) { + case CKR_OK: + slot->authInfo.lastLogin = PR_Now(); + status = PR_SUCCESS; + break; + case CKR_PIN_INCORRECT: + nss_SetError(NSS_ERROR_INVALID_PASSWORD); + status = PR_FAILURE; + break; + default: + status = PR_FAILURE; + break; + } + return status; +} + +NSS_IMPLEMENT PRStatus +nssSlot_Login +( + NSSSlot *slot, + NSSCallback *pwcb +) +{ + PRStatus status; + CK_USER_TYPE userType = CKU_USER; + NSSToken *token = nssSlot_GetToken(slot); + nssSession *session; + if (!token) { + return PR_FAILURE; + } + if (!nssToken_IsLoginRequired(token)) { + nssToken_Destroy(token); + return PR_SUCCESS; + } + session = nssToken_GetDefaultSession(slot->token); + if (nssToken_NeedsPINInitialization(token)) { + NSSUTF8 *password = NULL; + if (!pwcb->getInitPW) { + nssToken_Destroy(token); + return PR_FAILURE; /* don't know how to get initial password */ + } + status = (*pwcb->getInitPW)(slot->base.name, pwcb->arg, &password); + if (status == PR_SUCCESS) { + session = nssSlot_CreateSession(slot, NULL, PR_TRUE); + status = init_slot_password(slot, session, password); + nssSession_Destroy(session); + } + } else if (slot_needs_login(slot, session)) { + status = slot_login(slot, session, userType, pwcb); + } else { + status = PR_SUCCESS; + } + nssToken_Destroy(token); + return status; +} + +NSS_IMPLEMENT PRStatus +nssSlot_Logout +( + NSSSlot *slot, + nssSession *sessionOpt +) +{ + PRStatus nssrv = PR_SUCCESS; + nssSession *session; + CK_RV ckrv; + void *epv = nssModule_GetCryptokiEPV(slot->module); + session = sessionOpt ? + sessionOpt : + nssToken_GetDefaultSession(slot->token); + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_Logout(session->handle); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK) { + /* translate the error */ + nssrv = PR_FAILURE; + } + return nssrv; +} + +NSS_IMPLEMENT PRBool +nssSlot_IsLoggedIn +( + NSSSlot *slot +) +{ + nssSession *session = nssToken_GetDefaultSession(slot->token); + return !slot_needs_login(slot, session); +} + +NSS_IMPLEMENT void +nssSlot_SetPasswordDefaults +( + NSSSlot *slot, + PRInt32 askPasswordTimeout +) +{ + slot->authInfo.askPasswordTimeout = askPasswordTimeout; +} + + +NSS_IMPLEMENT PRStatus +nssSlot_SetPassword +( + NSSSlot *slot, + NSSUTF8 *oldPasswordOpt, + NSSUTF8 *newPassword +) +{ + PRStatus status; + nssSession *rwSession; + NSSToken *token = nssSlot_GetToken(slot); + if (!token) { + return PR_FAILURE; + } + rwSession = nssSlot_CreateSession(slot, NULL, PR_TRUE); + if (nssToken_NeedsPINInitialization(token)) { + status = init_slot_password(slot, rwSession, newPassword); + } else if (oldPasswordOpt) { + status = change_slot_password(slot, rwSession, + oldPasswordOpt, newPassword); + } else { + /* old password must be given in order to change */ + status = PR_FAILURE; + } + nssSession_Destroy(rwSession); + nssToken_Destroy(token); + return status; +} + +NSS_IMPLEMENT nssSession * +nssSlot_CreateSession +( + NSSSlot *slot, + NSSArena *arenaOpt, + PRBool readWrite /* so far, this is the only flag used */ +) +{ + CK_RV ckrv; + CK_FLAGS ckflags; + CK_SESSION_HANDLE handle; + void *epv = nssModule_GetCryptokiEPV(slot->module); + nssSession *rvSession; + ckflags = s_ck_readonly_flags; + if (readWrite) { + ckflags |= CKF_RW_SESSION; + } + ckrv = CKAPI(epv)->C_OpenSession(slot->slotID, ckflags, + slot, nss_ck_slot_notify, &handle); + if (ckrv != CKR_OK) { + /* set an error here, eh? */ + return (nssSession *)NULL; + } + rvSession = nss_ZNEW(arenaOpt, nssSession); + if (!rvSession) { + return (nssSession *)NULL; + } + if (!nssModule_IsThreadSafe(slot->module)) { + /* If the parent module is not threadsafe, create lock to manage + * session within threads. + */ + rvSession->lock = PZ_NewLock(nssILockOther); + if (!rvSession->lock) { + /* need to translate NSPR error? */ + if (arenaOpt) { + } else { + nss_ZFreeIf(rvSession); + } + return (nssSession *)NULL; + } + } + rvSession->handle = handle; + rvSession->slot = slot; + rvSession->isRW = readWrite; + return rvSession; +} + +NSS_IMPLEMENT PRStatus +nssSession_Destroy +( + nssSession *s +) +{ + CK_RV ckrv = CKR_OK; + if (s) { + void *epv = s->slot->epv; + ckrv = CKAPI(epv)->C_CloseSession(s->handle); + if (s->lock) { + PZ_DestroyLock(s->lock); + } + nss_ZFreeIf(s); + } + return (ckrv == CKR_OK) ? PR_SUCCESS : PR_FAILURE; +} +#endif /* PURE_STAN_BUILD */ + +NSS_IMPLEMENT PRStatus +nssSession_EnterMonitor +( + nssSession *s +) +{ + if (s->lock) PZ_Lock(s->lock); + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssSession_ExitMonitor +( + nssSession *s +) +{ + return (s->lock) ? PZ_Unlock(s->lock) : PR_SUCCESS; +} + +NSS_EXTERN PRBool +nssSession_IsReadWrite +( + nssSession *s +) +{ + return s->isRW; +} + diff --git a/security/nss/lib/dev/devt.h b/security/nss/lib/dev/devt.h new file mode 100644 index 000000000..10a7978c3 --- /dev/null +++ b/security/nss/lib/dev/devt.h @@ -0,0 +1,202 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef DEVT_H +#define DEVT_H + +#ifdef DEBUG +static const char DEVT_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +/* + * devt.h + * + * This file contains definitions for the low-level cryptoki devices. + */ + +#ifndef NSSBASET_H +#include "nssbaset.h" +#endif /* NSSBASET_H */ + +#ifndef NSSPKIT_H +#include "nsspkit.h" +#endif /* NSSPKIT_H */ + +#ifndef NSSDEVT_H +#include "nssdevt.h" +#endif /* NSSDEVT_H */ + +#ifndef NSSCKT_H +#include "nssckt.h" +#endif /* NSSCKT_H */ + +#ifndef BASET_H +#include "baset.h" +#endif /* BASET_H */ + +#ifdef NSS_3_4_CODE +#include "secmodt.h" +#endif /* NSS_3_4_CODE */ + +PR_BEGIN_EXTERN_C + +typedef struct nssSessionStr nssSession; + +/* XXX until NSSTokenStr is moved */ +struct nssDeviceBaseStr +{ + NSSArena *arena; + PZLock *lock; + PRInt32 refCount; + NSSUTF8 *name; + PRUint32 flags; +}; + +typedef struct nssTokenObjectCacheStr nssTokenObjectCache; + +/* XXX until devobject.c goes away */ +struct NSSTokenStr +{ + struct nssDeviceBaseStr base; + NSSSlot *slot; /* Parent (or peer, if you will) */ + CK_FLAGS ckFlags; /* from CK_TOKEN_INFO.flags */ + PRUint32 flags; + void *epv; + nssSession *defaultSession; + NSSTrustDomain *trustDomain; + PRIntervalTime lastTime; + nssTokenObjectCache *cache; +#ifdef NSS_3_4_CODE + PK11SlotInfo *pk11slot; +#endif +}; + +typedef enum { + nssSlotAskPasswordTimes_FirstTime = 0, + nssSlotAskPasswordTimes_EveryTime = 1, + nssSlotAskPasswordTimes_Timeout = 2 +} +nssSlotAskPasswordTimes; + +struct nssSlotAuthInfoStr +{ + PRTime lastLogin; + nssSlotAskPasswordTimes askTimes; + PRIntervalTime askPasswordTimeout; +}; + +struct NSSSlotStr +{ + struct nssDeviceBaseStr base; + NSSModule *module; /* Parent */ + NSSToken *token; /* Peer */ + CK_SLOT_ID slotID; + CK_FLAGS ckFlags; /* from CK_SLOT_INFO.flags */ + struct nssSlotAuthInfoStr authInfo; + PRIntervalTime lastTokenPing; +#ifdef NSS_3_4_CODE + void *epv; + PK11SlotInfo *pk11slot; +#endif +}; + +struct nssSessionStr +{ + PZLock *lock; + CK_SESSION_HANDLE handle; + NSSSlot *slot; + PRBool isRW; +}; + +typedef enum { + NSSCertificateType_Unknown = 0, + NSSCertificateType_PKIX = 1 +} NSSCertificateType; + +#ifdef nodef +/* the current definition of NSSTrust depends on this value being CK_ULONG */ +typedef CK_ULONG nssTrustLevel; +#else +typedef enum { + nssTrustLevel_Unknown = 0, + nssTrustLevel_NotTrusted = 1, + nssTrustLevel_Trusted = 2, + nssTrustLevel_TrustedDelegator = 3, + nssTrustLevel_Valid = 4, + nssTrustLevel_ValidDelegator = 5 +} nssTrustLevel; +#endif + +typedef struct nssCryptokiInstanceStr nssCryptokiInstance; + +struct nssCryptokiInstanceStr +{ + CK_OBJECT_HANDLE handle; + NSSToken *token; + PRBool isTokenObject; + NSSUTF8 *label; +}; + +typedef struct nssCryptokiInstanceStr nssCryptokiObject; + +typedef struct nssTokenCertSearchStr nssTokenCertSearch; + +typedef enum { + nssTokenSearchType_AllObjects = 0, + nssTokenSearchType_SessionOnly = 1, + nssTokenSearchType_TokenOnly = 2, + nssTokenSearchType_TokenForced = 3 +} nssTokenSearchType; + +struct nssTokenCertSearchStr +{ + nssTokenSearchType searchType; + PRStatus (* callback)(NSSCertificate *c, void *arg); + void *cbarg; + nssList *cached; + /* TODO: add a cache query callback if the list would be large + * (traversal) + */ +}; + +struct nssSlotListStr; +typedef struct nssSlotListStr nssSlotList; + +struct NSSAlgorithmAndParametersStr +{ + CK_MECHANISM mechanism; +}; + +PR_END_EXTERN_C + +#endif /* DEVT_H */ diff --git a/security/nss/lib/dev/devtm.h b/security/nss/lib/dev/devtm.h new file mode 100644 index 000000000..5e48c5d80 --- /dev/null +++ b/security/nss/lib/dev/devtm.h @@ -0,0 +1,58 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef DEVTM_H +#define DEVTM_H + +#ifdef DEBUG +static const char DEVTM_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +/* + * devtm.h + * + * This file contains module-private definitions for the low-level + * cryptoki devices. + */ + +#ifndef DEVT_H +#include "devt.h" +#endif /* DEVT_H */ + +PR_BEGIN_EXTERN_C + +#define MAX_LOCAL_CACHE_OBJECTS 10 + +PR_END_EXTERN_C + +#endif /* DEVTM_H */ diff --git a/security/nss/lib/dev/devtoken.c b/security/nss/lib/dev/devtoken.c new file mode 100644 index 000000000..a43ed43f4 --- /dev/null +++ b/security/nss/lib/dev/devtoken.c @@ -0,0 +1,1664 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifdef DEBUG +static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef NSSCKEPV_H +#include "nssckepv.h" +#endif /* NSSCKEPV_H */ + +#ifndef DEVM_H +#include "devm.h" +#endif /* DEVM_H */ + +#ifndef CKHELPER_H +#include "ckhelper.h" +#endif /* CKHELPER_H */ + +#ifdef NSS_3_4_CODE +#include "pk11func.h" +#include "dev3hack.h" +#endif + +/* The number of object handles to grab during each call to C_FindObjects */ +#define OBJECT_STACK_SIZE 16 + +#ifdef PURE_STAN_BUILD +struct NSSTokenStr +{ + struct nssDeviceBaseStr base; + NSSSlot *slot; /* Peer */ + CK_FLAGS ckFlags; /* from CK_TOKEN_INFO.flags */ + nssSession *defaultSession; + nssTokenObjectCache *cache; +}; + +NSS_IMPLEMENT NSSToken * +nssToken_Create +( + CK_SLOT_ID slotID, + NSSSlot *peer +) +{ + NSSArena *arena; + NSSToken *rvToken; + nssSession *session = NULL; + NSSUTF8 *tokenName = NULL; + PRUint32 length; + PRBool readWrite; + CK_TOKEN_INFO tokenInfo; + CK_RV ckrv; + void *epv = nssSlot_GetCryptokiEPV(peer); + arena = NSSArena_Create(); + if(!arena) { + return (NSSToken *)NULL; + } + rvToken = nss_ZNEW(arena, NSSToken); + if (!rvToken) { + goto loser; + } + /* Get token information */ + ckrv = CKAPI(epv)->C_GetTokenInfo(slotID, &tokenInfo); + if (ckrv != CKR_OK) { + /* set an error here, eh? */ + goto loser; + } + /* Grab the slot description from the PKCS#11 fixed-length buffer */ + length = nssPKCS11String_Length(tokenInfo.label, sizeof(tokenInfo.label)); + if (length > 0) { + tokenName = nssUTF8_Create(arena, nssStringType_UTF8String, + (void *)tokenInfo.label, length); + if (!tokenName) { + goto loser; + } + } + /* Open a default session handle for the token. */ + if (tokenInfo.ulMaxSessionCount == 1) { + /* if the token can only handle one session, it must be RW. */ + readWrite = PR_TRUE; + } else { + readWrite = PR_FALSE; + } + session = nssSlot_CreateSession(peer, arena, readWrite); + if (session == NULL) { + goto loser; + } + /* TODO: seed the RNG here */ + rvToken->base.arena = arena; + rvToken->base.refCount = 1; + rvToken->base.name = tokenName; + rvToken->base.lock = PZ_NewLock(nssNSSILockOther); /* XXX */ + if (!rvToken->base.lock) { + goto loser; + } + rvToken->slot = peer; /* slot owns ref to token */ + rvToken->ckFlags = tokenInfo.flags; + rvToken->defaultSession = session; + if (nssSlot_IsHardware(peer)) { + rvToken->cache = nssTokenObjectCache_Create(rvToken, + PR_TRUE, PR_TRUE, PR_TRUE); + if (!rvToken->cache) { + nssSlot_Destroy(peer); + goto loser; + } + } + return rvToken; +loser: + if (session) { + nssSession_Destroy(session); + } + nssArena_Destroy(arena); + return (NSSToken *)NULL; +} +#endif /* PURE_STAN_BUILD */ + +NSS_IMPLEMENT PRStatus +nssToken_Destroy +( + NSSToken *tok +) +{ + if (tok) { + PR_AtomicDecrement(&tok->base.refCount); + if (tok->base.refCount == 0) { + PZ_DestroyLock(tok->base.lock); + nssTokenObjectCache_Destroy(tok->cache); + return nssArena_Destroy(tok->base.arena); + } + } + return PR_SUCCESS; +} + +NSS_IMPLEMENT void +nssToken_Remove +( + NSSToken *tok +) +{ + nssTokenObjectCache_Clear(tok->cache); +} + +NSS_IMPLEMENT void +NSSToken_Destroy +( + NSSToken *tok +) +{ + (void)nssToken_Destroy(tok); +} + +NSS_IMPLEMENT NSSToken * +nssToken_AddRef +( + NSSToken *tok +) +{ + PR_AtomicIncrement(&tok->base.refCount); + return tok; +} + +NSS_IMPLEMENT NSSSlot * +nssToken_GetSlot +( + NSSToken *tok +) +{ + return nssSlot_AddRef(tok->slot); +} + +#ifdef PURE_STAN_BUILD +NSS_IMPLEMENT NSSModule * +nssToken_GetModule +( + NSSToken *token +) +{ + return nssSlot_GetModule(token->slot); +} +#endif + +NSS_IMPLEMENT void * +nssToken_GetCryptokiEPV +( + NSSToken *token +) +{ + return nssSlot_GetCryptokiEPV(token->slot); +} + +NSS_IMPLEMENT nssSession * +nssToken_GetDefaultSession +( + NSSToken *token +) +{ + return token->defaultSession; +} + +NSS_IMPLEMENT NSSUTF8 * +nssToken_GetName +( + NSSToken *tok +) +{ + if (tok == NULL) { + return ""; + } + if (tok->base.name[0] == 0) { + (void) nssSlot_IsTokenPresent(tok->slot); + } + return tok->base.name; +} + +NSS_IMPLEMENT NSSUTF8 * +NSSToken_GetName +( + NSSToken *token +) +{ + return nssToken_GetName(token); +} + +NSS_IMPLEMENT PRBool +nssToken_IsLoginRequired +( + NSSToken *token +) +{ + return (token->ckFlags & CKF_LOGIN_REQUIRED); +} + +NSS_IMPLEMENT PRBool +nssToken_NeedsPINInitialization +( + NSSToken *token +) +{ + return (!(token->ckFlags & CKF_USER_PIN_INITIALIZED)); +} + +NSS_IMPLEMENT PRStatus +nssToken_DeleteStoredObject +( + nssCryptokiObject *instance +) +{ + CK_RV ckrv; + PRStatus status; + PRBool createdSession = PR_FALSE; + NSSToken *token = instance->token; + nssSession *session = NULL; + void *epv = nssToken_GetCryptokiEPV(instance->token); + if (token->cache) { + nssTokenObjectCache_RemoveObject(token->cache, instance); + } + if (instance->isTokenObject) { + if (nssSession_IsReadWrite(token->defaultSession)) { + session = token->defaultSession; + } else { + session = nssSlot_CreateSession(token->slot, NULL, PR_TRUE); + createdSession = PR_TRUE; + } + } + if (session == NULL) { + return PR_FAILURE; + } + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_DestroyObject(session->handle, instance->handle); + nssSession_ExitMonitor(session); + if (createdSession) { + nssSession_Destroy(session); + } + status = (ckrv == CKR_OK) ? PR_SUCCESS : PR_FAILURE; + return status; +} + +static nssCryptokiObject * +import_object +( + NSSToken *tok, + nssSession *sessionOpt, + CK_ATTRIBUTE_PTR objectTemplate, + CK_ULONG otsize +) +{ + nssSession *session = NULL; + PRBool createdSession = PR_FALSE; + nssCryptokiObject *object = NULL; + CK_OBJECT_HANDLE handle; + CK_RV ckrv; + void *epv = nssToken_GetCryptokiEPV(tok); + if (nssCKObject_IsTokenObjectTemplate(objectTemplate, otsize)) { + if (sessionOpt) { + if (!nssSession_IsReadWrite(sessionOpt)) { + return CK_INVALID_HANDLE; + } else { + session = sessionOpt; + } + } else if (nssSession_IsReadWrite(tok->defaultSession)) { + session = tok->defaultSession; + } else { + session = nssSlot_CreateSession(tok->slot, NULL, PR_TRUE); + createdSession = PR_TRUE; + } + } else { + session = (sessionOpt) ? sessionOpt : tok->defaultSession; + } + if (session == NULL) { + return CK_INVALID_HANDLE; + } + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_CreateObject(session->handle, + objectTemplate, otsize, + &handle); + nssSession_ExitMonitor(session); + if (ckrv == CKR_OK) { + object = nssCryptokiObject_Create(tok, session, handle); + } + if (createdSession) { + nssSession_Destroy(session); + } + return object; +} + +static nssCryptokiObject ** +create_objects_from_handles +( + NSSToken *tok, + nssSession *session, + CK_OBJECT_HANDLE *handles, + PRUint32 numH +) +{ + nssCryptokiObject **objects; + objects = nss_ZNEWARRAY(NULL, nssCryptokiObject *, numH + 1); + if (objects) { + PRInt32 i; + for (i=0; i<(PRInt32)numH; i++) { + objects[i] = nssCryptokiObject_Create(tok, session, handles[i]); + if (!objects[i]) { + for (--i; i>0; --i) { + nssCryptokiObject_Destroy(objects[i]); + } + return (nssCryptokiObject **)NULL; + } + } + } + return objects; +} + +static nssCryptokiObject ** +find_objects +( + NSSToken *tok, + nssSession *sessionOpt, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG otsize, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_RV ckrv; + CK_ULONG count; + CK_OBJECT_HANDLE *objectHandles; + PRUint32 arraySize, numHandles; + void *epv = nssToken_GetCryptokiEPV(tok); + nssCryptokiObject **objects; + NSSArena *arena; + nssSession *session = (sessionOpt) ? sessionOpt : tok->defaultSession; + /* the arena is only for the array of object handles */ + arena = nssArena_Create(); + if (!arena) { + if (statusOpt) *statusOpt = PR_FAILURE; + return (nssCryptokiObject **)NULL; + } + if (maximumOpt > 0) { + arraySize = maximumOpt; + } else { + arraySize = OBJECT_STACK_SIZE; + } + numHandles = 0; + objectHandles = nss_ZNEWARRAY(arena, CK_OBJECT_HANDLE, arraySize); + if (!objectHandles) { + goto loser; + } + nssSession_EnterMonitor(session); /* ==== session lock === */ + /* Initialize the find with the template */ + ckrv = CKAPI(epv)->C_FindObjectsInit(session->handle, + obj_template, otsize); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + goto loser; + } + while (PR_TRUE) { + /* Issue the find for up to arraySize - numHandles objects */ + ckrv = CKAPI(epv)->C_FindObjects(session->handle, + objectHandles + numHandles, + arraySize - numHandles, + &count); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + goto loser; + } + /* bump the number of found objects */ + numHandles += count; + if (maximumOpt > 0 || numHandles < arraySize) { + /* When a maximum is provided, the search is done all at once, + * so the search is finished. If the number returned was less + * than the number sought, the search is finished. + */ + break; + } + /* the array is filled, double it and continue */ + arraySize *= 2; + objectHandles = nss_ZREALLOCARRAY(objectHandles, + CK_OBJECT_HANDLE, + arraySize); + if (!objectHandles) { + nssSession_ExitMonitor(session); + goto loser; + } + } + ckrv = CKAPI(epv)->C_FindObjectsFinal(session->handle); + nssSession_ExitMonitor(session); /* ==== end session lock === */ + if (ckrv != CKR_OK) { + goto loser; + } + if (numHandles > 0) { + objects = create_objects_from_handles(tok, session, + objectHandles, numHandles); + } else { + objects = NULL; + } + nssArena_Destroy(arena); + if (statusOpt) *statusOpt = PR_SUCCESS; + return objects; +loser: + nssArena_Destroy(arena); + if (statusOpt) *statusOpt = PR_FAILURE; + return (nssCryptokiObject **)NULL; +} + +static nssCryptokiObject ** +find_objects_by_template +( + NSSToken *token, + nssSession *sessionOpt, + CK_ATTRIBUTE_PTR obj_template, + CK_ULONG otsize, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_OBJECT_CLASS objclass; + nssCryptokiObject **objects = NULL; + PRUint32 i; + for (i=0; i<otsize; i++) { + if (obj_template[i].type == CKA_CLASS) { + objclass = *(CK_OBJECT_CLASS *)obj_template[i].pValue; + break; + } + } + PR_ASSERT(i < otsize); + /* If these objects are being cached, try looking there first */ + if (token->cache && + nssTokenObjectCache_HaveObjectClass(token->cache, objclass)) + { + PRStatus status; + objects = nssTokenObjectCache_FindObjectsByTemplate(token->cache, + objclass, + obj_template, + otsize, + maximumOpt, + &status); + if (status == PR_SUCCESS) { + if (statusOpt) *statusOpt = status; + return objects; + } + } + /* Either they are not cached, or cache failed; look on token. */ + objects = find_objects(token, sessionOpt, + obj_template, otsize, + maximumOpt, statusOpt); + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_ImportCertificate +( + NSSToken *tok, + nssSession *sessionOpt, + NSSCertificateType certType, + NSSItem *id, + NSSUTF8 *nickname, + NSSDER *encoding, + NSSDER *issuer, + NSSDER *subject, + NSSDER *serial, + NSSASCII7 *email, + PRBool asTokenObject +) +{ + CK_CERTIFICATE_TYPE cert_type; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE cert_tmpl[10]; + CK_ULONG ctsize; + nssTokenSearchType searchType; + nssCryptokiObject *rvObject = NULL; + + if (certType == NSSCertificateType_PKIX) { + cert_type = CKC_X_509; + } else { + return (nssCryptokiObject *)NULL; + } + NSS_CK_TEMPLATE_START(cert_tmpl, attr, ctsize); + if (asTokenObject) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + searchType = nssTokenSearchType_TokenOnly; + } else { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + searchType = nssTokenSearchType_SessionOnly; + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CERTIFICATE_TYPE, cert_type); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, id); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_LABEL, nickname); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_VALUE, encoding); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ISSUER, issuer); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SUBJECT, subject); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SERIAL_NUMBER, serial); + if (email) { + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_NETSCAPE_EMAIL, email); + } + NSS_CK_TEMPLATE_FINISH(cert_tmpl, attr, ctsize); + /* see if the cert is already there */ + rvObject = nssToken_FindCertificateByIssuerAndSerialNumber(tok, + sessionOpt, + issuer, + serial, + searchType, + NULL); + if (rvObject) { + NSSSlot *slot = nssToken_GetSlot(tok); + nssSession *session = nssSlot_CreateSession(slot, NULL, PR_TRUE); + if (!session) { + nssCryptokiObject_Destroy(rvObject); + return (nssCryptokiObject *)NULL; + } + /* according to PKCS#11, label, ID, issuer, and serial number + * may change after the object has been created. For PKIX, the + * last two attributes can't change, so for now we'll only worry + * about the first two. + */ + NSS_CK_TEMPLATE_START(cert_tmpl, attr, ctsize); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, id); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_LABEL, nickname); + NSS_CK_TEMPLATE_FINISH(cert_tmpl, attr, ctsize); + /* reset the mutable attributes on the token */ + nssCKObject_SetAttributes(rvObject->handle, + cert_tmpl, ctsize, + session, slot); + if (!rvObject->label && nickname) { + rvObject->label = nssUTF8_Duplicate(nickname, NULL); + } + nssSession_Destroy(session); + nssSlot_Destroy(slot); + } else { + /* Import the certificate onto the token */ + rvObject = import_object(tok, sessionOpt, cert_tmpl, ctsize); + } + if (rvObject && tok->cache) { + /* The cache will overwrite the attributes if the object already + * exists. + */ + nssTokenObjectCache_ImportObject(tok->cache, rvObject, + CKO_CERTIFICATE, + cert_tmpl, ctsize); + } + return rvObject; +} + +/* traverse all certificates - this should only happen if the token + * has been marked as "traversable" + */ +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCertificates +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE cert_template[2]; + CK_ULONG ctsize; + nssCryptokiObject **objects; + NSS_CK_TEMPLATE_START(cert_template, attr, ctsize); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly || + searchType == nssTokenSearchType_TokenForced) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_TEMPLATE_FINISH(cert_template, attr, ctsize); + + if (searchType == nssTokenSearchType_TokenForced) { + objects = find_objects(token, sessionOpt, + cert_template, ctsize, + maximumOpt, statusOpt); + } else { + objects = find_objects_by_template(token, sessionOpt, + cert_template, ctsize, + maximumOpt, statusOpt); + } + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCertificatesBySubject +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE subj_template[3]; + CK_ULONG stsize; + nssCryptokiObject **objects; + NSS_CK_TEMPLATE_START(subj_template, attr, stsize); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SUBJECT, subject); + NSS_CK_TEMPLATE_FINISH(subj_template, attr, stsize); + /* now locate the token certs matching this template */ + objects = find_objects_by_template(token, sessionOpt, + subj_template, stsize, + maximumOpt, statusOpt); + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCertificatesByNickname +( + NSSToken *token, + nssSession *sessionOpt, + NSSUTF8 *name, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE nick_template[3]; + CK_ULONG ntsize; + nssCryptokiObject **objects; + NSS_CK_TEMPLATE_START(nick_template, attr, ntsize); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_LABEL, name); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_TEMPLATE_FINISH(nick_template, attr, ntsize); + /* now locate the token certs matching this template */ + objects = find_objects_by_template(token, sessionOpt, + nick_template, ntsize, + maximumOpt, statusOpt); + if (!objects) { + /* This is to workaround the fact that PKCS#11 doesn't specify + * whether the '\0' should be included. XXX Is that still true? + * im - this is not needed by the current softoken. However, I'm + * leaving it in until I have surveyed more tokens to see if it needed. + * well, its needed by the builtin token... + */ + nick_template[0].ulValueLen++; + objects = find_objects_by_template(token, sessionOpt, + nick_template, ntsize, + maximumOpt, statusOpt); + } + return objects; +} + +/* XXX + * This function *does not* use the token object cache, because not even + * the softoken will return a value for CKA_NETSCAPE_EMAIL from a call + * to GetAttributes. The softoken does allow searches with that attribute, + * it just won't return a value for it. + */ +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCertificatesByEmail +( + NSSToken *token, + nssSession *sessionOpt, + NSSASCII7 *email, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE email_template[3]; + CK_ULONG etsize; + nssCryptokiObject **objects; + NSS_CK_TEMPLATE_START(email_template, attr, etsize); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_NETSCAPE_EMAIL, email); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_TEMPLATE_FINISH(email_template, attr, etsize); + /* now locate the token certs matching this template */ + objects = find_objects(token, sessionOpt, + email_template, etsize, + maximumOpt, statusOpt); + if (!objects) { + /* This is to workaround the fact that PKCS#11 doesn't specify + * whether the '\0' should be included. XXX Is that still true? + * im - this is not needed by the current softoken. However, I'm + * leaving it in until I have surveyed more tokens to see if it needed. + * well, its needed by the builtin token... + */ + email_template[0].ulValueLen++; + objects = find_objects(token, sessionOpt, + email_template, etsize, + maximumOpt, statusOpt); + } + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCertificatesByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *id, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE id_template[3]; + CK_ULONG idtsize; + nssCryptokiObject **objects; + NSS_CK_TEMPLATE_START(id_template, attr, idtsize); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, id); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_TEMPLATE_FINISH(id_template, attr, idtsize); + /* now locate the token certs matching this template */ + objects = find_objects_by_template(token, sessionOpt, + id_template, idtsize, + maximumOpt, statusOpt); + return objects; +} + +/* + * decode the serial item and return our result. + * NOTE serialDecode's data is really stored in serial. Don't free it. + */ +static PRStatus +nssToken_decodeSerialItem(NSSItem *serial, NSSItem *serialDecode) +{ + unsigned char *data = (unsigned char *)serial->data; + int data_left, data_len, index; + + if ((serial->size >= 3) && (data[0] == 0x2)) { + /* remove the der encoding of the serial number before generating the + * key.. */ + data_left = serial->size-2; + data_len = 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) | 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) { + serialDecode->size = data_len; + serialDecode->data = &data[index]; + return PR_SUCCESS; + } + } + return PR_FAILURE; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_FindCertificateByIssuerAndSerialNumber +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *issuer, + NSSDER *serial, + nssTokenSearchType searchType, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE_PTR serialAttr; + CK_ATTRIBUTE cert_template[4]; + CK_ULONG ctsize; + nssCryptokiObject **objects; + nssCryptokiObject *rvObject = NULL; + NSS_CK_TEMPLATE_START(cert_template, attr, ctsize); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + /* Set the unique id */ + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ISSUER, issuer); + serialAttr = attr; + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SERIAL_NUMBER, serial); + NSS_CK_TEMPLATE_FINISH(cert_template, attr, ctsize); + /* get the object handle */ + objects = find_objects_by_template(token, sessionOpt, + cert_template, ctsize, + 1, statusOpt); + if (objects) { + rvObject = objects[0]; + nss_ZFreeIf(objects); + } + + /* + * NSS used to incorrectly store serial numbers in their decoded form. + * because of this old tokens have decoded serial numbers. + */ + if (!objects) { + NSSItem serialDecode; + PRStatus status; + + status = nssToken_decodeSerialItem(serial, &serialDecode); + if (status != PR_SUCCESS) { + return NULL; + } + NSS_CK_SET_ATTRIBUTE_ITEM(serialAttr,CKA_SERIAL_NUMBER,&serialDecode); + objects = find_objects_by_template(token, sessionOpt, + cert_template, ctsize, + 1, statusOpt); + if (objects) { + rvObject = objects[0]; + nss_ZFreeIf(objects); + } + } + return rvObject; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_FindCertificateByEncodedCertificate +( + NSSToken *token, + nssSession *sessionOpt, + NSSBER *encodedCertificate, + nssTokenSearchType searchType, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE cert_template[3]; + CK_ULONG ctsize; + nssCryptokiObject **objects; + nssCryptokiObject *rvObject = NULL; + NSS_CK_TEMPLATE_START(cert_template, attr, ctsize); + /* Set the search to token/session only if provided */ + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_VALUE, encodedCertificate); + NSS_CK_TEMPLATE_FINISH(cert_template, attr, ctsize); + /* get the object handle */ + objects = find_objects_by_template(token, sessionOpt, + cert_template, ctsize, + 1, statusOpt); + if (objects) { + rvObject = objects[0]; + nss_ZFreeIf(objects); + } + return rvObject; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindPrivateKeys +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[2]; + CK_ULONG ktsize; + nssCryptokiObject **objects; + + NSS_CK_TEMPLATE_START(key_template, attr, ktsize); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_privkey); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_TEMPLATE_FINISH(key_template, attr, ktsize); + + objects = find_objects_by_template(token, sessionOpt, + key_template, ktsize, + maximumOpt, statusOpt); + return objects; +} + +/* XXX ?there are no session cert objects, so only search token objects */ +NSS_IMPLEMENT nssCryptokiObject * +nssToken_FindPrivateKeyByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *keyID +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[3]; + CK_ULONG ktsize; + nssCryptokiObject **objects; + nssCryptokiObject *rvKey = NULL; + + NSS_CK_TEMPLATE_START(key_template, attr, ktsize); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_privkey); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, keyID); + NSS_CK_TEMPLATE_FINISH(key_template, attr, ktsize); + + objects = find_objects_by_template(token, sessionOpt, + key_template, ktsize, + 1, NULL); + if (objects) { + rvKey = objects[0]; + nss_ZFreeIf(objects); + } + return rvKey; +} + +/* XXX ?there are no session cert objects, so only search token objects */ +NSS_IMPLEMENT nssCryptokiObject * +nssToken_FindPublicKeyByID +( + NSSToken *token, + nssSession *sessionOpt, + NSSItem *keyID +) +{ + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE key_template[3]; + CK_ULONG ktsize; + nssCryptokiObject **objects; + nssCryptokiObject *rvKey = NULL; + + NSS_CK_TEMPLATE_START(key_template, attr, ktsize); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_pubkey); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ID, keyID); + NSS_CK_TEMPLATE_FINISH(key_template, attr, ktsize); + + objects = find_objects_by_template(token, sessionOpt, + key_template, ktsize, + 1, NULL); + if (objects) { + rvKey = objects[0]; + nss_ZFreeIf(objects); + } + return rvKey; +} + +static void +sha1_hash(NSSItem *input, NSSItem *output) +{ + NSSAlgorithmAndParameters *ap; +#ifdef NSS_3_4_CODE + PK11SlotInfo *internal = PK11_GetInternalSlot(); + NSSToken *token = PK11Slot_GetNSSToken(internal); +#else + NSSToken *token = nss_GetDefaultCryptoToken(); +#endif + ap = NSSAlgorithmAndParameters_CreateSHA1Digest(NULL); + (void)nssToken_Digest(token, NULL, ap, input, output, NULL); +#ifdef NSS_3_4_CODE + PK11_FreeSlot(token->pk11slot); +#endif + nss_ZFreeIf(ap); +} + +static void +md5_hash(NSSItem *input, NSSItem *output) +{ + NSSAlgorithmAndParameters *ap; +#ifdef NSS_3_4_CODE + PK11SlotInfo *internal = PK11_GetInternalSlot(); + NSSToken *token = PK11Slot_GetNSSToken(internal); +#else + NSSToken *token = nss_GetDefaultCryptoToken(); +#endif + ap = NSSAlgorithmAndParameters_CreateMD5Digest(NULL); + (void)nssToken_Digest(token, NULL, ap, input, output, NULL); +#ifdef NSS_3_4_CODE + PK11_FreeSlot(token->pk11slot); +#endif + nss_ZFreeIf(ap); +} + +static CK_TRUST +get_ck_trust +( + nssTrustLevel nssTrust +) +{ + CK_TRUST t; + switch (nssTrust) { + case nssTrustLevel_Unknown: t = CKT_NETSCAPE_TRUST_UNKNOWN; break; + case nssTrustLevel_NotTrusted: t = CKT_NETSCAPE_UNTRUSTED; break; + case nssTrustLevel_TrustedDelegator: t = CKT_NETSCAPE_TRUSTED_DELEGATOR; + break; + case nssTrustLevel_ValidDelegator: t = CKT_NETSCAPE_VALID_DELEGATOR; break; + case nssTrustLevel_Trusted: t = CKT_NETSCAPE_TRUSTED; break; + case nssTrustLevel_Valid: t = CKT_NETSCAPE_VALID; break; + } + return t; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_ImportTrust +( + NSSToken *tok, + nssSession *sessionOpt, + NSSDER *certEncoding, + NSSDER *certIssuer, + NSSDER *certSerial, + nssTrustLevel serverAuth, + nssTrustLevel clientAuth, + nssTrustLevel codeSigning, + nssTrustLevel emailProtection, + PRBool asTokenObject +) +{ + nssCryptokiObject *object; + CK_OBJECT_CLASS tobjc = CKO_NETSCAPE_TRUST; + CK_TRUST ckSA, ckCA, ckCS, ckEP; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE trust_tmpl[10]; + CK_ULONG tsize; + PRUint8 sha1[20]; /* this is cheating... */ + PRUint8 md5[16]; + NSSItem sha1_result, md5_result; + sha1_result.data = sha1; sha1_result.size = sizeof sha1; + md5_result.data = md5; md5_result.size = sizeof md5; + sha1_hash(certEncoding, &sha1_result); + md5_hash(certEncoding, &md5_result); + ckSA = get_ck_trust(serverAuth); + ckCA = get_ck_trust(clientAuth); + ckCS = get_ck_trust(codeSigning); + ckEP = get_ck_trust(emailProtection); + NSS_CK_TEMPLATE_START(trust_tmpl, attr, tsize); + if (asTokenObject) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } else { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, tobjc); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ISSUER, certIssuer); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SERIAL_NUMBER, certSerial); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CERT_SHA1_HASH, &sha1_result); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CERT_MD5_HASH, &md5_result); + /* now set the trust values */ + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_SERVER_AUTH, ckSA); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CLIENT_AUTH, ckCA); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CODE_SIGNING, ckCS); + NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_EMAIL_PROTECTION, ckEP); + NSS_CK_TEMPLATE_FINISH(trust_tmpl, attr, tsize); + /* import the trust object onto the token */ + object = import_object(tok, sessionOpt, trust_tmpl, tsize); + if (object && tok->cache) { + nssTokenObjectCache_ImportObject(tok->cache, object, tobjc, + trust_tmpl, tsize); + } + return object; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindTrustObjects +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_OBJECT_CLASS tobjc = CKO_NETSCAPE_TRUST; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE tobj_template[2]; + CK_ULONG tobj_size; + nssCryptokiObject **objects; + nssSession *session = sessionOpt ? sessionOpt : token->defaultSession; + + NSS_CK_TEMPLATE_START(tobj_template, attr, tobj_size); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly || + searchType == nssTokenSearchType_TokenForced) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, tobjc); + NSS_CK_TEMPLATE_FINISH(tobj_template, attr, tobj_size); + + if (searchType == nssTokenSearchType_TokenForced) { + objects = find_objects(token, session, + tobj_template, tobj_size, + maximumOpt, statusOpt); + } else { + objects = find_objects_by_template(token, session, + tobj_template, tobj_size, + maximumOpt, statusOpt); + } + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_FindTrustForCertificate +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *certEncoding, + NSSDER *certIssuer, + NSSDER *certSerial, + nssTokenSearchType searchType +) +{ + CK_OBJECT_CLASS tobjc = CKO_NETSCAPE_TRUST; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE tobj_template[5]; + CK_ULONG tobj_size; + PRUint8 sha1[20]; /* this is cheating... */ + NSSItem sha1_result; + nssSession *session = sessionOpt ? sessionOpt : token->defaultSession; + nssCryptokiObject *object, **objects; + + sha1_result.data = sha1; sha1_result.size = sizeof sha1; + sha1_hash(certEncoding, &sha1_result); + NSS_CK_TEMPLATE_START(tobj_template, attr, tobj_size); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, tobjc); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CERT_SHA1_HASH, &sha1_result); +#ifdef NSS_3_4_CODE + if (!PK11_HasRootCerts(token->pk11slot)) { +#endif + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ISSUER, certIssuer); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SERIAL_NUMBER , certSerial); +#ifdef NSS_3_4_CODE + } + /* + * we need to arrange for the built-in token to lose the bottom 2 + * attributes so that old built-in tokens will continue to work. + */ +#endif + NSS_CK_TEMPLATE_FINISH(tobj_template, attr, tobj_size); + object = NULL; + objects = find_objects_by_template(token, session, + tobj_template, tobj_size, + 1, NULL); + if (objects) { + object = objects[0]; + nss_ZFreeIf(objects); + } + return object; +} + +NSS_IMPLEMENT nssCryptokiObject * +nssToken_ImportCRL +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + NSSDER *encoding, + PRBool isKRL, + NSSUTF8 *url, + PRBool asTokenObject +) +{ + nssCryptokiObject *object; + CK_OBJECT_CLASS crlobjc = CKO_NETSCAPE_CRL; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE crl_tmpl[6]; + CK_ULONG crlsize; + + NSS_CK_TEMPLATE_START(crl_tmpl, attr, crlsize); + if (asTokenObject) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } else { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, crlobjc); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SUBJECT, subject); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_VALUE, encoding); + NSS_CK_SET_ATTRIBUTE_UTF8(attr, CKA_NETSCAPE_URL, url); + if (isKRL) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_NETSCAPE_KRL, &g_ck_true); + } else { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_NETSCAPE_KRL, &g_ck_false); + } + NSS_CK_TEMPLATE_FINISH(crl_tmpl, attr, crlsize); + + /* import the crl object onto the token */ + object = import_object(token, sessionOpt, crl_tmpl, crlsize); + if (object && token->cache) { + nssTokenObjectCache_ImportObject(token->cache, object, crlobjc, + crl_tmpl, crlsize); + } + return object; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCRLs +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_OBJECT_CLASS crlobjc = CKO_NETSCAPE_CRL; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE crlobj_template[2]; + CK_ULONG crlobj_size; + nssCryptokiObject **objects; + nssSession *session = sessionOpt ? sessionOpt : token->defaultSession; + + NSS_CK_TEMPLATE_START(crlobj_template, attr, crlobj_size); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly || + searchType == nssTokenSearchType_TokenForced) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, crlobjc); + NSS_CK_TEMPLATE_FINISH(crlobj_template, attr, crlobj_size); + + if (searchType == nssTokenSearchType_TokenForced) { + objects = find_objects(token, session, + crlobj_template, crlobj_size, + maximumOpt, statusOpt); + } else { + objects = find_objects_by_template(token, session, + crlobj_template, crlobj_size, + maximumOpt, statusOpt); + } + return objects; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssToken_FindCRLsBySubject +( + NSSToken *token, + nssSession *sessionOpt, + NSSDER *subject, + nssTokenSearchType searchType, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + CK_OBJECT_CLASS crlobjc = CKO_NETSCAPE_CRL; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE crlobj_template[3]; + CK_ULONG crlobj_size; + nssCryptokiObject **objects; + nssSession *session = sessionOpt ? sessionOpt : token->defaultSession; + + NSS_CK_TEMPLATE_START(crlobj_template, attr, crlobj_size); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly || + searchType == nssTokenSearchType_TokenForced) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, crlobjc); + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SUBJECT, subject); + NSS_CK_TEMPLATE_FINISH(crlobj_template, attr, crlobj_size); + + objects = find_objects_by_template(token, session, + crlobj_template, crlobj_size, + maximumOpt, statusOpt); + return objects; +} + +NSS_IMPLEMENT PRStatus +nssToken_GetCachedObjectAttributes +( + NSSToken *token, + NSSArena *arenaOpt, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR atemplate, + CK_ULONG atlen +) +{ + if (!token->cache) { + return PR_FAILURE; + } + return nssTokenObjectCache_GetObjectAttributes(token->cache, arenaOpt, + object, objclass, + atemplate, atlen); +} + +NSS_IMPLEMENT NSSItem * +nssToken_Digest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSAlgorithmAndParameters *ap, + NSSItem *data, + NSSItem *rvOpt, + NSSArena *arenaOpt +) +{ + CK_RV ckrv; + CK_ULONG digestLen; + CK_BYTE_PTR digest; + NSSItem *rvItem = NULL; + void *epv = nssToken_GetCryptokiEPV(tok); + nssSession *session; + session = (sessionOpt) ? sessionOpt : tok->defaultSession; + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_DigestInit(session->handle, &ap->mechanism); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + return NULL; + } +#if 0 + /* XXX the standard says this should work, but it doesn't */ + ckrv = CKAPI(epv)->C_Digest(session->handle, NULL, 0, NULL, &digestLen); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + return NULL; + } +#endif + digestLen = 0; /* XXX for now */ + digest = NULL; + if (rvOpt) { + if (rvOpt->size > 0 && rvOpt->size < digestLen) { + nssSession_ExitMonitor(session); + /* the error should be bad args */ + return NULL; + } + if (rvOpt->data) { + digest = rvOpt->data; + } + digestLen = rvOpt->size; + } + if (!digest) { + digest = (CK_BYTE_PTR)nss_ZAlloc(arenaOpt, digestLen); + if (!digest) { + nssSession_ExitMonitor(session); + return NULL; + } + } + ckrv = CKAPI(epv)->C_Digest(session->handle, + (CK_BYTE_PTR)data->data, + (CK_ULONG)data->size, + (CK_BYTE_PTR)digest, + &digestLen); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK) { + nss_ZFreeIf(digest); + return NULL; + } + if (!rvOpt) { + rvItem = nssItem_Create(arenaOpt, NULL, digestLen, (void *)digest); + } + return rvItem; +} + +NSS_IMPLEMENT PRStatus +nssToken_BeginDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSAlgorithmAndParameters *ap +) +{ + CK_RV ckrv; + nssSession *session; + void *epv = nssToken_GetCryptokiEPV(tok); + session = (sessionOpt) ? sessionOpt : tok->defaultSession; + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_DigestInit(session->handle, &ap->mechanism); + nssSession_ExitMonitor(session); + return (ckrv == CKR_OK) ? PR_SUCCESS : PR_FAILURE; +} + +NSS_IMPLEMENT PRStatus +nssToken_ContinueDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSItem *item +) +{ + CK_RV ckrv; + nssSession *session; + void *epv = nssToken_GetCryptokiEPV(tok); + session = (sessionOpt) ? sessionOpt : tok->defaultSession; + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_DigestUpdate(session->handle, + (CK_BYTE_PTR)item->data, + (CK_ULONG)item->size); + nssSession_ExitMonitor(session); + return (ckrv == CKR_OK) ? PR_SUCCESS : PR_FAILURE; +} + +NSS_IMPLEMENT NSSItem * +nssToken_FinishDigest +( + NSSToken *tok, + nssSession *sessionOpt, + NSSItem *rvOpt, + NSSArena *arenaOpt +) +{ + CK_RV ckrv; + CK_ULONG digestLen; + CK_BYTE_PTR digest; + NSSItem *rvItem = NULL; + void *epv = nssToken_GetCryptokiEPV(tok); + nssSession *session; + session = (sessionOpt) ? sessionOpt : tok->defaultSession; + nssSession_EnterMonitor(session); + ckrv = CKAPI(epv)->C_DigestFinal(session->handle, NULL, &digestLen); + if (ckrv != CKR_OK || digestLen == 0) { + nssSession_ExitMonitor(session); + return NULL; + } + digest = NULL; + if (rvOpt) { + if (rvOpt->size > 0 && rvOpt->size < digestLen) { + nssSession_ExitMonitor(session); + /* the error should be bad args */ + return NULL; + } + if (rvOpt->data) { + digest = rvOpt->data; + } + digestLen = rvOpt->size; + } + if (!digest) { + digest = (CK_BYTE_PTR)nss_ZAlloc(arenaOpt, digestLen); + if (!digest) { + nssSession_ExitMonitor(session); + return NULL; + } + } + ckrv = CKAPI(epv)->C_DigestFinal(session->handle, digest, &digestLen); + nssSession_ExitMonitor(session); + if (ckrv != CKR_OK) { + nss_ZFreeIf(digest); + return NULL; + } + if (!rvOpt) { + rvItem = nssItem_Create(arenaOpt, NULL, digestLen, (void *)digest); + } + return rvItem; +} + +NSS_IMPLEMENT PRBool +nssToken_IsPresent +( + NSSToken *token +) +{ + return nssSlot_IsTokenPresent(token->slot); +} + +/* Sigh. The methods to find objects declared above cause problems with + * the low-level object cache in the softoken -- the objects are found in + * toto, then one wave of GetAttributes is done, then another. Having a + * large number of objects causes the cache to be thrashed, as the objects + * are gone before there's any chance to ask for their attributes. + * So, for now, bringing back traversal methods for certs. This way all of + * the cert's attributes can be grabbed immediately after finding it, + * increasing the likelihood that the cache takes care of it. + */ +NSS_IMPLEMENT PRStatus +nssToken_TraverseCertificates +( + NSSToken *token, + nssSession *sessionOpt, + nssTokenSearchType searchType, + PRStatus (* callback)(nssCryptokiObject *instance, void *arg), + void *arg +) +{ + CK_RV ckrv; + CK_ULONG count; + CK_OBJECT_HANDLE *objectHandles; + CK_ATTRIBUTE_PTR attr; + CK_ATTRIBUTE cert_template[2]; + CK_ULONG ctsize; + NSSArena *arena; + PRStatus status; + PRUint32 arraySize, numHandles; + nssCryptokiObject **objects; + void *epv = nssToken_GetCryptokiEPV(token); + nssSession *session = (sessionOpt) ? sessionOpt : token->defaultSession; + + /* template for all certs */ + NSS_CK_TEMPLATE_START(cert_template, attr, ctsize); + if (searchType == nssTokenSearchType_SessionOnly) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); + } else if (searchType == nssTokenSearchType_TokenOnly || + searchType == nssTokenSearchType_TokenForced) { + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); + } + NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert); + NSS_CK_TEMPLATE_FINISH(cert_template, attr, ctsize); + + /* the arena is only for the array of object handles */ + arena = nssArena_Create(); + if (!arena) { + return PR_FAILURE; + } + arraySize = OBJECT_STACK_SIZE; + numHandles = 0; + objectHandles = nss_ZNEWARRAY(arena, CK_OBJECT_HANDLE, arraySize); + if (!objectHandles) { + goto loser; + } + nssSession_EnterMonitor(session); /* ==== session lock === */ + /* Initialize the find with the template */ + ckrv = CKAPI(epv)->C_FindObjectsInit(session->handle, + cert_template, ctsize); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + goto loser; + } + while (PR_TRUE) { + /* Issue the find for up to arraySize - numHandles objects */ + ckrv = CKAPI(epv)->C_FindObjects(session->handle, + objectHandles + numHandles, + arraySize - numHandles, + &count); + if (ckrv != CKR_OK) { + nssSession_ExitMonitor(session); + goto loser; + } + /* bump the number of found objects */ + numHandles += count; + if (numHandles < arraySize) { + break; + } + /* the array is filled, double it and continue */ + arraySize *= 2; + objectHandles = nss_ZREALLOCARRAY(objectHandles, + CK_OBJECT_HANDLE, + arraySize); + if (!objectHandles) { + nssSession_ExitMonitor(session); + goto loser; + } + } + ckrv = CKAPI(epv)->C_FindObjectsFinal(session->handle); + nssSession_ExitMonitor(session); /* ==== end session lock === */ + if (ckrv != CKR_OK) { + goto loser; + } + if (numHandles > 0) { + objects = create_objects_from_handles(token, session, + objectHandles, numHandles); + if (objects) { + nssCryptokiObject **op; + for (op = objects; *op; op++) { + status = (*callback)(*op, arg); + } + nss_ZFreeIf(objects); + } + } + nssArena_Destroy(arena); + return PR_SUCCESS; +loser: + nssArena_Destroy(arena); + return PR_FAILURE; +} + diff --git a/security/nss/lib/dev/devutil.c b/security/nss/lib/dev/devutil.c new file mode 100644 index 000000000..99218f83d --- /dev/null +++ b/security/nss/lib/dev/devutil.c @@ -0,0 +1,1445 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifdef DEBUG +static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +#ifndef DEVM_H +#include "devm.h" +#endif /* DEVM_H */ + +#ifndef CKHELPER_H +#include "ckhelper.h" +#endif /* CKHELPER_H */ + +NSS_IMPLEMENT nssCryptokiObject * +nssCryptokiObject_Create +( + NSSToken *t, + nssSession *session, + CK_OBJECT_HANDLE h +) +{ + PRStatus status; + NSSSlot *slot; + nssCryptokiObject *object; + CK_BBOOL *isTokenObject; + CK_ATTRIBUTE cert_template[] = { + { CKA_TOKEN, NULL, 0 }, + { CKA_LABEL, NULL, 0 } + }; + slot = nssToken_GetSlot(t); + status = nssCKObject_GetAttributes(h, cert_template, 2, + NULL, session, slot); + nssSlot_Destroy(slot); + if (status != PR_SUCCESS) { + /* a failure here indicates a device error */ + return (nssCryptokiObject *)NULL; + } + object = nss_ZNEW(NULL, nssCryptokiObject); + if (!object) { + return (nssCryptokiObject *)NULL; + } + object->handle = h; + object->token = nssToken_AddRef(t); + isTokenObject = (CK_BBOOL *)cert_template[0].pValue; + object->isTokenObject = *isTokenObject; + nss_ZFreeIf(isTokenObject); + NSS_CK_ATTRIBUTE_TO_UTF8(&cert_template[1], object->label); + return object; +} + +NSS_IMPLEMENT void +nssCryptokiObject_Destroy +( + nssCryptokiObject *object +) +{ + if (object) { + nssToken_Destroy(object->token); + nss_ZFreeIf(object->label); + nss_ZFreeIf(object); + } +} + +NSS_IMPLEMENT nssCryptokiObject * +nssCryptokiObject_Clone +( + nssCryptokiObject *object +) +{ + nssCryptokiObject *rvObject; + rvObject = nss_ZNEW(NULL, nssCryptokiObject); + if (rvObject) { + rvObject->handle = object->handle; + rvObject->token = nssToken_AddRef(object->token); + rvObject->isTokenObject = object->isTokenObject; + if (object->label) { + rvObject->label = nssUTF8_Duplicate(object->label, NULL); + } + } + return rvObject; +} + +NSS_EXTERN PRBool +nssCryptokiObject_Equal +( + nssCryptokiObject *o1, + nssCryptokiObject *o2 +) +{ + return (o1->token == o2->token && o1->handle == o2->handle); +} + +NSS_IMPLEMENT PRUint32 +nssPKCS11String_Length(CK_CHAR *pkcs11Str, PRUint32 bufLen) +{ + PRInt32 i; + for (i = bufLen - 1; i>=0; ) { + if (pkcs11Str[i] != ' ' && pkcs11Str[i] != '\0') break; + --i; + } + return (PRUint32)(i + 1); +} + +/* + * Slot arrays + */ + +NSS_IMPLEMENT NSSSlot ** +nssSlotArray_Clone +( + NSSSlot **slots +) +{ + NSSSlot **rvSlots = NULL; + NSSSlot **sp = slots; + PRUint32 count = 0; + while (sp && *sp) count++; + if (count > 0) { + rvSlots = nss_ZNEWARRAY(NULL, NSSSlot *, count + 1); + if (rvSlots) { + sp = slots; + count = 0; + for (sp = slots; *sp; sp++) { + rvSlots[count++] = nssSlot_AddRef(*sp); + } + } + } + return rvSlots; +} + +#ifdef PURE_STAN_BUILD +NSS_IMPLEMENT void +nssModuleArray_Destroy +( + NSSModule **modules +) +{ + if (modules) { + NSSModule **mp; + for (mp = modules; *mp; mp++) { + nssModule_Destroy(*mp); + } + nss_ZFreeIf(modules); + } +} +#endif + +NSS_IMPLEMENT void +nssSlotArray_Destroy +( + NSSSlot **slots +) +{ + if (slots) { + NSSSlot **slotp; + for (slotp = slots; *slotp; slotp++) { + nssSlot_Destroy(*slotp); + } + nss_ZFreeIf(slots); + } +} + +NSS_IMPLEMENT void +NSSSlotArray_Destroy +( + NSSSlot **slots +) +{ + nssSlotArray_Destroy(slots); +} + +NSS_IMPLEMENT void +nssTokenArray_Destroy +( + NSSToken **tokens +) +{ + if (tokens) { + NSSToken **tokenp; + for (tokenp = tokens; *tokenp; tokenp++) { + nssToken_Destroy(*tokenp); + } + nss_ZFreeIf(tokens); + } +} + +NSS_IMPLEMENT void +NSSTokenArray_Destroy +( + NSSToken **tokens +) +{ + nssTokenArray_Destroy(tokens); +} + +NSS_IMPLEMENT void +nssCryptokiObjectArray_Destroy +( + nssCryptokiObject **objects +) +{ + if (objects) { + nssCryptokiObject **op; + for (op = objects; *op; op++) { + nssCryptokiObject_Destroy(*op); + } + nss_ZFreeIf(objects); + } +} + +#ifdef PURE_STAN_BUILD +/* + * Slot lists + */ + +struct nssSlotListNodeStr +{ + PRCList link; + NSSSlot *slot; + PRUint32 order; +}; + +/* XXX separate slots with non-present tokens? */ +struct nssSlotListStr +{ + NSSArena *arena; + PRBool i_allocated_arena; + PZLock *lock; + PRCList head; + PRUint32 count; +}; + +NSS_IMPLEMENT nssSlotList * +nssSlotList_Create +( + NSSArena *arenaOpt +) +{ + nssSlotList *rvList; + NSSArena *arena; + nssArenaMark *mark; + if (arenaOpt) { + arena = arenaOpt; + mark = nssArena_Mark(arena); + if (!mark) { + return (nssSlotList *)NULL; + } + } else { + arena = nssArena_Create(); + if (!arena) { + return (nssSlotList *)NULL; + } + } + rvList = nss_ZNEW(arena, nssSlotList); + if (!rvList) { + goto loser; + } + rvList->lock = PZ_NewLock(nssILockOther); /* XXX */ + if (!rvList->lock) { + goto loser; + } + PR_INIT_CLIST(&rvList->head); + rvList->arena = arena; + rvList->i_allocated_arena = (arenaOpt == NULL); + nssArena_Unmark(arena, mark); + return rvList; +loser: + if (arenaOpt) { + nssArena_Release(arena, mark); + } else { + nssArena_Destroy(arena); + } + return (nssSlotList *)NULL; +} + +NSS_IMPLEMENT void +nssSlotList_Destroy +( + nssSlotList *slotList +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + if (slotList) { + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + node = (struct nssSlotListNodeStr *)link; + nssSlot_Destroy(node->slot); + link = PR_NEXT_LINK(link); + } + if (slotList->i_allocated_arena) { + nssArena_Destroy(slotList->arena); + } + } +} + +/* XXX should do allocs outside of lock */ +NSS_IMPLEMENT PRStatus +nssSlotList_Add +( + nssSlotList *slotList, + NSSSlot *slot, + PRUint32 order +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + PZ_Lock(slotList->lock); + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + node = (struct nssSlotListNodeStr *)link; + if (order < node->order) { + break; + } + link = PR_NEXT_LINK(link); + } + node = nss_ZNEW(slotList->arena, struct nssSlotListNodeStr); + if (!node) { + return PR_FAILURE; + } + PR_INIT_CLIST(&node->link); + node->slot = nssSlot_AddRef(slot); + node->order = order; + PR_INSERT_AFTER(&node->link, link); + slotList->count++; + PZ_Unlock(slotList->lock); + return PR_SUCCESS; +} + +NSS_IMPLEMENT PRStatus +nssSlotList_AddModuleSlots +( + nssSlotList *slotList, + NSSModule *module, + PRUint32 order +) +{ + nssArenaMark *mark = NULL; + NSSSlot **sp, **slots = NULL; + PRCList *link; + struct nssSlotListNodeStr *node; + PZ_Lock(slotList->lock); + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + node = (struct nssSlotListNodeStr *)link; + if (order < node->order) { + break; + } + link = PR_NEXT_LINK(link); + } + slots = nssModule_GetSlots(module); + if (!slots) { + PZ_Unlock(slotList->lock); + return PR_SUCCESS; + } + mark = nssArena_Mark(slotList->arena); + if (!mark) { + goto loser; + } + for (sp = slots; *sp; sp++) { + node = nss_ZNEW(slotList->arena, struct nssSlotListNodeStr); + if (!node) { + goto loser; + } + PR_INIT_CLIST(&node->link); + node->slot = *sp; /* have ref from nssModule_GetSlots */ + node->order = order; + PR_INSERT_AFTER(&node->link, link); + slotList->count++; + } + PZ_Unlock(slotList->lock); + nssArena_Unmark(slotList->arena, mark); + return PR_SUCCESS; +loser: + PZ_Unlock(slotList->lock); + if (mark) { + nssArena_Release(slotList->arena, mark); + } + if (slots) { + nssSlotArray_Destroy(slots); + } + return PR_FAILURE; +} + +NSS_IMPLEMENT NSSSlot ** +nssSlotList_GetSlots +( + nssSlotList *slotList +) +{ + PRUint32 i; + PRCList *link; + struct nssSlotListNodeStr *node; + NSSSlot **rvSlots = NULL; + PZ_Lock(slotList->lock); + rvSlots = nss_ZNEWARRAY(NULL, NSSSlot *, slotList->count + 1); + if (!rvSlots) { + PZ_Unlock(slotList->lock); + return (NSSSlot **)NULL; + } + i = 0; + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + node = (struct nssSlotListNodeStr *)link; + rvSlots[i] = nssSlot_AddRef(node->slot); + link = PR_NEXT_LINK(link); + i++; + } + PZ_Unlock(slotList->lock); + return rvSlots; +} + +#if 0 +NSS_IMPLEMENT NSSSlot * +nssSlotList_GetBestSlotForAlgorithmAndParameters +( + nssSlotList *slotList, + NSSAlgorithmAndParameters *ap +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + NSSSlot *rvSlot = NULL; + PZ_Lock(slotList->lock); + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + node = (struct nssSlotListNodeStr *)link; + if (nssSlot_DoesAlgorithmAndParameters(ap)) { + rvSlot = nssSlot_AddRef(node->slot); /* XXX check isPresent? */ + } + link = PR_NEXT_LINK(link); + } + PZ_Unlock(slotList->lock); + return rvSlot; +} +#endif + +NSS_IMPLEMENT NSSSlot * +nssSlotList_GetBestSlot +( + nssSlotList *slotList +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + NSSSlot *rvSlot = NULL; + PZ_Lock(slotList->lock); + if (PR_CLIST_IS_EMPTY(&slotList->head)) { + PZ_Unlock(slotList->lock); + return (NSSSlot *)NULL; + } + link = PR_NEXT_LINK(&slotList->head); + node = (struct nssSlotListNodeStr *)link; + rvSlot = nssSlot_AddRef(node->slot); /* XXX check isPresent? */ + PZ_Unlock(slotList->lock); + return rvSlot; +} + +NSS_IMPLEMENT NSSSlot * +nssSlotList_FindSlotByName +( + nssSlotList *slotList, + NSSUTF8 *slotName +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + NSSSlot *rvSlot = NULL; + PZ_Lock(slotList->lock); + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + NSSUTF8 *sName; + node = (struct nssSlotListNodeStr *)link; + sName = nssSlot_GetName(node->slot); + if (nssUTF8_Equal(sName, slotName, NULL)) { + rvSlot = nssSlot_AddRef(node->slot); + break; + } + link = PR_NEXT_LINK(link); + } + PZ_Unlock(slotList->lock); + return rvSlot; +} + +NSS_IMPLEMENT NSSToken * +nssSlotList_FindTokenByName +( + nssSlotList *slotList, + NSSUTF8 *tokenName +) +{ + PRCList *link; + struct nssSlotListNodeStr *node; + NSSToken *rvToken = NULL; + PZ_Lock(slotList->lock); + link = PR_NEXT_LINK(&slotList->head); + while (link != &slotList->head) { + NSSUTF8 *tName; + node = (struct nssSlotListNodeStr *)link; + tName = nssSlot_GetTokenName(node->slot); + if (nssUTF8_Equal(tName, tokenName, NULL)) { + rvToken = nssSlot_GetToken(node->slot); + break; + } + link = PR_NEXT_LINK(link); + } + PZ_Unlock(slotList->lock); + return rvToken; +} +#endif /* PURE_STAN_BUILD */ + +/* object cache for token */ + +typedef struct +{ + NSSArena *arena; + nssCryptokiObject *object; + CK_ATTRIBUTE_PTR attributes; + CK_ULONG numAttributes; +} +nssCryptokiObjectAndAttributes; + +enum { + cachedCerts = 0, + cachedTrust = 1, + cachedCRLs = 2 +} cachedObjectType; + +struct nssTokenObjectCacheStr +{ + NSSToken *token; + PZLock *lock; + PRBool loggedIn; + PRBool doObjectType[3]; + PRBool searchedObjectType[3]; + nssCryptokiObjectAndAttributes **objects[3]; +}; + +NSS_IMPLEMENT nssTokenObjectCache * +nssTokenObjectCache_Create +( + NSSToken *token, + PRBool cacheCerts, + PRBool cacheTrust, + PRBool cacheCRLs +) +{ + nssTokenObjectCache *rvCache; + rvCache = nss_ZNEW(NULL, nssTokenObjectCache); + if (!rvCache) { + goto loser; + } + rvCache->lock = PZ_NewLock(nssILockOther); /* XXX */ + if (!rvCache->lock) { + goto loser; + } + rvCache->doObjectType[cachedCerts] = cacheCerts; + rvCache->doObjectType[cachedTrust] = cacheTrust; + rvCache->doObjectType[cachedCRLs] = cacheCRLs; + rvCache->token = token; /* cache goes away with token */ + return rvCache; +loser: + return (nssTokenObjectCache *)NULL; +} + +static void +clear_cache +( + nssTokenObjectCache *cache +) +{ + nssCryptokiObjectAndAttributes **oa; + PRUint32 objectType; + for (objectType = cachedCerts; objectType <= cachedCRLs; objectType++) { + if (!cache->objects[objectType]) { + continue; + } + for (oa = cache->objects[objectType]; *oa; oa++) { + /* prevent the token from being destroyed */ + (*oa)->object->token = NULL; + nssCryptokiObject_Destroy((*oa)->object); + nssArena_Destroy((*oa)->arena); + } + nss_ZFreeIf(cache->objects[objectType]); + cache->objects[objectType] = NULL; + cache->searchedObjectType[objectType] = PR_FALSE; + } +} + +NSS_IMPLEMENT void +nssTokenObjectCache_Clear +( + nssTokenObjectCache *cache +) +{ + if (cache) { + clear_cache(cache); + } +} + +NSS_IMPLEMENT void +nssTokenObjectCache_Destroy +( + nssTokenObjectCache *cache +) +{ + if (cache) { + clear_cache(cache); + PZ_DestroyLock(cache->lock); + nss_ZFreeIf(cache); + } +} + +NSS_IMPLEMENT PRBool +nssTokenObjectCache_HaveObjectClass +( + nssTokenObjectCache *cache, + CK_OBJECT_CLASS objclass +) +{ + PRBool haveIt; + PZ_Lock(cache->lock); + switch (objclass) { + case CKO_CERTIFICATE: haveIt = cache->doObjectType[cachedCerts]; break; + case CKO_NETSCAPE_TRUST: haveIt = cache->doObjectType[cachedTrust]; break; + case CKO_NETSCAPE_CRL: haveIt = cache->doObjectType[cachedCRLs]; break; + default: haveIt = PR_FALSE; + } + PZ_Unlock(cache->lock); + return haveIt; +} + +static nssCryptokiObjectAndAttributes ** +create_object_array +( + nssCryptokiObject **objects, + PRBool *doObjects, + PRUint32 *numObjects, + PRStatus *status +) +{ + nssCryptokiObject **op = objects; + nssCryptokiObjectAndAttributes **rvOandA = NULL; + *numObjects = 0; + /* There are no objects for this type */ + if (!objects) { + return (nssCryptokiObjectAndAttributes **)NULL; + } + while (*op++) (*numObjects)++; + if (*numObjects == MAX_LOCAL_CACHE_OBJECTS) { + /* Hit the maximum allowed, so don't use a cache (there are + * too many objects to make caching worthwhile, presumably, if + * the token can handle that many objects, it can handle searching. + */ + *doObjects = PR_FALSE; + *status = PR_FAILURE; + *numObjects = 0; + } else if (*numObjects > 0) { + rvOandA = nss_ZNEWARRAY(NULL, + nssCryptokiObjectAndAttributes *, + *numObjects + 1); + *status = rvOandA ? PR_SUCCESS : PR_FALSE; + } + return rvOandA; +} + +static nssCryptokiObjectAndAttributes * +create_object +( + nssCryptokiObject *object, + CK_ATTRIBUTE_TYPE *types, + PRUint32 numTypes, + PRStatus *status +) +{ + PRUint32 j; + NSSArena *arena; + NSSSlot *slot = NULL; + nssSession *session = NULL; + nssCryptokiObjectAndAttributes *rvCachedObject = NULL; + + slot = nssToken_GetSlot(object->token); + session = nssToken_GetDefaultSession(object->token); + + arena = nssArena_Create(); + if (!arena) { + nssSlot_Destroy(slot); + return (nssCryptokiObjectAndAttributes *)NULL; + } + rvCachedObject = nss_ZNEW(arena, nssCryptokiObjectAndAttributes); + if (!rvCachedObject) { + goto loser; + } + rvCachedObject->arena = arena; + /* The cache is tied to the token, and therefore the objects + * in it should not hold references to the token. + */ + nssToken_Destroy(object->token); + rvCachedObject->object = object; + rvCachedObject->attributes = nss_ZNEWARRAY(arena, CK_ATTRIBUTE, numTypes); + if (!rvCachedObject->attributes) { + goto loser; + } + for (j=0; j<numTypes; j++) { + rvCachedObject->attributes[j].type = types[j]; + } + *status = nssCKObject_GetAttributes(object->handle, + rvCachedObject->attributes, + numTypes, + arena, + session, + slot); + if (*status != PR_SUCCESS) { + goto loser; + } + rvCachedObject->numAttributes = numTypes; + *status = PR_SUCCESS; + if (slot) { + nssSlot_Destroy(slot); + } + return rvCachedObject; +loser: + *status = PR_FAILURE; + if (slot) { + nssSlot_Destroy(slot); + } + nssArena_Destroy(arena); + return (nssCryptokiObjectAndAttributes *)NULL; +} + +/* + * + * State diagram for cache: + * + * token !present token removed + * +-------------------------+<----------------------+ + * | ^ | + * v | | + * +----------+ slot friendly | token present +----------+ + * | cache | -----------------> % ---------------> | cache | + * | unloaded | | loaded | + * +----------+ +----------+ + * ^ | ^ | + * | | slot !friendly slot logged in | | + * | +-----------------------> % ----------------------+ | + * | | | + * | slot logged out v slot !friendly | + * +-----------------------------+<--------------------------+ + * + */ +static PRBool +search_for_objects +( + nssTokenObjectCache *cache +) +{ + PRBool doSearch = PR_FALSE; + NSSSlot *slot = nssToken_GetSlot(cache->token); + if (!nssSlot_IsTokenPresent(slot)) { + /* The token is no longer present, destroy any cached objects */ + /* clear_cache(cache); */ + nssSlot_Destroy(slot); + return PR_FALSE; + } + /* Handle non-friendly slots (slots which require login for objects) */ + if (!nssSlot_IsFriendly(slot)) { + if (nssSlot_IsLoggedIn(slot)) { + /* Either no state change, or went from !logged in -> logged in */ + cache->loggedIn = PR_TRUE; + doSearch = PR_TRUE; + } else { + if (cache->loggedIn) { + /* went from logged in -> !logged in, destroy cached objects */ + clear_cache(cache); + cache->loggedIn = PR_FALSE; + } /* else no state change, still not logged in, so exit */ + } + } else { + /* slot is friendly, thus always available for search */ + doSearch = PR_TRUE; + } + nssSlot_Destroy(slot); + return doSearch; +} + +static nssCryptokiObjectAndAttributes * +create_cert +( + nssCryptokiObject *object, + PRStatus *status +) +{ + CK_ATTRIBUTE_TYPE certAttr[] = { + CKA_CLASS, + CKA_TOKEN, + CKA_LABEL, + CKA_CERTIFICATE_TYPE, + CKA_ID, + CKA_VALUE, + CKA_ISSUER, + CKA_SERIAL_NUMBER, + CKA_SUBJECT, + CKA_NETSCAPE_EMAIL + }; + PRUint32 numCertAttr = sizeof(certAttr) / sizeof(certAttr[0]); + return create_object(object, certAttr, numCertAttr, status); +} + +static PRStatus +get_token_certs_for_cache +( + nssTokenObjectCache *cache +) +{ + PRStatus status; + nssCryptokiObject **objects; + PRBool *doIt = &cache->doObjectType[cachedCerts]; + PRUint32 i, numObjects; + + if (!search_for_objects(cache) || + cache->searchedObjectType[cachedCerts] || + !cache->doObjectType[cachedCerts]) + { + /* Either there was a state change that prevents a search + * (token removed or logged out), or the search was already done, + * or certs are not being cached. + */ + return PR_SUCCESS; + } + objects = nssToken_FindCertificates(cache->token, NULL, + nssTokenSearchType_TokenForced, + MAX_LOCAL_CACHE_OBJECTS, &status); + if (status != PR_SUCCESS) { + return status; + } + cache->objects[cachedCerts] = create_object_array(objects, + doIt, + &numObjects, + &status); + if (status != PR_SUCCESS) { + return status; + } + for (i=0; i<numObjects; i++) { + cache->objects[cachedCerts][i] = create_cert(objects[i], &status); + if (status != PR_SUCCESS) { + break; + } + } + if (status == PR_SUCCESS) { + nss_ZFreeIf(objects); + } else { + PRUint32 j; + for (j=0; j<i; j++) { + /* sigh */ + nssToken_AddRef(cache->objects[cachedCerts][i]->object->token); + nssArena_Destroy(cache->objects[cachedCerts][i]->arena); + } + nssCryptokiObjectArray_Destroy(objects); + } + cache->searchedObjectType[cachedCerts] = PR_TRUE; + return status; +} + +static nssCryptokiObjectAndAttributes * +create_trust +( + nssCryptokiObject *object, + PRStatus *status +) +{ + CK_ATTRIBUTE_TYPE trustAttr[] = { + CKA_CLASS, + CKA_TOKEN, + CKA_LABEL, + CKA_CERT_SHA1_HASH, + CKA_CERT_MD5_HASH, + CKA_ISSUER, + CKA_SUBJECT, + CKA_TRUST_SERVER_AUTH, + CKA_TRUST_CLIENT_AUTH, + CKA_TRUST_EMAIL_PROTECTION, + CKA_TRUST_CODE_SIGNING + }; + PRUint32 numTrustAttr = sizeof(trustAttr) / sizeof(trustAttr[0]); + return create_object(object, trustAttr, numTrustAttr, status); +} + +static PRStatus +get_token_trust_for_cache +( + nssTokenObjectCache *cache +) +{ + PRStatus status; + nssCryptokiObject **objects; + PRBool *doIt = &cache->doObjectType[cachedTrust]; + PRUint32 i, numObjects; + + if (!search_for_objects(cache) || + cache->searchedObjectType[cachedTrust] || + !cache->doObjectType[cachedTrust]) + { + /* Either there was a state change that prevents a search + * (token removed or logged out), or the search was already done, + * or trust is not being cached. + */ + return PR_SUCCESS; + } + objects = nssToken_FindTrustObjects(cache->token, NULL, + nssTokenSearchType_TokenForced, + MAX_LOCAL_CACHE_OBJECTS, &status); + if (status != PR_SUCCESS) { + return status; + } + cache->objects[cachedTrust] = create_object_array(objects, + doIt, + &numObjects, + &status); + if (status != PR_SUCCESS) { + return status; + } + for (i=0; i<numObjects; i++) { + cache->objects[cachedTrust][i] = create_trust(objects[i], &status); + if (status != PR_SUCCESS) { + break; + } + } + if (status == PR_SUCCESS) { + nss_ZFreeIf(objects); + } else { + PRUint32 j; + for (j=0; j<i; j++) { + /* sigh */ + nssToken_AddRef(cache->objects[cachedTrust][i]->object->token); + nssArena_Destroy(cache->objects[cachedTrust][i]->arena); + } + nssCryptokiObjectArray_Destroy(objects); + } + cache->searchedObjectType[cachedTrust] = PR_TRUE; + return status; +} + +static nssCryptokiObjectAndAttributes * +create_crl +( + nssCryptokiObject *object, + PRStatus *status +) +{ + CK_ATTRIBUTE_TYPE crlAttr[] = { + CKA_CLASS, + CKA_TOKEN, + CKA_LABEL, + CKA_VALUE, + CKA_SUBJECT, + CKA_NETSCAPE_KRL, + CKA_NETSCAPE_URL + }; + PRUint32 numCRLAttr = sizeof(crlAttr) / sizeof(crlAttr[0]); + return create_object(object, crlAttr, numCRLAttr, status); +} + +static PRStatus +get_token_crls_for_cache +( + nssTokenObjectCache *cache +) +{ + PRStatus status; + nssCryptokiObject **objects; + PRBool *doIt = &cache->doObjectType[cachedCRLs]; + PRUint32 i, numObjects; + + if (!search_for_objects(cache) || + cache->searchedObjectType[cachedCRLs] || + !cache->doObjectType[cachedCRLs]) + { + /* Either there was a state change that prevents a search + * (token removed or logged out), or the search was already done, + * or CRLs are not being cached. + */ + return PR_SUCCESS; + } + objects = nssToken_FindCRLs(cache->token, NULL, + nssTokenSearchType_TokenForced, + MAX_LOCAL_CACHE_OBJECTS, &status); + if (status != PR_SUCCESS) { + return status; + } + cache->objects[cachedCRLs] = create_object_array(objects, + doIt, + &numObjects, + &status); + if (status != PR_SUCCESS) { + return status; + } + for (i=0; i<numObjects; i++) { + cache->objects[cachedCRLs][i] = create_crl(objects[i], &status); + if (status != PR_SUCCESS) { + break; + } + } + if (status == PR_SUCCESS) { + nss_ZFreeIf(objects); + } else { + PRUint32 j; + for (j=0; j<i; j++) { + /* sigh */ + nssToken_AddRef(cache->objects[cachedCRLs][i]->object->token); + nssArena_Destroy(cache->objects[cachedCRLs][i]->arena); + } + nssCryptokiObjectArray_Destroy(objects); + } + cache->searchedObjectType[cachedCRLs] = PR_TRUE; + return status; +} + +static nssCryptokiObject ** +find_objects_in_array +( + nssCryptokiObjectAndAttributes **objArray, + CK_ATTRIBUTE_PTR ot, + CK_ULONG otlen, + PRUint32 maximumOpt +) +{ + PRIntn oi; + PRUint32 i, j; + PRBool match; + NSSArena *arena; + PRUint32 size = 8; + PRUint32 numMatches = 0; + nssCryptokiObject **objects = NULL; + nssCryptokiObjectAndAttributes **matches = NULL; + if (!objArray) { + return (nssCryptokiObject **)NULL; + } + arena = nssArena_Create(); + if (!arena) { + return (nssCryptokiObject **)NULL; + } + matches = nss_ZNEWARRAY(arena, nssCryptokiObjectAndAttributes *, size); + if (!matches) { + goto loser; + } + if (maximumOpt == 0) maximumOpt = ~0; + for (; *objArray && numMatches < maximumOpt; objArray++) { + nssCryptokiObjectAndAttributes *obj = *objArray; + for (i=0; i<otlen; i++) { + for (j=0; j<obj->numAttributes; j++) { + if (ot[i].type == obj->attributes[j].type) { + if (ot[i].ulValueLen == obj->attributes[j].ulValueLen && + nsslibc_memequal(ot[i].pValue, + obj->attributes[j].pValue, + ot[i].ulValueLen, NULL)) + { + match = PR_TRUE; + } else { + match = PR_FALSE; + } + break; + } + } + if (j == obj->numAttributes || !match) { + break; + } + } + if (match) { + matches[numMatches++] = obj; + if (numMatches == size) { + size *= 2; + matches = nss_ZREALLOCARRAY(matches, + nssCryptokiObjectAndAttributes *, + size); + if (!matches) { + goto loser; + } + } + } + } + if (numMatches > 0) { + objects = nss_ZNEWARRAY(NULL, nssCryptokiObject *, numMatches + 1); + if (!objects) { + goto loser; + } + for (oi=0; oi<(PRIntn)numMatches; oi++) { + objects[oi] = nssCryptokiObject_Clone(matches[oi]->object); + if (!objects[oi]) { + goto loser; + } + } + } + nssArena_Destroy(arena); + return objects; +loser: + if (objects) { + for (--oi; oi>=0; --oi) { + nssCryptokiObject_Destroy(objects[oi]); + } + } + nssArena_Destroy(arena); + return (nssCryptokiObject **)NULL; +} + +NSS_IMPLEMENT nssCryptokiObject ** +nssTokenObjectCache_FindObjectsByTemplate +( + nssTokenObjectCache *cache, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR otemplate, + CK_ULONG otlen, + PRUint32 maximumOpt, + PRStatus *statusOpt +) +{ + PRStatus status = PR_FAILURE; + nssCryptokiObject **rvObjects = NULL; + PZ_Lock(cache->lock); + switch (objclass) { + case CKO_CERTIFICATE: + if (cache->doObjectType[cachedCerts]) { + status = get_token_certs_for_cache(cache); + if (status != PR_SUCCESS) { + goto finish; + } + rvObjects = find_objects_in_array(cache->objects[cachedCerts], + otemplate, otlen, maximumOpt); + } + break; + case CKO_NETSCAPE_TRUST: + if (cache->doObjectType[cachedTrust]) { + status = get_token_trust_for_cache(cache); + if (status != PR_SUCCESS) { + goto finish; + } + rvObjects = find_objects_in_array(cache->objects[cachedTrust], + otemplate, otlen, maximumOpt); + } + break; + case CKO_NETSCAPE_CRL: + if (cache->doObjectType[cachedCRLs]) { + status = get_token_crls_for_cache(cache); + if (status != PR_SUCCESS) { + goto finish; + } + rvObjects = find_objects_in_array(cache->objects[cachedCRLs], + otemplate, otlen, maximumOpt); + } + break; + default: break; + } +finish: + PZ_Unlock(cache->lock); + if (statusOpt) { + *statusOpt = status; + } + return rvObjects; +} + +static PRBool +cache_available_for_object_type +( + nssTokenObjectCache *cache, + PRUint32 objectType +) +{ + if (!cache->doObjectType[objectType]) { + /* not caching this object kind */ + return PR_FALSE; + } + if (!cache->searchedObjectType[objectType]) { + /* objects are not cached yet */ + return PR_FALSE; + } + if (!search_for_objects(cache)) { + /* not logged in or removed */ + return PR_FALSE; + } + return PR_TRUE; +} + +NSS_IMPLEMENT PRStatus +nssTokenObjectCache_GetObjectAttributes +( + nssTokenObjectCache *cache, + NSSArena *arenaOpt, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR atemplate, + CK_ULONG atlen +) +{ + PRUint32 i, j; + NSSArena *arena = NULL; + nssArenaMark *mark = NULL; + nssCryptokiObjectAndAttributes *cachedOA = NULL; + nssCryptokiObjectAndAttributes **oa = NULL; + PRUint32 objectType; + PZ_Lock(cache->lock); + switch (objclass) { + case CKO_CERTIFICATE: objectType = cachedCerts; break; + case CKO_NETSCAPE_TRUST: objectType = cachedTrust; break; + case CKO_NETSCAPE_CRL: objectType = cachedCRLs; break; + default: goto loser; + } + if (!cache_available_for_object_type(cache, objectType)) { + goto loser; + } + oa = cache->objects[objectType]; + if (!oa) { + goto loser; + } + for (; *oa; oa++) { + if (nssCryptokiObject_Equal((*oa)->object, object)) { + cachedOA = *oa; + break; + } + } + if (!cachedOA) { + goto loser; /* don't have this object */ + } + if (arenaOpt) { + arena = arenaOpt; + mark = nssArena_Mark(arena); + } + for (i=0; i<atlen; i++) { + for (j=0; j<cachedOA->numAttributes; j++) { + if (atemplate[i].type == cachedOA->attributes[j].type) { + CK_ATTRIBUTE_PTR attr = &cachedOA->attributes[j]; + if (cachedOA->attributes[j].ulValueLen == 0 || + cachedOA->attributes[j].ulValueLen == (CK_ULONG)-1) + { + break; /* invalid attribute */ + } + if (atemplate[i].ulValueLen > 0) { + if (atemplate[i].pValue == NULL || + atemplate[i].ulValueLen < attr->ulValueLen) + { + goto loser; + } + } else { + atemplate[i].pValue = nss_ZAlloc(arena, attr->ulValueLen); + if (!atemplate[i].pValue) { + goto loser; + } + } + nsslibc_memcpy(atemplate[i].pValue, + attr->pValue, attr->ulValueLen); + atemplate[i].ulValueLen = attr->ulValueLen; + break; + } + } + if (j == cachedOA->numAttributes) { + atemplate[i].ulValueLen = (CK_ULONG)-1; + } + } + PZ_Unlock(cache->lock); + if (mark) { + nssArena_Unmark(arena, mark); + } + return PR_SUCCESS; +loser: + PZ_Unlock(cache->lock); + if (mark) { + nssArena_Release(arena, mark); + } + return PR_FAILURE; +} + +NSS_IMPLEMENT PRStatus +nssTokenObjectCache_ImportObject +( + nssTokenObjectCache *cache, + nssCryptokiObject *object, + CK_OBJECT_CLASS objclass, + CK_ATTRIBUTE_PTR ot, + CK_ULONG otlen +) +{ + PRStatus status = PR_SUCCESS; + PRUint32 count; + nssCryptokiObjectAndAttributes **oa, ***otype; + PRUint32 objectType; + PRBool haveIt = PR_FALSE; + + PZ_Lock(cache->lock); + switch (objclass) { + case CKO_CERTIFICATE: objectType = cachedCerts; break; + case CKO_NETSCAPE_TRUST: objectType = cachedTrust; break; + case CKO_NETSCAPE_CRL: objectType = cachedCRLs; break; + default: + PZ_Unlock(cache->lock); + return PR_SUCCESS; /* don't need to import it here */ + } + if (!cache_available_for_object_type(cache, objectType)) { + PZ_Unlock(cache->lock); + return PR_SUCCESS; /* cache not active, ignored */ + } + count = 0; + otype = &cache->objects[objectType]; /* index into array of types */ + oa = *otype; /* the array of objects for this type */ + while (oa && *oa) { + if (nssCryptokiObject_Equal((*oa)->object, object)) { + haveIt = PR_TRUE; + break; + } + count++; + oa++; + } + if (haveIt) { + /* Destroy the old entry */ + (*oa)->object->token = NULL; + nssCryptokiObject_Destroy((*oa)->object); + nssArena_Destroy((*oa)->arena); + } else { + /* Create space for a new entry */ + if (count > 0) { + *otype = nss_ZREALLOCARRAY(*otype, + nssCryptokiObjectAndAttributes *, + count + 2); + } else { + *otype = nss_ZNEWARRAY(NULL, nssCryptokiObjectAndAttributes *, 2); + } + } + if (*otype) { + nssCryptokiObject *copyObject = nssCryptokiObject_Clone(object); + if (objectType == cachedCerts) { + (*otype)[count] = create_cert(copyObject, &status); + } else if (objectType == cachedTrust) { + (*otype)[count] = create_trust(copyObject, &status); + } else if (objectType == cachedCRLs) { + (*otype)[count] = create_crl(copyObject, &status); + } + } else { + status = PR_FAILURE; + } + PZ_Unlock(cache->lock); + return status; +} + +NSS_IMPLEMENT void +nssTokenObjectCache_RemoveObject +( + nssTokenObjectCache *cache, + nssCryptokiObject *object +) +{ + PRUint32 oType; + nssCryptokiObjectAndAttributes **oa, **swp = NULL; + PZ_Lock(cache->lock); + for (oType=0; oType<3; oType++) { + if (!cache_available_for_object_type(cache, oType) || + !cache->objects[oType]) + { + continue; + } + for (oa = cache->objects[oType]; *oa; oa++) { + if (nssCryptokiObject_Equal((*oa)->object, object)) { + swp = oa; /* the entry to remove */ + while (oa[1]) oa++; /* go to the tail */ + (*swp)->object->token = NULL; + nssCryptokiObject_Destroy((*swp)->object); + nssArena_Destroy((*swp)->arena); /* destroy it */ + *swp = *oa; /* swap the last with the removed */ + *oa = NULL; /* null-terminate the array */ + break; + } + } + if (swp) { + break; + } + } + if ((oType <3) && + cache->objects[oType] && cache->objects[oType][0] == NULL) { + nss_ZFreeIf(cache->objects[oType]); /* no entries remaining */ + cache->objects[oType] = NULL; + } + PZ_Unlock(cache->lock); +} + +/* XXX of course this doesn't belong here */ +NSS_IMPLEMENT NSSAlgorithmAndParameters * +NSSAlgorithmAndParameters_CreateSHA1Digest +( + NSSArena *arenaOpt +) +{ + NSSAlgorithmAndParameters *rvAP = NULL; + rvAP = nss_ZNEW(arenaOpt, NSSAlgorithmAndParameters); + if (rvAP) { + rvAP->mechanism.mechanism = CKM_SHA_1; + rvAP->mechanism.pParameter = NULL; + rvAP->mechanism.ulParameterLen = 0; + } + return rvAP; +} + +NSS_IMPLEMENT NSSAlgorithmAndParameters * +NSSAlgorithmAndParameters_CreateMD5Digest +( + NSSArena *arenaOpt +) +{ + NSSAlgorithmAndParameters *rvAP = NULL; + rvAP = nss_ZNEW(arenaOpt, NSSAlgorithmAndParameters); + if (rvAP) { + rvAP->mechanism.mechanism = CKM_MD5; + rvAP->mechanism.pParameter = NULL; + rvAP->mechanism.ulParameterLen = 0; + } + return rvAP; +} + diff --git a/security/nss/lib/dev/manifest.mn b/security/nss/lib/dev/manifest.mn new file mode 100644 index 000000000..effab4805 --- /dev/null +++ b/security/nss/lib/dev/manifest.mn @@ -0,0 +1,66 @@ +# +# The contents of this file are subject to the Mozilla Public +# License Version 1.1 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.mozilla.org/MPL/ +# +# Software distributed under the License is distributed on an "AS +# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or +# implied. See the License for the specific language governing +# rights and limitations under the License. +# +# The Original Code is the Netscape security libraries. +# +# The Initial Developer of the Original Code is Netscape +# Communications Corporation. Portions created by Netscape are +# Copyright (C) 1994-2000 Netscape Communications Corporation. All +# Rights Reserved. +# +# Contributor(s): +# +# Alternatively, the contents of this file may be used under the +# terms of the GNU General Public License Version 2 or later (the +# "GPL"), in which case the provisions of the GPL are applicable +# instead of those above. If you wish to allow use of your +# version of this file only under the terms of the GPL and not to +# allow others to use your version of this file under the MPL, +# indicate your decision by deleting the provisions above and +# replace them with the notice and other provisions required by +# the GPL. If you do not delete the provisions above, a recipient +# may use your version of this file under either the MPL or the +# GPL. +# +MANIFEST_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$" + +CORE_DEPTH = ../../.. + +PRIVATE_EXPORTS = \ + ckhelper.h \ + devt.h \ + dev.h \ + nssdevt.h \ + nssdev.h \ + $(NULL) + +EXPORTS = \ + $(NULL) + +MODULE = security + +CSRCS = \ + devmod.c \ + devslot.c \ + devtoken.c \ + devutil.c \ + ckhelper.c \ + $(NULL) + +# here is where the 3.4 glue code is added +ifndef PURE_STAN_BUILD +DEFINES = -DNSS_3_4_CODE +PRIVATE_EXPORTS += devm.h devtm.h +endif + +REQUIRES = security nspr + +LIBRARY_NAME = nssdev diff --git a/security/nss/lib/dev/nssdev.h b/security/nss/lib/dev/nssdev.h new file mode 100644 index 000000000..7b219adfe --- /dev/null +++ b/security/nss/lib/dev/nssdev.h @@ -0,0 +1,72 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef NSSDEV_H +#define NSSDEV_H + +#ifdef DEBUG +static const char NSSDEV_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ +/* + * nssdev.h + * + * High-level methods for interaction with cryptoki devices + */ + +#ifndef NSSDEVT_H +#include "nssdevt.h" +#endif /* NSSDEVT_H */ + +PR_BEGIN_EXTERN_C + +/* NSSAlgorithmAndParameters + * + * NSSAlgorithmAndParameters_CreateSHA1Digest + * NSSAlgorithmAndParameters_CreateMD5Digest + */ + +NSS_EXTERN NSSAlgorithmAndParameters * +NSSAlgorithmAndParameters_CreateSHA1Digest +( + NSSArena *arenaOpt +); + +NSS_EXTERN NSSAlgorithmAndParameters * +NSSAlgorithmAndParameters_CreateMD5Digest +( + NSSArena *arenaOpt +); + +PR_END_EXTERN_C + +#endif /* DEV_H */ diff --git a/security/nss/lib/dev/nssdevt.h b/security/nss/lib/dev/nssdevt.h new file mode 100644 index 000000000..a603ce545 --- /dev/null +++ b/security/nss/lib/dev/nssdevt.h @@ -0,0 +1,69 @@ +/* + * The contents of this file are subject to the Mozilla Public + * License Version 1.1 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS + * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or + * implied. See the License for the specific language governing + * rights and limitations under the License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is Netscape + * Communications Corporation. Portions created by Netscape are + * Copyright (C) 1994-2000 Netscape Communications Corporation. All + * Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the + * terms of the GNU General Public License Version 2 or later (the + * "GPL"), in which case the provisions of the GPL are applicable + * instead of those above. If you wish to allow use of your + * version of this file only under the terms of the GPL and not to + * allow others to use your version of this file under the MPL, + * indicate your decision by deleting the provisions above and + * replace them with the notice and other provisions required by + * the GPL. If you do not delete the provisions above, a recipient + * may use your version of this file under either the MPL or the + * GPL. + */ + +#ifndef NSSDEVT_H +#define NSSDEVT_H + +#ifdef DEBUG +static const char NSSDEVT_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"; +#endif /* DEBUG */ + +/* + * nssdevt.h + * + * This file contains definitions for the low-level cryptoki devices. + */ + +#ifndef NSSBASET_H +#include "nssbaset.h" +#endif /* NSSBASET_H */ + +#ifndef NSSPKIT_H +#include "nsspkit.h" +#endif /* NSSPKIT_H */ + +PR_BEGIN_EXTERN_C + +/* + * NSSModule and NSSSlot -- placeholders for the PKCS#11 types + */ + +typedef struct NSSModuleStr NSSModule; + +typedef struct NSSSlotStr NSSSlot; + +typedef struct NSSTokenStr NSSToken; + +PR_END_EXTERN_C + +#endif /* NSSDEVT_H */ |